Home | History | Annotate | Download | only in dist
      1 /******************************************************************************
      2 ** This file is an amalgamation of many separate C source files from SQLite
      3 ** version 3.7.4.  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% or more are commonly seen when SQLite is compiled as a single
      8 ** translation unit.
      9 **
     10 ** This file is all you need to compile SQLite.  To use SQLite in other
     11 ** programs, you need this file and the "sqlite3.h" header file that defines
     12 ** the programming interface to the SQLite library.  (If you do not have
     13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
     14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
     15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
     16 ** if you want a wrapper to interface SQLite with your choice of programming
     17 ** language. The code for the "sqlite3" command-line shell is also in a
     18 ** separate file. This file contains only code for the core SQLite library.
     19 */
     20 #define SQLITE_CORE 1
     21 #define SQLITE_AMALGAMATION 1
     22 #ifndef SQLITE_PRIVATE
     23 # define SQLITE_PRIVATE static
     24 #endif
     25 #ifndef SQLITE_API
     26 # define SQLITE_API
     27 #endif
     28 // Begin Android Add
     29 #define fdatasync fsync
     30 #undef __APPLE__
     31 // End Android Add
     32 /************** Begin file sqliteInt.h ***************************************/
     33 /*
     34 ** 2001 September 15
     35 **
     36 ** The author disclaims copyright to this source code.  In place of
     37 ** a legal notice, here is a blessing:
     38 **
     39 **    May you do good and not evil.
     40 **    May you find forgiveness for yourself and forgive others.
     41 **    May you share freely, never taking more than you give.
     42 **
     43 *************************************************************************
     44 ** Internal interface definitions for SQLite.
     45 **
     46 */
     47 #ifndef _SQLITEINT_H_
     48 #define _SQLITEINT_H_
     49 
     50 /*
     51 ** These #defines should enable >2GB file support on POSIX if the
     52 ** underlying operating system supports it.  If the OS lacks
     53 ** large file support, or if the OS is windows, these should be no-ops.
     54 **
     55 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
     56 ** system #includes.  Hence, this block of code must be the very first
     57 ** code in all source files.
     58 **
     59 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
     60 ** on the compiler command line.  This is necessary if you are compiling
     61 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
     62 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
     63 ** without this option, LFS is enable.  But LFS does not exist in the kernel
     64 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
     65 ** portability you should omit LFS.
     66 **
     67 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
     68 */
     69 #ifndef SQLITE_DISABLE_LFS
     70 # define _LARGE_FILE       1
     71 # ifndef _FILE_OFFSET_BITS
     72 #   define _FILE_OFFSET_BITS 64
     73 # endif
     74 # define _LARGEFILE_SOURCE 1
     75 #endif
     76 
     77 /*
     78 ** Include the configuration header output by 'configure' if we're using the
     79 ** autoconf-based build
     80 */
     81 #ifdef _HAVE_SQLITE_CONFIG_H
     82 #include "config.h"
     83 #endif
     84 
     85 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
     86 /************** Begin file sqliteLimit.h *************************************/
     87 /*
     88 ** 2007 May 7
     89 **
     90 ** The author disclaims copyright to this source code.  In place of
     91 ** a legal notice, here is a blessing:
     92 **
     93 **    May you do good and not evil.
     94 **    May you find forgiveness for yourself and forgive others.
     95 **    May you share freely, never taking more than you give.
     96 **
     97 *************************************************************************
     98 **
     99 ** This file defines various limits of what SQLite can process.
    100 */
    101 
    102 /*
    103 ** The maximum length of a TEXT or BLOB in bytes.   This also
    104 ** limits the size of a row in a table or index.
    105 **
    106 ** The hard limit is the ability of a 32-bit signed integer
    107 ** to count the size: 2^31-1 or 2147483647.
    108 */
    109 #ifndef SQLITE_MAX_LENGTH
    110 # define SQLITE_MAX_LENGTH 1000000000
    111 #endif
    112 
    113 /*
    114 ** This is the maximum number of
    115 **
    116 **    * Columns in a table
    117 **    * Columns in an index
    118 **    * Columns in a view
    119 **    * Terms in the SET clause of an UPDATE statement
    120 **    * Terms in the result set of a SELECT statement
    121 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
    122 **    * Terms in the VALUES clause of an INSERT statement
    123 **
    124 ** The hard upper limit here is 32676.  Most database people will
    125 ** tell you that in a well-normalized database, you usually should
    126 ** not have more than a dozen or so columns in any table.  And if
    127 ** that is the case, there is no point in having more than a few
    128 ** dozen values in any of the other situations described above.
    129 */
    130 #ifndef SQLITE_MAX_COLUMN
    131 # define SQLITE_MAX_COLUMN 2000
    132 #endif
    133 
    134 /*
    135 ** The maximum length of a single SQL statement in bytes.
    136 **
    137 ** It used to be the case that setting this value to zero would
    138 ** turn the limit off.  That is no longer true.  It is not possible
    139 ** to turn this limit off.
    140 */
    141 #ifndef SQLITE_MAX_SQL_LENGTH
    142 # define SQLITE_MAX_SQL_LENGTH 1000000000
    143 #endif
    144 
    145 /*
    146 ** The maximum depth of an expression tree. This is limited to
    147 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
    148 ** want to place more severe limits on the complexity of an
    149 ** expression.
    150 **
    151 ** A value of 0 used to mean that the limit was not enforced.
    152 ** But that is no longer true.  The limit is now strictly enforced
    153 ** at all times.
    154 */
    155 #ifndef SQLITE_MAX_EXPR_DEPTH
    156 # define SQLITE_MAX_EXPR_DEPTH 1000
    157 #endif
    158 
    159 /*
    160 ** The maximum number of terms in a compound SELECT statement.
    161 ** The code generator for compound SELECT statements does one
    162 ** level of recursion for each term.  A stack overflow can result
    163 ** if the number of terms is too large.  In practice, most SQL
    164 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
    165 ** any limit on the number of terms in a compount SELECT.
    166 */
    167 #ifndef SQLITE_MAX_COMPOUND_SELECT
    168 # define SQLITE_MAX_COMPOUND_SELECT 500
    169 #endif
    170 
    171 /*
    172 ** The maximum number of opcodes in a VDBE program.
    173 ** Not currently enforced.
    174 */
    175 #ifndef SQLITE_MAX_VDBE_OP
    176 # define SQLITE_MAX_VDBE_OP 25000
    177 #endif
    178 
    179 /*
    180 ** The maximum number of arguments to an SQL function.
    181 */
    182 #ifndef SQLITE_MAX_FUNCTION_ARG
    183 # define SQLITE_MAX_FUNCTION_ARG 127
    184 #endif
    185 
    186 /*
    187 ** The maximum number of in-memory pages to use for the main database
    188 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
    189 */
    190 #ifndef SQLITE_DEFAULT_CACHE_SIZE
    191 # define SQLITE_DEFAULT_CACHE_SIZE  2000
    192 #endif
    193 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
    194 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
    195 #endif
    196 
    197 /*
    198 ** The default number of frames to accumulate in the log file before
    199 ** checkpointing the database in WAL mode.
    200 */
    201 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
    202 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
    203 #endif
    204 
    205 /*
    206 ** The maximum number of attached databases.  This must be between 0
    207 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
    208 ** is used internally to track attached databases.
    209 */
    210 #ifndef SQLITE_MAX_ATTACHED
    211 # define SQLITE_MAX_ATTACHED 10
    212 #endif
    213 
    214 
    215 /*
    216 ** The maximum value of a ?nnn wildcard that the parser will accept.
    217 */
    218 #ifndef SQLITE_MAX_VARIABLE_NUMBER
    219 # define SQLITE_MAX_VARIABLE_NUMBER 999
    220 #endif
    221 
    222 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
    223 ** imposed by the use of 16-bit offsets within each page.
    224 **
    225 ** Earlier versions of SQLite allowed the user to change this value at
    226 ** compile time. This is no longer permitted, on the grounds that it creates
    227 ** a library that is technically incompatible with an SQLite library
    228 ** compiled with a different limit. If a process operating on a database
    229 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
    230 ** compiled with the default page-size limit will not be able to rollback
    231 ** the aborted transaction. This could lead to database corruption.
    232 */
    233 #ifdef SQLITE_MAX_PAGE_SIZE
    234 # undef SQLITE_MAX_PAGE_SIZE
    235 #endif
    236 #define SQLITE_MAX_PAGE_SIZE 65536
    237 
    238 
    239 /*
    240 ** The default size of a database page.
    241 */
    242 #ifndef SQLITE_DEFAULT_PAGE_SIZE
    243 # define SQLITE_DEFAULT_PAGE_SIZE 1024
    244 #endif
    245 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    246 # undef SQLITE_DEFAULT_PAGE_SIZE
    247 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    248 #endif
    249 
    250 /*
    251 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
    252 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
    253 ** device characteristics (sector-size and atomic write() support),
    254 ** SQLite may choose a larger value. This constant is the maximum value
    255 ** SQLite will choose on its own.
    256 */
    257 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
    258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
    259 #endif
    260 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
    261 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
    262 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
    263 #endif
    264 
    265 
    266 /*
    267 ** Maximum number of pages in one database file.
    268 **
    269 ** This is really just the default value for the max_page_count pragma.
    270 ** This value can be lowered (or raised) at run-time using that the
    271 ** max_page_count macro.
    272 */
    273 #ifndef SQLITE_MAX_PAGE_COUNT
    274 # define SQLITE_MAX_PAGE_COUNT 1073741823
    275 #endif
    276 
    277 /*
    278 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
    279 ** operator.
    280 */
    281 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
    282 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
    283 #endif
    284 
    285 /*
    286 ** Maximum depth of recursion for triggers.
    287 **
    288 ** A value of 1 means that a trigger program will not be able to itself
    289 ** fire any triggers. A value of 0 means that no trigger programs at all
    290 ** may be executed.
    291 */
    292 #ifndef SQLITE_MAX_TRIGGER_DEPTH
    293 # define SQLITE_MAX_TRIGGER_DEPTH 1000
    294 #endif
    295 
    296 /************** End of sqliteLimit.h *****************************************/
    297 /************** Continuing where we left off in sqliteInt.h ******************/
    298 
    299 /* Disable nuisance warnings on Borland compilers */
    300 #if defined(__BORLANDC__)
    301 #pragma warn -rch /* unreachable code */
    302 #pragma warn -ccc /* Condition is always true or false */
    303 #pragma warn -aus /* Assigned value is never used */
    304 #pragma warn -csu /* Comparing signed and unsigned */
    305 #pragma warn -spa /* Suspicious pointer arithmetic */
    306 #endif
    307 
    308 /* Needed for various definitions... */
    309 #ifndef _GNU_SOURCE
    310 # define _GNU_SOURCE
    311 #endif
    312 
    313 /*
    314 ** Include standard header files as necessary
    315 */
    316 #ifdef HAVE_STDINT_H
    317 #include <stdint.h>
    318 #endif
    319 #ifdef HAVE_INTTYPES_H
    320 #include <inttypes.h>
    321 #endif
    322 
    323 /*
    324 ** The number of samples of an index that SQLite takes in order to
    325 ** construct a histogram of the table content when running ANALYZE
    326 ** and with SQLITE_ENABLE_STAT2
    327 */
    328 #define SQLITE_INDEX_SAMPLES 10
    329 
    330 /*
    331 ** The following macros are used to cast pointers to integers and
    332 ** integers to pointers.  The way you do this varies from one compiler
    333 ** to the next, so we have developed the following set of #if statements
    334 ** to generate appropriate macros for a wide range of compilers.
    335 **
    336 ** The correct "ANSI" way to do this is to use the intptr_t type.
    337 ** Unfortunately, that typedef is not available on all compilers, or
    338 ** if it is available, it requires an #include of specific headers
    339 ** that vary from one machine to the next.
    340 **
    341 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
    342 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
    343 ** So we have to define the macros in different ways depending on the
    344 ** compiler.
    345 */
    346 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
    347 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
    348 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
    349 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
    350 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
    351 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
    352 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
    353 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
    354 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
    355 #else                          /* Generates a warning - but it always works */
    356 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
    357 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
    358 #endif
    359 
    360 /*
    361 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
    362 ** 0 means mutexes are permanently disable and the library is never
    363 ** threadsafe.  1 means the library is serialized which is the highest
    364 ** level of threadsafety.  2 means the libary is multithreaded - multiple
    365 ** threads can use SQLite as long as no two threads try to use the same
    366 ** database connection at the same time.
    367 **
    368 ** Older versions of SQLite used an optional THREADSAFE macro.
    369 ** We support that for legacy.
    370 */
    371 #if !defined(SQLITE_THREADSAFE)
    372 #if defined(THREADSAFE)
    373 # define SQLITE_THREADSAFE THREADSAFE
    374 #else
    375 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
    376 #endif
    377 #endif
    378 
    379 /*
    380 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
    381 ** It determines whether or not the features related to
    382 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
    383 ** be overridden at runtime using the sqlite3_config() API.
    384 */
    385 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
    386 # define SQLITE_DEFAULT_MEMSTATUS 1
    387 #endif
    388 
    389 /*
    390 ** Exactly one of the following macros must be defined in order to
    391 ** specify which memory allocation subsystem to use.
    392 **
    393 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
    394 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
    395 **
    396 ** (Historical note:  There used to be several other options, but we've
    397 ** pared it down to just these two.)
    398 **
    399 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
    400 ** the default.
    401 */
    402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
    403 # error "At most one of the following compile-time configuration options\
    404  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
    405 #endif
    406 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
    407 # define SQLITE_SYSTEM_MALLOC 1
    408 #endif
    409 
    410 /*
    411 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
    412 ** sizes of memory allocations below this value where possible.
    413 */
    414 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
    415 # define SQLITE_MALLOC_SOFT_LIMIT 1024
    416 #endif
    417 
    418 /*
    419 ** We need to define _XOPEN_SOURCE as follows in order to enable
    420 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
    421 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
    422 ** so it is omitted there.  See ticket #2673.
    423 **
    424 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
    425 ** implemented on some systems.  So we avoid defining it at all
    426 ** if it is already defined or if it is unneeded because we are
    427 ** not doing a threadsafe build.  Ticket #2681.
    428 **
    429 ** See also ticket #2741.
    430 */
    431 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
    432 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
    433 #endif
    434 
    435 /*
    436 ** The TCL headers are only needed when compiling the TCL bindings.
    437 */
    438 #if defined(SQLITE_TCL) || defined(TCLSH)
    439 # include <tcl.h>
    440 #endif
    441 
    442 /*
    443 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
    444 ** Setting NDEBUG makes the code smaller and run faster.  So the following
    445 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
    446 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
    447 ** feature.
    448 */
    449 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
    450 # define NDEBUG 1
    451 #endif
    452 
    453 /*
    454 ** The testcase() macro is used to aid in coverage testing.  When
    455 ** doing coverage testing, the condition inside the argument to
    456 ** testcase() must be evaluated both true and false in order to
    457 ** get full branch coverage.  The testcase() macro is inserted
    458 ** to help ensure adequate test coverage in places where simple
    459 ** condition/decision coverage is inadequate.  For example, testcase()
    460 ** can be used to make sure boundary values are tested.  For
    461 ** bitmask tests, testcase() can be used to make sure each bit
    462 ** is significant and used at least once.  On switch statements
    463 ** where multiple cases go to the same block of code, testcase()
    464 ** can insure that all cases are evaluated.
    465 **
    466 */
    467 #ifdef SQLITE_COVERAGE_TEST
    468 SQLITE_PRIVATE   void sqlite3Coverage(int);
    469 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
    470 #else
    471 # define testcase(X)
    472 #endif
    473 
    474 /*
    475 ** The TESTONLY macro is used to enclose variable declarations or
    476 ** other bits of code that are needed to support the arguments
    477 ** within testcase() and assert() macros.
    478 */
    479 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
    480 # define TESTONLY(X)  X
    481 #else
    482 # define TESTONLY(X)
    483 #endif
    484 
    485 /*
    486 ** Sometimes we need a small amount of code such as a variable initialization
    487 ** to setup for a later assert() statement.  We do not want this code to
    488 ** appear when assert() is disabled.  The following macro is therefore
    489 ** used to contain that setup code.  The "VVA" acronym stands for
    490 ** "Verification, Validation, and Accreditation".  In other words, the
    491 ** code within VVA_ONLY() will only run during verification processes.
    492 */
    493 #ifndef NDEBUG
    494 # define VVA_ONLY(X)  X
    495 #else
    496 # define VVA_ONLY(X)
    497 #endif
    498 
    499 /*
    500 ** The ALWAYS and NEVER macros surround boolean expressions which
    501 ** are intended to always be true or false, respectively.  Such
    502 ** expressions could be omitted from the code completely.  But they
    503 ** are included in a few cases in order to enhance the resilience
    504 ** of SQLite to unexpected behavior - to make the code "self-healing"
    505 ** or "ductile" rather than being "brittle" and crashing at the first
    506 ** hint of unplanned behavior.
    507 **
    508 ** In other words, ALWAYS and NEVER are added for defensive code.
    509 **
    510 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
    511 ** be true and false so that the unreachable code then specify will
    512 ** not be counted as untested code.
    513 */
    514 #if defined(SQLITE_COVERAGE_TEST)
    515 # define ALWAYS(X)      (1)
    516 # define NEVER(X)       (0)
    517 #elif !defined(NDEBUG)
    518 # define ALWAYS(X)      ((X)?1:(assert(0),0))
    519 # define NEVER(X)       ((X)?(assert(0),1):0)
    520 #else
    521 # define ALWAYS(X)      (X)
    522 # define NEVER(X)       (X)
    523 #endif
    524 
    525 /*
    526 ** Return true (non-zero) if the input is a integer that is too large
    527 ** to fit in 32-bits.  This macro is used inside of various testcase()
    528 ** macros to verify that we have tested SQLite for large-file support.
    529 */
    530 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
    531 
    532 /*
    533 ** The macro unlikely() is a hint that surrounds a boolean
    534 ** expression that is usually false.  Macro likely() surrounds
    535 ** a boolean expression that is usually true.  GCC is able to
    536 ** use these hints to generate better code, sometimes.
    537 */
    538 #if defined(__GNUC__) && 0
    539 # define likely(X)    __builtin_expect((X),1)
    540 # define unlikely(X)  __builtin_expect((X),0)
    541 #else
    542 # define likely(X)    !!(X)
    543 # define unlikely(X)  !!(X)
    544 #endif
    545 
    546 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
    547 /************** Begin file sqlite3.h *****************************************/
    548 /*
    549 ** 2001 September 15
    550 **
    551 ** The author disclaims copyright to this source code.  In place of
    552 ** a legal notice, here is a blessing:
    553 **
    554 **    May you do good and not evil.
    555 **    May you find forgiveness for yourself and forgive others.
    556 **    May you share freely, never taking more than you give.
    557 **
    558 *************************************************************************
    559 ** This header file defines the interface that the SQLite library
    560 ** presents to client programs.  If a C-function, structure, datatype,
    561 ** or constant definition does not appear in this file, then it is
    562 ** not a published API of SQLite, is subject to change without
    563 ** notice, and should not be referenced by programs that use SQLite.
    564 **
    565 ** Some of the definitions that are in this file are marked as
    566 ** "experimental".  Experimental interfaces are normally new
    567 ** features recently added to SQLite.  We do not anticipate changes
    568 ** to experimental interfaces but reserve the right to make minor changes
    569 ** if experience from use "in the wild" suggest such changes are prudent.
    570 **
    571 ** The official C-language API documentation for SQLite is derived
    572 ** from comments in this file.  This file is the authoritative source
    573 ** on how SQLite interfaces are suppose to operate.
    574 **
    575 ** The name of this file under configuration management is "sqlite.h.in".
    576 ** The makefile makes some minor changes to this file (such as inserting
    577 ** the version number) and changes its name to "sqlite3.h" as
    578 ** part of the build process.
    579 */
    580 #ifndef _SQLITE3_H_
    581 #define _SQLITE3_H_
    582 #include <stdarg.h>     /* Needed for the definition of va_list */
    583 
    584 /*
    585 ** Make sure we can call this stuff from C++.
    586 */
    587 #if 0
    588 extern "C" {
    589 #endif
    590 
    591 
    592 /*
    593 ** Add the ability to override 'extern'
    594 */
    595 #ifndef SQLITE_EXTERN
    596 # define SQLITE_EXTERN extern
    597 #endif
    598 
    599 #ifndef SQLITE_API
    600 # define SQLITE_API
    601 #endif
    602 
    603 
    604 /*
    605 ** These no-op macros are used in front of interfaces to mark those
    606 ** interfaces as either deprecated or experimental.  New applications
    607 ** should not use deprecated interfaces - they are support for backwards
    608 ** compatibility only.  Application writers should be aware that
    609 ** experimental interfaces are subject to change in point releases.
    610 **
    611 ** These macros used to resolve to various kinds of compiler magic that
    612 ** would generate warning messages when they were used.  But that
    613 ** compiler magic ended up generating such a flurry of bug reports
    614 ** that we have taken it all out and gone back to using simple
    615 ** noop macros.
    616 */
    617 #define SQLITE_DEPRECATED
    618 #define SQLITE_EXPERIMENTAL
    619 
    620 /*
    621 ** Ensure these symbols were not defined by some previous header file.
    622 */
    623 #ifdef SQLITE_VERSION
    624 # undef SQLITE_VERSION
    625 #endif
    626 #ifdef SQLITE_VERSION_NUMBER
    627 # undef SQLITE_VERSION_NUMBER
    628 #endif
    629 
    630 /*
    631 ** CAPI3REF: Compile-Time Library Version Numbers
    632 **
    633 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
    634 ** evaluates to a string literal that is the SQLite version in the
    635 ** format "X.Y.Z" where X is the major version number (always 3 for
    636 ** SQLite3) and Y is the minor version number and Z is the release number.)^
    637 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
    638 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
    639 ** numbers used in [SQLITE_VERSION].)^
    640 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
    641 ** be larger than the release from which it is derived.  Either Y will
    642 ** be held constant and Z will be incremented or else Y will be incremented
    643 ** and Z will be reset to zero.
    644 **
    645 ** Since version 3.6.18, SQLite source code has been stored in the
    646 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
    647 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
    648 ** a string which identifies a particular check-in of SQLite
    649 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
    650 ** string contains the date and time of the check-in (UTC) and an SHA1
    651 ** hash of the entire source tree.
    652 **
    653 ** See also: [sqlite3_libversion()],
    654 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
    655 ** [sqlite_version()] and [sqlite_source_id()].
    656 */
    657 #define SQLITE_VERSION        "3.7.4"
    658 #define SQLITE_VERSION_NUMBER 3007004
    659 #define SQLITE_SOURCE_ID      "2011-02-23 14:33:31 8609a15dfad23a7c5311b52617d5c4818c0b8d1e"
    660 
    661 /*
    662 ** CAPI3REF: Run-Time Library Version Numbers
    663 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
    664 **
    665 ** These interfaces provide the same information as the [SQLITE_VERSION],
    666 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
    667 ** but are associated with the library instead of the header file.  ^(Cautious
    668 ** programmers might include assert() statements in their application to
    669 ** verify that values returned by these interfaces match the macros in
    670 ** the header, and thus insure that the application is
    671 ** compiled with matching library and header files.
    672 **
    673 ** <blockquote><pre>
    674 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
    675 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
    676 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
    677 ** </pre></blockquote>)^
    678 **
    679 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
    680 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
    681 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
    682 ** function is provided for use in DLLs since DLL users usually do not have
    683 ** direct access to string constants within the DLL.  ^The
    684 ** sqlite3_libversion_number() function returns an integer equal to
    685 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
    686 ** a pointer to a string constant whose value is the same as the
    687 ** [SQLITE_SOURCE_ID] C preprocessor macro.
    688 **
    689 ** See also: [sqlite_version()] and [sqlite_source_id()].
    690 */
    691 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
    692 SQLITE_API const char *sqlite3_libversion(void);
    693 SQLITE_API const char *sqlite3_sourceid(void);
    694 SQLITE_API int sqlite3_libversion_number(void);
    695 
    696 /*
    697 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
    698 **
    699 ** ^The sqlite3_compileoption_used() function returns 0 or 1
    700 ** indicating whether the specified option was defined at
    701 ** compile time.  ^The SQLITE_ prefix may be omitted from the
    702 ** option name passed to sqlite3_compileoption_used().
    703 **
    704 ** ^The sqlite3_compileoption_get() function allows iterating
    705 ** over the list of options that were defined at compile time by
    706 ** returning the N-th compile time option string.  ^If N is out of range,
    707 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
    708 ** prefix is omitted from any strings returned by
    709 ** sqlite3_compileoption_get().
    710 **
    711 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
    712 ** and sqlite3_compileoption_get() may be omitted by specifying the
    713 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
    714 **
    715 ** See also: SQL functions [sqlite_compileoption_used()] and
    716 ** [sqlite_compileoption_get()] and the [compile_options pragma].
    717 */
    718 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
    719 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
    720 SQLITE_API const char *sqlite3_compileoption_get(int N);
    721 #endif
    722 
    723 /*
    724 ** CAPI3REF: Test To See If The Library Is Threadsafe
    725 **
    726 ** ^The sqlite3_threadsafe() function returns zero if and only if
    727 ** SQLite was compiled mutexing code omitted due to the
    728 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
    729 **
    730 ** SQLite can be compiled with or without mutexes.  When
    731 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
    732 ** are enabled and SQLite is threadsafe.  When the
    733 ** [SQLITE_THREADSAFE] macro is 0,
    734 ** the mutexes are omitted.  Without the mutexes, it is not safe
    735 ** to use SQLite concurrently from more than one thread.
    736 **
    737 ** Enabling mutexes incurs a measurable performance penalty.
    738 ** So if speed is of utmost importance, it makes sense to disable
    739 ** the mutexes.  But for maximum safety, mutexes should be enabled.
    740 ** ^The default behavior is for mutexes to be enabled.
    741 **
    742 ** This interface can be used by an application to make sure that the
    743 ** version of SQLite that it is linking against was compiled with
    744 ** the desired setting of the [SQLITE_THREADSAFE] macro.
    745 **
    746 ** This interface only reports on the compile-time mutex setting
    747 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
    748 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
    749 ** can be fully or partially disabled using a call to [sqlite3_config()]
    750 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
    751 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
    752 ** sqlite3_threadsafe() function shows only the compile-time setting of
    753 ** thread safety, not any run-time changes to that setting made by
    754 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
    755 ** is unchanged by calls to sqlite3_config().)^
    756 **
    757 ** See the [threading mode] documentation for additional information.
    758 */
    759 SQLITE_API int sqlite3_threadsafe(void);
    760 
    761 /*
    762 ** CAPI3REF: Database Connection Handle
    763 ** KEYWORDS: {database connection} {database connections}
    764 **
    765 ** Each open SQLite database is represented by a pointer to an instance of
    766 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
    767 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
    768 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
    769 ** is its destructor.  There are many other interfaces (such as
    770 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
    771 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
    772 ** sqlite3 object.
    773 */
    774 typedef struct sqlite3 sqlite3;
    775 
    776 /*
    777 ** CAPI3REF: 64-Bit Integer Types
    778 ** KEYWORDS: sqlite_int64 sqlite_uint64
    779 **
    780 ** Because there is no cross-platform way to specify 64-bit integer types
    781 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
    782 **
    783 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
    784 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
    785 ** compatibility only.
    786 **
    787 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
    788 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
    789 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
    790 ** between 0 and +18446744073709551615 inclusive.
    791 */
    792 #ifdef SQLITE_INT64_TYPE
    793   typedef SQLITE_INT64_TYPE sqlite_int64;
    794   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
    795 #elif defined(_MSC_VER) || defined(__BORLANDC__)
    796   typedef __int64 sqlite_int64;
    797   typedef unsigned __int64 sqlite_uint64;
    798 #else
    799   typedef long long int sqlite_int64;
    800   typedef unsigned long long int sqlite_uint64;
    801 #endif
    802 typedef sqlite_int64 sqlite3_int64;
    803 typedef sqlite_uint64 sqlite3_uint64;
    804 
    805 /*
    806 ** If compiling for a processor that lacks floating point support,
    807 ** substitute integer for floating-point.
    808 */
    809 #ifdef SQLITE_OMIT_FLOATING_POINT
    810 # define double sqlite3_int64
    811 #endif
    812 
    813 /*
    814 ** CAPI3REF: Closing A Database Connection
    815 **
    816 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
    817 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
    818 ** successfully destroyed and all associated resources are deallocated.
    819 **
    820 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
    821 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
    822 ** the [sqlite3] object prior to attempting to close the object.  ^If
    823 ** sqlite3_close() is called on a [database connection] that still has
    824 ** outstanding [prepared statements] or [BLOB handles], then it returns
    825 ** SQLITE_BUSY.
    826 **
    827 ** ^If [sqlite3_close()] is invoked while a transaction is open,
    828 ** the transaction is automatically rolled back.
    829 **
    830 ** The C parameter to [sqlite3_close(C)] must be either a NULL
    831 ** pointer or an [sqlite3] object pointer obtained
    832 ** from [sqlite3_open()], [sqlite3_open16()], or
    833 ** [sqlite3_open_v2()], and not previously closed.
    834 ** ^Calling sqlite3_close() with a NULL pointer argument is a
    835 ** harmless no-op.
    836 */
    837 SQLITE_API int sqlite3_close(sqlite3 *);
    838 
    839 /*
    840 ** The type for a callback function.
    841 ** This is legacy and deprecated.  It is included for historical
    842 ** compatibility and is not documented.
    843 */
    844 typedef int (*sqlite3_callback)(void*,int,char**, char**);
    845 
    846 /*
    847 ** CAPI3REF: One-Step Query Execution Interface
    848 **
    849 ** The sqlite3_exec() interface is a convenience wrapper around
    850 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
    851 ** that allows an application to run multiple statements of SQL
    852 ** without having to use a lot of C code.
    853 **
    854 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
    855 ** semicolon-separate SQL statements passed into its 2nd argument,
    856 ** in the context of the [database connection] passed in as its 1st
    857 ** argument.  ^If the callback function of the 3rd argument to
    858 ** sqlite3_exec() is not NULL, then it is invoked for each result row
    859 ** coming out of the evaluated SQL statements.  ^The 4th argument to
    860 ** to sqlite3_exec() is relayed through to the 1st argument of each
    861 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
    862 ** is NULL, then no callback is ever invoked and result rows are
    863 ** ignored.
    864 **
    865 ** ^If an error occurs while evaluating the SQL statements passed into
    866 ** sqlite3_exec(), then execution of the current statement stops and
    867 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
    868 ** is not NULL then any error message is written into memory obtained
    869 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
    870 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
    871 ** on error message strings returned through the 5th parameter of
    872 ** of sqlite3_exec() after the error message string is no longer needed.
    873 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
    874 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
    875 ** NULL before returning.
    876 **
    877 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
    878 ** routine returns SQLITE_ABORT without invoking the callback again and
    879 ** without running any subsequent SQL statements.
    880 **
    881 ** ^The 2nd argument to the sqlite3_exec() callback function is the
    882 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
    883 ** callback is an array of pointers to strings obtained as if from
    884 ** [sqlite3_column_text()], one for each column.  ^If an element of a
    885 ** result row is NULL then the corresponding string pointer for the
    886 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
    887 ** sqlite3_exec() callback is an array of pointers to strings where each
    888 ** entry represents the name of corresponding result column as obtained
    889 ** from [sqlite3_column_name()].
    890 **
    891 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
    892 ** to an empty string, or a pointer that contains only whitespace and/or
    893 ** SQL comments, then no SQL statements are evaluated and the database
    894 ** is not changed.
    895 **
    896 ** Restrictions:
    897 **
    898 ** <ul>
    899 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
    900 **      is a valid and open [database connection].
    901 ** <li> The application must not close [database connection] specified by
    902 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
    903 ** <li> The application must not modify the SQL statement text passed into
    904 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
    905 ** </ul>
    906 */
    907 SQLITE_API int sqlite3_exec(
    908   sqlite3*,                                  /* An open database */
    909   const char *sql,                           /* SQL to be evaluated */
    910   int (*callback)(void*,int,char**,char**),  /* Callback function */
    911   void *,                                    /* 1st argument to callback */
    912   char **errmsg                              /* Error msg written here */
    913 );
    914 
    915 /*
    916 ** CAPI3REF: Result Codes
    917 ** KEYWORDS: SQLITE_OK {error code} {error codes}
    918 ** KEYWORDS: {result code} {result codes}
    919 **
    920 ** Many SQLite functions return an integer result code from the set shown
    921 ** here in order to indicates success or failure.
    922 **
    923 ** New error codes may be added in future versions of SQLite.
    924 **
    925 ** See also: [SQLITE_IOERR_READ | extended result codes]
    926 */
    927 #define SQLITE_OK           0   /* Successful result */
    928 /* beginning-of-error-codes */
    929 #define SQLITE_ERROR        1   /* SQL error or missing database */
    930 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
    931 #define SQLITE_PERM         3   /* Access permission denied */
    932 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
    933 #define SQLITE_BUSY         5   /* The database file is locked */
    934 #define SQLITE_LOCKED       6   /* A table in the database is locked */
    935 #define SQLITE_NOMEM        7   /* A malloc() failed */
    936 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
    937 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
    938 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
    939 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
    940 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
    941 #define SQLITE_FULL        13   /* Insertion failed because database is full */
    942 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
    943 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
    944 #define SQLITE_EMPTY       16   /* Database is empty */
    945 #define SQLITE_SCHEMA      17   /* The database schema changed */
    946 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
    947 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
    948 #define SQLITE_MISMATCH    20   /* Data type mismatch */
    949 #define SQLITE_MISUSE      21   /* Library used incorrectly */
    950 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
    951 #define SQLITE_AUTH        23   /* Authorization denied */
    952 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
    953 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
    954 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
    955 // Begin Android Add
    956 #define SQLITE_UNCLOSED    27   /* db can't be closed due unfinalized stmts */
    957 // End Android Add
    958 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
    959 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
    960 /* end-of-error-codes */
    961 
    962 /*
    963 ** CAPI3REF: Extended Result Codes
    964 ** KEYWORDS: {extended error code} {extended error codes}
    965 ** KEYWORDS: {extended result code} {extended result codes}
    966 **
    967 ** In its default configuration, SQLite API routines return one of 26 integer
    968 ** [SQLITE_OK | result codes].  However, experience has shown that many of
    969 ** these result codes are too coarse-grained.  They do not provide as
    970 ** much information about problems as programmers might like.  In an effort to
    971 ** address this, newer versions of SQLite (version 3.3.8 and later) include
    972 ** support for additional result codes that provide more detailed information
    973 ** about errors. The extended result codes are enabled or disabled
    974 ** on a per database connection basis using the
    975 ** [sqlite3_extended_result_codes()] API.
    976 **
    977 ** Some of the available extended result codes are listed here.
    978 ** One may expect the number of extended result codes will be expand
    979 ** over time.  Software that uses extended result codes should expect
    980 ** to see new result codes in future releases of SQLite.
    981 **
    982 ** The SQLITE_OK result code will never be extended.  It will always
    983 ** be exactly zero.
    984 */
    985 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
    986 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
    987 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
    988 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
    989 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
    990 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
    991 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
    992 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
    993 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
    994 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
    995 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
    996 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
    997 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
    998 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
    999 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
   1000 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
   1001 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
   1002 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   1003 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   1004 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   1005 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   1006 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   1007 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   1008 
   1009 /*
   1010 ** CAPI3REF: Flags For File Open Operations
   1011 **
   1012 ** These bit values are intended for use in the
   1013 ** 3rd parameter to the [sqlite3_open_v2()] interface and
   1014 ** in the 4th parameter to the xOpen method of the
   1015 ** [sqlite3_vfs] object.
   1016 */
   1017 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
   1018 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
   1019 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
   1020 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
   1021 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
   1022 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
   1023 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
   1024 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
   1025 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
   1026 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
   1027 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
   1028 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
   1029 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
   1030 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
   1031 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
   1032 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
   1033 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
   1034 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
   1035 
   1036 /*
   1037 ** CAPI3REF: Device Characteristics
   1038 **
   1039 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
   1040 ** object returns an integer which is a vector of the these
   1041 ** bit values expressing I/O characteristics of the mass storage
   1042 ** device that holds the file that the [sqlite3_io_methods]
   1043 ** refers to.
   1044 **
   1045 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1046 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1047 ** mean that writes of blocks that are nnn bytes in size and
   1048 ** are aligned to an address which is an integer multiple of
   1049 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1050 ** that when data is appended to a file, the data is appended
   1051 ** first then the size of the file is extended, never the other
   1052 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1053 ** information is written to disk in the same order as calls
   1054 ** to xWrite().
   1055 */
   1056 #define SQLITE_IOCAP_ATOMIC                 0x00000001
   1057 #define SQLITE_IOCAP_ATOMIC512              0x00000002
   1058 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
   1059 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
   1060 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
   1061 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
   1062 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
   1063 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
   1064 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
   1065 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   1066 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   1067 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
   1068 
   1069 /*
   1070 ** CAPI3REF: File Locking Levels
   1071 **
   1072 ** SQLite uses one of these integer values as the second
   1073 ** argument to calls it makes to the xLock() and xUnlock() methods
   1074 ** of an [sqlite3_io_methods] object.
   1075 */
   1076 #define SQLITE_LOCK_NONE          0
   1077 #define SQLITE_LOCK_SHARED        1
   1078 #define SQLITE_LOCK_RESERVED      2
   1079 #define SQLITE_LOCK_PENDING       3
   1080 #define SQLITE_LOCK_EXCLUSIVE     4
   1081 
   1082 /*
   1083 ** CAPI3REF: Synchronization Type Flags
   1084 **
   1085 ** When SQLite invokes the xSync() method of an
   1086 ** [sqlite3_io_methods] object it uses a combination of
   1087 ** these integer values as the second argument.
   1088 **
   1089 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
   1090 ** sync operation only needs to flush data to mass storage.  Inode
   1091 ** information need not be flushed. If the lower four bits of the flag
   1092 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
   1093 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
   1094 ** to use Mac OS X style fullsync instead of fsync().
   1095 **
   1096 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
   1097 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
   1098 ** settings.  The [synchronous pragma] determines when calls to the
   1099 ** xSync VFS method occur and applies uniformly across all platforms.
   1100 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
   1101 ** energetic or rigorous or forceful the sync operations are and
   1102 ** only make a difference on Mac OSX for the default SQLite code.
   1103 ** (Third-party VFS implementations might also make the distinction
   1104 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
   1105 ** operating systems natively supported by SQLite, only Mac OSX
   1106 ** cares about the difference.)
   1107 */
   1108 #define SQLITE_SYNC_NORMAL        0x00002
   1109 #define SQLITE_SYNC_FULL          0x00003
   1110 #define SQLITE_SYNC_DATAONLY      0x00010
   1111 
   1112 /*
   1113 ** CAPI3REF: OS Interface Open File Handle
   1114 **
   1115 ** An [sqlite3_file] object represents an open file in the
   1116 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
   1117 ** implementations will
   1118 ** want to subclass this object by appending additional fields
   1119 ** for their own use.  The pMethods entry is a pointer to an
   1120 ** [sqlite3_io_methods] object that defines methods for performing
   1121 ** I/O operations on the open file.
   1122 */
   1123 typedef struct sqlite3_file sqlite3_file;
   1124 struct sqlite3_file {
   1125   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
   1126 };
   1127 
   1128 /*
   1129 ** CAPI3REF: OS Interface File Virtual Methods Object
   1130 **
   1131 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
   1132 ** [sqlite3_file] object (or, more commonly, a subclass of the
   1133 ** [sqlite3_file] object) with a pointer to an instance of this object.
   1134 ** This object defines the methods used to perform various operations
   1135 ** against the open file represented by the [sqlite3_file] object.
   1136 **
   1137 ** If the xOpen method sets the sqlite3_file.pMethods element
   1138 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
   1139 ** may be invoked even if the xOpen reported that it failed.  The
   1140 ** only way to prevent a call to xClose following a failed xOpen
   1141 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
   1142 **
   1143 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
   1144 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
   1145 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
   1146 ** flag may be ORed in to indicate that only the data of the file
   1147 ** and not its inode needs to be synced.
   1148 **
   1149 ** The integer values to xLock() and xUnlock() are one of
   1150 ** <ul>
   1151 ** <li> [SQLITE_LOCK_NONE],
   1152 ** <li> [SQLITE_LOCK_SHARED],
   1153 ** <li> [SQLITE_LOCK_RESERVED],
   1154 ** <li> [SQLITE_LOCK_PENDING], or
   1155 ** <li> [SQLITE_LOCK_EXCLUSIVE].
   1156 ** </ul>
   1157 ** xLock() increases the lock. xUnlock() decreases the lock.
   1158 ** The xCheckReservedLock() method checks whether any database connection,
   1159 ** either in this process or in some other process, is holding a RESERVED,
   1160 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
   1161 ** if such a lock exists and false otherwise.
   1162 **
   1163 ** The xFileControl() method is a generic interface that allows custom
   1164 ** VFS implementations to directly control an open file using the
   1165 ** [sqlite3_file_control()] interface.  The second "op" argument is an
   1166 ** integer opcode.  The third argument is a generic pointer intended to
   1167 ** point to a structure that may contain arguments or space in which to
   1168 ** write return values.  Potential uses for xFileControl() might be
   1169 ** functions to enable blocking locks with timeouts, to change the
   1170 ** locking strategy (for example to use dot-file locks), to inquire
   1171 ** about the status of a lock, or to break stale locks.  The SQLite
   1172 ** core reserves all opcodes less than 100 for its own use.
   1173 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
   1174 ** Applications that define a custom xFileControl method should use opcodes
   1175 ** greater than 100 to avoid conflicts.
   1176 **
   1177 ** The xSectorSize() method returns the sector size of the
   1178 ** device that underlies the file.  The sector size is the
   1179 ** minimum write that can be performed without disturbing
   1180 ** other bytes in the file.  The xDeviceCharacteristics()
   1181 ** method returns a bit vector describing behaviors of the
   1182 ** underlying device:
   1183 **
   1184 ** <ul>
   1185 ** <li> [SQLITE_IOCAP_ATOMIC]
   1186 ** <li> [SQLITE_IOCAP_ATOMIC512]
   1187 ** <li> [SQLITE_IOCAP_ATOMIC1K]
   1188 ** <li> [SQLITE_IOCAP_ATOMIC2K]
   1189 ** <li> [SQLITE_IOCAP_ATOMIC4K]
   1190 ** <li> [SQLITE_IOCAP_ATOMIC8K]
   1191 ** <li> [SQLITE_IOCAP_ATOMIC16K]
   1192 ** <li> [SQLITE_IOCAP_ATOMIC32K]
   1193 ** <li> [SQLITE_IOCAP_ATOMIC64K]
   1194 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
   1195 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
   1196 ** </ul>
   1197 **
   1198 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
   1199 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
   1200 ** mean that writes of blocks that are nnn bytes in size and
   1201 ** are aligned to an address which is an integer multiple of
   1202 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   1203 ** that when data is appended to a file, the data is appended
   1204 ** first then the size of the file is extended, never the other
   1205 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   1206 ** information is written to disk in the same order as calls
   1207 ** to xWrite().
   1208 **
   1209 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
   1210 ** in the unread portions of the buffer with zeros.  A VFS that
   1211 ** fails to zero-fill short reads might seem to work.  However,
   1212 ** failure to zero-fill short reads will eventually lead to
   1213 ** database corruption.
   1214 */
   1215 typedef struct sqlite3_io_methods sqlite3_io_methods;
   1216 struct sqlite3_io_methods {
   1217   int iVersion;
   1218   int (*xClose)(sqlite3_file*);
   1219   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
   1220   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
   1221   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
   1222   int (*xSync)(sqlite3_file*, int flags);
   1223   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
   1224   int (*xLock)(sqlite3_file*, int);
   1225   int (*xUnlock)(sqlite3_file*, int);
   1226   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
   1227   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
   1228   int (*xSectorSize)(sqlite3_file*);
   1229   int (*xDeviceCharacteristics)(sqlite3_file*);
   1230   /* Methods above are valid for version 1 */
   1231   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
   1232   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
   1233   void (*xShmBarrier)(sqlite3_file*);
   1234   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
   1235   /* Methods above are valid for version 2 */
   1236   /* Additional methods may be added in future releases */
   1237 };
   1238 
   1239 /*
   1240 ** CAPI3REF: Standard File Control Opcodes
   1241 **
   1242 ** These integer constants are opcodes for the xFileControl method
   1243 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
   1244 ** interface.
   1245 **
   1246 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
   1247 ** opcode causes the xFileControl method to write the current state of
   1248 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
   1249 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
   1250 ** into an integer that the pArg argument points to. This capability
   1251 ** is used during testing and only needs to be supported when SQLITE_TEST
   1252 ** is defined.
   1253 **
   1254 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
   1255 ** layer a hint of how large the database file will grow to be during the
   1256 ** current transaction.  This hint is not guaranteed to be accurate but it
   1257 ** is often close.  The underlying VFS might choose to preallocate database
   1258 ** file space based on this hint in order to help writes to the database
   1259 ** file run faster.
   1260 **
   1261 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
   1262 ** extends and truncates the database file in chunks of a size specified
   1263 ** by the user. The fourth argument to [sqlite3_file_control()] should
   1264 ** point to an integer (type int) containing the new chunk-size to use
   1265 ** for the nominated database. Allocating database file space in large
   1266 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
   1267 ** improve performance on some systems.
   1268 */
   1269 #define SQLITE_FCNTL_LOCKSTATE        1
   1270 #define SQLITE_GET_LOCKPROXYFILE      2
   1271 #define SQLITE_SET_LOCKPROXYFILE      3
   1272 #define SQLITE_LAST_ERRNO             4
   1273 #define SQLITE_FCNTL_SIZE_HINT        5
   1274 #define SQLITE_FCNTL_CHUNK_SIZE       6
   1275 #define SQLITE_FCNTL_FILE_POINTER     7
   1276 
   1277 
   1278 /*
   1279 ** CAPI3REF: Mutex Handle
   1280 **
   1281 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   1282 ** abstract type for a mutex object.  The SQLite core never looks
   1283 ** at the internal representation of an [sqlite3_mutex].  It only
   1284 ** deals with pointers to the [sqlite3_mutex] object.
   1285 **
   1286 ** Mutexes are created using [sqlite3_mutex_alloc()].
   1287 */
   1288 typedef struct sqlite3_mutex sqlite3_mutex;
   1289 
   1290 /*
   1291 ** CAPI3REF: OS Interface Object
   1292 **
   1293 ** An instance of the sqlite3_vfs object defines the interface between
   1294 ** the SQLite core and the underlying operating system.  The "vfs"
   1295 ** in the name of the object stands for "virtual file system".
   1296 **
   1297 ** The value of the iVersion field is initially 1 but may be larger in
   1298 ** future versions of SQLite.  Additional fields may be appended to this
   1299 ** object when the iVersion value is increased.  Note that the structure
   1300 ** of the sqlite3_vfs object changes in the transaction between
   1301 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
   1302 ** modified.
   1303 **
   1304 ** The szOsFile field is the size of the subclassed [sqlite3_file]
   1305 ** structure used by this VFS.  mxPathname is the maximum length of
   1306 ** a pathname in this VFS.
   1307 **
   1308 ** Registered sqlite3_vfs objects are kept on a linked list formed by
   1309 ** the pNext pointer.  The [sqlite3_vfs_register()]
   1310 ** and [sqlite3_vfs_unregister()] interfaces manage this list
   1311 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
   1312 ** searches the list.  Neither the application code nor the VFS
   1313 ** implementation should use the pNext pointer.
   1314 **
   1315 ** The pNext field is the only field in the sqlite3_vfs
   1316 ** structure that SQLite will ever modify.  SQLite will only access
   1317 ** or modify this field while holding a particular static mutex.
   1318 ** The application should never modify anything within the sqlite3_vfs
   1319 ** object once the object has been registered.
   1320 **
   1321 ** The zName field holds the name of the VFS module.  The name must
   1322 ** be unique across all VFS modules.
   1323 **
   1324 ** ^SQLite guarantees that the zFilename parameter to xOpen
   1325 ** is either a NULL pointer or string obtained
   1326 ** from xFullPathname() with an optional suffix added.
   1327 ** ^If a suffix is added to the zFilename parameter, it will
   1328 ** consist of a single "-" character followed by no more than
   1329 ** 10 alphanumeric and/or "-" characters.
   1330 ** ^SQLite further guarantees that
   1331 ** the string will be valid and unchanged until xClose() is
   1332 ** called. Because of the previous sentence,
   1333 ** the [sqlite3_file] can safely store a pointer to the
   1334 ** filename if it needs to remember the filename for some reason.
   1335 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
   1336 ** must invent its own temporary name for the file.  ^Whenever the
   1337 ** xFilename parameter is NULL it will also be the case that the
   1338 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
   1339 **
   1340 ** The flags argument to xOpen() includes all bits set in
   1341 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
   1342 ** or [sqlite3_open16()] is used, then flags includes at least
   1343 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
   1344 ** If xOpen() opens a file read-only then it sets *pOutFlags to
   1345 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
   1346 **
   1347 ** ^(SQLite will also add one of the following flags to the xOpen()
   1348 ** call, depending on the object being opened:
   1349 **
   1350 ** <ul>
   1351 ** <li>  [SQLITE_OPEN_MAIN_DB]
   1352 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
   1353 ** <li>  [SQLITE_OPEN_TEMP_DB]
   1354 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
   1355 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
   1356 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
   1357 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
   1358 ** <li>  [SQLITE_OPEN_WAL]
   1359 ** </ul>)^
   1360 **
   1361 ** The file I/O implementation can use the object type flags to
   1362 ** change the way it deals with files.  For example, an application
   1363 ** that does not care about crash recovery or rollback might make
   1364 ** the open of a journal file a no-op.  Writes to this journal would
   1365 ** also be no-ops, and any attempt to read the journal would return
   1366 ** SQLITE_IOERR.  Or the implementation might recognize that a database
   1367 ** file will be doing page-aligned sector reads and writes in a random
   1368 ** order and set up its I/O subsystem accordingly.
   1369 **
   1370 ** SQLite might also add one of the following flags to the xOpen method:
   1371 **
   1372 ** <ul>
   1373 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
   1374 ** <li> [SQLITE_OPEN_EXCLUSIVE]
   1375 ** </ul>
   1376 **
   1377 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
   1378 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
   1379 ** will be set for TEMP databases and their journals, transient
   1380 ** databases, and subjournals.
   1381 **
   1382 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
   1383 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
   1384 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
   1385 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
   1386 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
   1387 ** be created, and that it is an error if it already exists.
   1388 ** It is <i>not</i> used to indicate the file should be opened
   1389 ** for exclusive access.
   1390 **
   1391 ** ^At least szOsFile bytes of memory are allocated by SQLite
   1392 ** to hold the  [sqlite3_file] structure passed as the third
   1393 ** argument to xOpen.  The xOpen method does not have to
   1394 ** allocate the structure; it should just fill it in.  Note that
   1395 ** the xOpen method must set the sqlite3_file.pMethods to either
   1396 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
   1397 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
   1398 ** element will be valid after xOpen returns regardless of the success
   1399 ** or failure of the xOpen call.
   1400 **
   1401 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
   1402 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
   1403 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
   1404 ** to test whether a file is at least readable.   The file can be a
   1405 ** directory.
   1406 **
   1407 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
   1408 ** output buffer xFullPathname.  The exact size of the output buffer
   1409 ** is also passed as a parameter to both  methods. If the output buffer
   1410 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
   1411 ** handled as a fatal error by SQLite, vfs implementations should endeavor
   1412 ** to prevent this by setting mxPathname to a sufficiently large value.
   1413 **
   1414 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
   1415 ** interfaces are not strictly a part of the filesystem, but they are
   1416 ** included in the VFS structure for completeness.
   1417 ** The xRandomness() function attempts to return nBytes bytes
   1418 ** of good-quality randomness into zOut.  The return value is
   1419 ** the actual number of bytes of randomness obtained.
   1420 ** The xSleep() method causes the calling thread to sleep for at
   1421 ** least the number of microseconds given.  ^The xCurrentTime()
   1422 ** method returns a Julian Day Number for the current date and time as
   1423 ** a floating point value.
   1424 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
   1425 ** Day Number multipled by 86400000 (the number of milliseconds in
   1426 ** a 24-hour day).
   1427 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
   1428 ** date and time if that method is available (if iVersion is 2 or
   1429 ** greater and the function pointer is not NULL) and will fall back
   1430 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
   1431 */
   1432 typedef struct sqlite3_vfs sqlite3_vfs;
   1433 struct sqlite3_vfs {
   1434   int iVersion;            /* Structure version number (currently 2) */
   1435   int szOsFile;            /* Size of subclassed sqlite3_file */
   1436   int mxPathname;          /* Maximum file pathname length */
   1437   sqlite3_vfs *pNext;      /* Next registered VFS */
   1438   const char *zName;       /* Name of this virtual file system */
   1439   void *pAppData;          /* Pointer to application-specific data */
   1440   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
   1441                int flags, int *pOutFlags);
   1442   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
   1443   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
   1444   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
   1445   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
   1446   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
   1447   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
   1448   void (*xDlClose)(sqlite3_vfs*, void*);
   1449   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
   1450   int (*xSleep)(sqlite3_vfs*, int microseconds);
   1451   int (*xCurrentTime)(sqlite3_vfs*, double*);
   1452   int (*xGetLastError)(sqlite3_vfs*, int, char *);
   1453   /*
   1454   ** The methods above are in version 1 of the sqlite_vfs object
   1455   ** definition.  Those that follow are added in version 2 or later
   1456   */
   1457   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
   1458   /*
   1459   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
   1460   ** New fields may be appended in figure versions.  The iVersion
   1461   ** value will increment whenever this happens.
   1462   */
   1463 };
   1464 
   1465 /*
   1466 ** CAPI3REF: Flags for the xAccess VFS method
   1467 **
   1468 ** These integer constants can be used as the third parameter to
   1469 ** the xAccess method of an [sqlite3_vfs] object.  They determine
   1470 ** what kind of permissions the xAccess method is looking for.
   1471 ** With SQLITE_ACCESS_EXISTS, the xAccess method
   1472 ** simply checks whether the file exists.
   1473 ** With SQLITE_ACCESS_READWRITE, the xAccess method
   1474 ** checks whether the named directory is both readable and writable
   1475 ** (in other words, if files can be added, removed, and renamed within
   1476 ** the directory).
   1477 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
   1478 ** [temp_store_directory pragma], though this could change in a future
   1479 ** release of SQLite.
   1480 ** With SQLITE_ACCESS_READ, the xAccess method
   1481 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
   1482 ** currently unused, though it might be used in a future release of
   1483 ** SQLite.
   1484 */
   1485 #define SQLITE_ACCESS_EXISTS    0
   1486 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
   1487 #define SQLITE_ACCESS_READ      2   /* Unused */
   1488 
   1489 /*
   1490 ** CAPI3REF: Flags for the xShmLock VFS method
   1491 **
   1492 ** These integer constants define the various locking operations
   1493 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
   1494 ** following are the only legal combinations of flags to the
   1495 ** xShmLock method:
   1496 **
   1497 ** <ul>
   1498 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
   1499 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
   1500 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
   1501 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
   1502 ** </ul>
   1503 **
   1504 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
   1505 ** was given no the corresponding lock.
   1506 **
   1507 ** The xShmLock method can transition between unlocked and SHARED or
   1508 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
   1509 ** and EXCLUSIVE.
   1510 */
   1511 #define SQLITE_SHM_UNLOCK       1
   1512 #define SQLITE_SHM_LOCK         2
   1513 #define SQLITE_SHM_SHARED       4
   1514 #define SQLITE_SHM_EXCLUSIVE    8
   1515 
   1516 /*
   1517 ** CAPI3REF: Maximum xShmLock index
   1518 **
   1519 ** The xShmLock method on [sqlite3_io_methods] may use values
   1520 ** between 0 and this upper bound as its "offset" argument.
   1521 ** The SQLite core will never attempt to acquire or release a
   1522 ** lock outside of this range
   1523 */
   1524 #define SQLITE_SHM_NLOCK        8
   1525 
   1526 
   1527 /*
   1528 ** CAPI3REF: Initialize The SQLite Library
   1529 **
   1530 ** ^The sqlite3_initialize() routine initializes the
   1531 ** SQLite library.  ^The sqlite3_shutdown() routine
   1532 ** deallocates any resources that were allocated by sqlite3_initialize().
   1533 ** These routines are designed to aid in process initialization and
   1534 ** shutdown on embedded systems.  Workstation applications using
   1535 ** SQLite normally do not need to invoke either of these routines.
   1536 **
   1537 ** A call to sqlite3_initialize() is an "effective" call if it is
   1538 ** the first time sqlite3_initialize() is invoked during the lifetime of
   1539 ** the process, or if it is the first time sqlite3_initialize() is invoked
   1540 ** following a call to sqlite3_shutdown().  ^(Only an effective call
   1541 ** of sqlite3_initialize() does any initialization.  All other calls
   1542 ** are harmless no-ops.)^
   1543 **
   1544 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
   1545 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
   1546 ** an effective call to sqlite3_shutdown() does any deinitialization.
   1547 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
   1548 **
   1549 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
   1550 ** is not.  The sqlite3_shutdown() interface must only be called from a
   1551 ** single thread.  All open [database connections] must be closed and all
   1552 ** other SQLite resources must be deallocated prior to invoking
   1553 ** sqlite3_shutdown().
   1554 **
   1555 ** Among other things, ^sqlite3_initialize() will invoke
   1556 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
   1557 ** will invoke sqlite3_os_end().
   1558 **
   1559 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
   1560 ** ^If for some reason, sqlite3_initialize() is unable to initialize
   1561 ** the library (perhaps it is unable to allocate a needed resource such
   1562 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
   1563 **
   1564 ** ^The sqlite3_initialize() routine is called internally by many other
   1565 ** SQLite interfaces so that an application usually does not need to
   1566 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
   1567 ** calls sqlite3_initialize() so the SQLite library will be automatically
   1568 ** initialized when [sqlite3_open()] is called if it has not be initialized
   1569 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
   1570 ** compile-time option, then the automatic calls to sqlite3_initialize()
   1571 ** are omitted and the application must call sqlite3_initialize() directly
   1572 ** prior to using any other SQLite interface.  For maximum portability,
   1573 ** it is recommended that applications always invoke sqlite3_initialize()
   1574 ** directly prior to using any other SQLite interface.  Future releases
   1575 ** of SQLite may require this.  In other words, the behavior exhibited
   1576 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
   1577 ** default behavior in some future release of SQLite.
   1578 **
   1579 ** The sqlite3_os_init() routine does operating-system specific
   1580 ** initialization of the SQLite library.  The sqlite3_os_end()
   1581 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
   1582 ** performed by these routines include allocation or deallocation
   1583 ** of static resources, initialization of global variables,
   1584 ** setting up a default [sqlite3_vfs] module, or setting up
   1585 ** a default configuration using [sqlite3_config()].
   1586 **
   1587 ** The application should never invoke either sqlite3_os_init()
   1588 ** or sqlite3_os_end() directly.  The application should only invoke
   1589 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
   1590 ** interface is called automatically by sqlite3_initialize() and
   1591 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
   1592 ** implementations for sqlite3_os_init() and sqlite3_os_end()
   1593 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
   1594 ** When [custom builds | built for other platforms]
   1595 ** (using the [SQLITE_OS_OTHER=1] compile-time
   1596 ** option) the application must supply a suitable implementation for
   1597 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
   1598 ** implementation of sqlite3_os_init() or sqlite3_os_end()
   1599 ** must return [SQLITE_OK] on success and some other [error code] upon
   1600 ** failure.
   1601 */
   1602 SQLITE_API int sqlite3_initialize(void);
   1603 SQLITE_API int sqlite3_shutdown(void);
   1604 SQLITE_API int sqlite3_os_init(void);
   1605 SQLITE_API int sqlite3_os_end(void);
   1606 
   1607 /*
   1608 ** CAPI3REF: Configuring The SQLite Library
   1609 **
   1610 ** The sqlite3_config() interface is used to make global configuration
   1611 ** changes to SQLite in order to tune SQLite to the specific needs of
   1612 ** the application.  The default configuration is recommended for most
   1613 ** applications and so this routine is usually not necessary.  It is
   1614 ** provided to support rare applications with unusual needs.
   1615 **
   1616 ** The sqlite3_config() interface is not threadsafe.  The application
   1617 ** must insure that no other SQLite interfaces are invoked by other
   1618 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
   1619 ** may only be invoked prior to library initialization using
   1620 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
   1621 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
   1622 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
   1623 ** Note, however, that ^sqlite3_config() can be called as part of the
   1624 ** implementation of an application-defined [sqlite3_os_init()].
   1625 **
   1626 ** The first argument to sqlite3_config() is an integer
   1627 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
   1628 ** what property of SQLite is to be configured.  Subsequent arguments
   1629 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
   1630 ** in the first argument.
   1631 **
   1632 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
   1633 ** ^If the option is unknown or SQLite is unable to set the option
   1634 ** then this routine returns a non-zero [error code].
   1635 */
   1636 SQLITE_API int sqlite3_config(int, ...);
   1637 
   1638 /*
   1639 ** CAPI3REF: Configure database connections
   1640 **
   1641 ** The sqlite3_db_config() interface is used to make configuration
   1642 ** changes to a [database connection].  The interface is similar to
   1643 ** [sqlite3_config()] except that the changes apply to a single
   1644 ** [database connection] (specified in the first argument).  The
   1645 ** sqlite3_db_config() interface should only be used immediately after
   1646 ** the database connection is created using [sqlite3_open()],
   1647 ** [sqlite3_open16()], or [sqlite3_open_v2()].
   1648 **
   1649 ** The second argument to sqlite3_db_config(D,V,...)  is the
   1650 ** configuration verb - an integer code that indicates what
   1651 ** aspect of the [database connection] is being configured.
   1652 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
   1653 ** New verbs are likely to be added in future releases of SQLite.
   1654 ** Additional arguments depend on the verb.
   1655 **
   1656 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
   1657 ** the call is considered successful.
   1658 */
   1659 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
   1660 
   1661 /*
   1662 ** CAPI3REF: Memory Allocation Routines
   1663 **
   1664 ** An instance of this object defines the interface between SQLite
   1665 ** and low-level memory allocation routines.
   1666 **
   1667 ** This object is used in only one place in the SQLite interface.
   1668 ** A pointer to an instance of this object is the argument to
   1669 ** [sqlite3_config()] when the configuration option is
   1670 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
   1671 ** By creating an instance of this object
   1672 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
   1673 ** during configuration, an application can specify an alternative
   1674 ** memory allocation subsystem for SQLite to use for all of its
   1675 ** dynamic memory needs.
   1676 **
   1677 ** Note that SQLite comes with several [built-in memory allocators]
   1678 ** that are perfectly adequate for the overwhelming majority of applications
   1679 ** and that this object is only useful to a tiny minority of applications
   1680 ** with specialized memory allocation requirements.  This object is
   1681 ** also used during testing of SQLite in order to specify an alternative
   1682 ** memory allocator that simulates memory out-of-memory conditions in
   1683 ** order to verify that SQLite recovers gracefully from such
   1684 ** conditions.
   1685 **
   1686 ** The xMalloc and xFree methods must work like the
   1687 ** malloc() and free() functions from the standard C library.
   1688 ** The xRealloc method must work like realloc() from the standard C library
   1689 ** with the exception that if the second argument to xRealloc is zero,
   1690 ** xRealloc must be a no-op - it must not perform any allocation or
   1691 ** deallocation.  ^SQLite guarantees that the second argument to
   1692 ** xRealloc is always a value returned by a prior call to xRoundup.
   1693 ** And so in cases where xRoundup always returns a positive number,
   1694 ** xRealloc can perform exactly as the standard library realloc() and
   1695 ** still be in compliance with this specification.
   1696 **
   1697 ** xSize should return the allocated size of a memory allocation
   1698 ** previously obtained from xMalloc or xRealloc.  The allocated size
   1699 ** is always at least as big as the requested size but may be larger.
   1700 **
   1701 ** The xRoundup method returns what would be the allocated size of
   1702 ** a memory allocation given a particular requested size.  Most memory
   1703 ** allocators round up memory allocations at least to the next multiple
   1704 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
   1705 ** Every memory allocation request coming in through [sqlite3_malloc()]
   1706 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
   1707 ** that causes the corresponding memory allocation to fail.
   1708 **
   1709 ** The xInit method initializes the memory allocator.  (For example,
   1710 ** it might allocate any require mutexes or initialize internal data
   1711 ** structures.  The xShutdown method is invoked (indirectly) by
   1712 ** [sqlite3_shutdown()] and should deallocate any resources acquired
   1713 ** by xInit.  The pAppData pointer is used as the only parameter to
   1714 ** xInit and xShutdown.
   1715 **
   1716 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
   1717 ** the xInit method, so the xInit method need not be threadsafe.  The
   1718 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   1719 ** not need to be threadsafe either.  For all other methods, SQLite
   1720 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
   1721 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
   1722 ** it is by default) and so the methods are automatically serialized.
   1723 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
   1724 ** methods must be threadsafe or else make their own arrangements for
   1725 ** serialization.
   1726 **
   1727 ** SQLite will never invoke xInit() more than once without an intervening
   1728 ** call to xShutdown().
   1729 */
   1730 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
   1731 struct sqlite3_mem_methods {
   1732   void *(*xMalloc)(int);         /* Memory allocation function */
   1733   void (*xFree)(void*);          /* Free a prior allocation */
   1734   void *(*xRealloc)(void*,int);  /* Resize an allocation */
   1735   int (*xSize)(void*);           /* Return the size of an allocation */
   1736   int (*xRoundup)(int);          /* Round up request size to allocation size */
   1737   int (*xInit)(void*);           /* Initialize the memory allocator */
   1738   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
   1739   void *pAppData;                /* Argument to xInit() and xShutdown() */
   1740 };
   1741 
   1742 /*
   1743 ** CAPI3REF: Configuration Options
   1744 **
   1745 ** These constants are the available integer configuration options that
   1746 ** can be passed as the first argument to the [sqlite3_config()] interface.
   1747 **
   1748 ** New configuration options may be added in future releases of SQLite.
   1749 ** Existing configuration options might be discontinued.  Applications
   1750 ** should check the return code from [sqlite3_config()] to make sure that
   1751 ** the call worked.  The [sqlite3_config()] interface will return a
   1752 ** non-zero [error code] if a discontinued or unsupported configuration option
   1753 ** is invoked.
   1754 **
   1755 ** <dl>
   1756 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
   1757 ** <dd>There are no arguments to this option.  ^This option sets the
   1758 ** [threading mode] to Single-thread.  In other words, it disables
   1759 ** all mutexing and puts SQLite into a mode where it can only be used
   1760 ** by a single thread.   ^If SQLite is compiled with
   1761 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1762 ** it is not possible to change the [threading mode] from its default
   1763 ** value of Single-thread and so [sqlite3_config()] will return
   1764 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
   1765 ** configuration option.</dd>
   1766 **
   1767 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
   1768 ** <dd>There are no arguments to this option.  ^This option sets the
   1769 ** [threading mode] to Multi-thread.  In other words, it disables
   1770 ** mutexing on [database connection] and [prepared statement] objects.
   1771 ** The application is responsible for serializing access to
   1772 ** [database connections] and [prepared statements].  But other mutexes
   1773 ** are enabled so that SQLite will be safe to use in a multi-threaded
   1774 ** environment as long as no two threads attempt to use the same
   1775 ** [database connection] at the same time.  ^If SQLite is compiled with
   1776 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1777 ** it is not possible to set the Multi-thread [threading mode] and
   1778 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1779 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
   1780 **
   1781 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
   1782 ** <dd>There are no arguments to this option.  ^This option sets the
   1783 ** [threading mode] to Serialized. In other words, this option enables
   1784 ** all mutexes including the recursive
   1785 ** mutexes on [database connection] and [prepared statement] objects.
   1786 ** In this mode (which is the default when SQLite is compiled with
   1787 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
   1788 ** to [database connections] and [prepared statements] so that the
   1789 ** application is free to use the same [database connection] or the
   1790 ** same [prepared statement] in different threads at the same time.
   1791 ** ^If SQLite is compiled with
   1792 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1793 ** it is not possible to set the Serialized [threading mode] and
   1794 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
   1795 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
   1796 **
   1797 ** <dt>SQLITE_CONFIG_MALLOC</dt>
   1798 ** <dd> ^(This option takes a single argument which is a pointer to an
   1799 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
   1800 ** alternative low-level memory allocation routines to be used in place of
   1801 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
   1802 ** its own private copy of the content of the [sqlite3_mem_methods] structure
   1803 ** before the [sqlite3_config()] call returns.</dd>
   1804 **
   1805 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
   1806 ** <dd> ^(This option takes a single argument which is a pointer to an
   1807 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
   1808 ** structure is filled with the currently defined memory allocation routines.)^
   1809 ** This option can be used to overload the default memory allocation
   1810 ** routines with a wrapper that simulations memory allocation failure or
   1811 ** tracks memory usage, for example. </dd>
   1812 **
   1813 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
   1814 ** <dd> ^This option takes single argument of type int, interpreted as a
   1815 ** boolean, which enables or disables the collection of memory allocation
   1816 ** statistics. ^(When memory allocation statistics are disabled, the
   1817 ** following SQLite interfaces become non-operational:
   1818 **   <ul>
   1819 **   <li> [sqlite3_memory_used()]
   1820 **   <li> [sqlite3_memory_highwater()]
   1821 **   <li> [sqlite3_soft_heap_limit64()]
   1822 **   <li> [sqlite3_status()]
   1823 **   </ul>)^
   1824 ** ^Memory allocation statistics are enabled by default unless SQLite is
   1825 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
   1826 ** allocation statistics are disabled by default.
   1827 ** </dd>
   1828 **
   1829 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
   1830 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1831 ** scratch memory.  There are three arguments:  A pointer an 8-byte
   1832 ** aligned memory buffer from which the scrach allocations will be
   1833 ** drawn, the size of each scratch allocation (sz),
   1834 ** and the maximum number of scratch allocations (N).  The sz
   1835 ** argument must be a multiple of 16.
   1836 ** The first argument must be a pointer to an 8-byte aligned buffer
   1837 ** of at least sz*N bytes of memory.
   1838 ** ^SQLite will use no more than two scratch buffers per thread.  So
   1839 ** N should be set to twice the expected maximum number of threads.
   1840 ** ^SQLite will never require a scratch buffer that is more than 6
   1841 ** times the database page size. ^If SQLite needs needs additional
   1842 ** scratch memory beyond what is provided by this configuration option, then
   1843 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
   1844 **
   1845 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
   1846 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
   1847 ** the database page cache with the default page cache implemenation.
   1848 ** This configuration should not be used if an application-define page
   1849 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
   1850 ** There are three arguments to this option: A pointer to 8-byte aligned
   1851 ** memory, the size of each page buffer (sz), and the number of pages (N).
   1852 ** The sz argument should be the size of the largest database page
   1853 ** (a power of two between 512 and 32768) plus a little extra for each
   1854 ** page header.  ^The page header size is 20 to 40 bytes depending on
   1855 ** the host architecture.  ^It is harmless, apart from the wasted memory,
   1856 ** to make sz a little too large.  The first
   1857 ** argument should point to an allocation of at least sz*N bytes of memory.
   1858 ** ^SQLite will use the memory provided by the first argument to satisfy its
   1859 ** memory needs for the first N pages that it adds to cache.  ^If additional
   1860 ** page cache memory is needed beyond what is provided by this option, then
   1861 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
   1862 ** The pointer in the first argument must
   1863 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
   1864 ** will be undefined.</dd>
   1865 **
   1866 ** <dt>SQLITE_CONFIG_HEAP</dt>
   1867 ** <dd> ^This option specifies a static memory buffer that SQLite will use
   1868 ** for all of its dynamic memory allocation needs beyond those provided
   1869 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
   1870 ** There are three arguments: An 8-byte aligned pointer to the memory,
   1871 ** the number of bytes in the memory buffer, and the minimum allocation size.
   1872 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
   1873 ** to using its default memory allocator (the system malloc() implementation),
   1874 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
   1875 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
   1876 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
   1877 ** allocator is engaged to handle all of SQLites memory allocation needs.
   1878 ** The first pointer (the memory pointer) must be aligned to an 8-byte
   1879 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
   1880 **
   1881 ** <dt>SQLITE_CONFIG_MUTEX</dt>
   1882 ** <dd> ^(This option takes a single argument which is a pointer to an
   1883 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
   1884 ** alternative low-level mutex routines to be used in place
   1885 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
   1886 ** content of the [sqlite3_mutex_methods] structure before the call to
   1887 ** [sqlite3_config()] returns. ^If SQLite is compiled with
   1888 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1889 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1890 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
   1891 ** return [SQLITE_ERROR].</dd>
   1892 **
   1893 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
   1894 ** <dd> ^(This option takes a single argument which is a pointer to an
   1895 ** instance of the [sqlite3_mutex_methods] structure.  The
   1896 ** [sqlite3_mutex_methods]
   1897 ** structure is filled with the currently defined mutex routines.)^
   1898 ** This option can be used to overload the default mutex allocation
   1899 ** routines with a wrapper used to track mutex usage for performance
   1900 ** profiling or testing, for example.   ^If SQLite is compiled with
   1901 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
   1902 ** the entire mutexing subsystem is omitted from the build and hence calls to
   1903 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
   1904 ** return [SQLITE_ERROR].</dd>
   1905 **
   1906 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
   1907 ** <dd> ^(This option takes two arguments that determine the default
   1908 ** memory allocation for the lookaside memory allocator on each
   1909 ** [database connection].  The first argument is the
   1910 ** size of each lookaside buffer slot and the second is the number of
   1911 ** slots allocated to each database connection.)^  ^(This option sets the
   1912 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
   1913 ** verb to [sqlite3_db_config()] can be used to change the lookaside
   1914 ** configuration on individual connections.)^ </dd>
   1915 **
   1916 ** <dt>SQLITE_CONFIG_PCACHE</dt>
   1917 ** <dd> ^(This option takes a single argument which is a pointer to
   1918 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
   1919 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
   1920 ** object and uses it for page cache memory allocations.</dd>
   1921 **
   1922 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
   1923 ** <dd> ^(This option takes a single argument which is a pointer to an
   1924 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
   1925 ** page cache implementation into that object.)^ </dd>
   1926 **
   1927 ** <dt>SQLITE_CONFIG_LOG</dt>
   1928 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
   1929 ** function with a call signature of void(*)(void*,int,const char*),
   1930 ** and a pointer to void. ^If the function pointer is not NULL, it is
   1931 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
   1932 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
   1933 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
   1934 ** passed through as the first parameter to the application-defined logger
   1935 ** function whenever that function is invoked.  ^The second parameter to
   1936 ** the logger function is a copy of the first parameter to the corresponding
   1937 ** [sqlite3_log()] call and is intended to be a [result code] or an
   1938 ** [extended result code].  ^The third parameter passed to the logger is
   1939 ** log message after formatting via [sqlite3_snprintf()].
   1940 ** The SQLite logging interface is not reentrant; the logger function
   1941 ** supplied by the application must not invoke any SQLite interface.
   1942 ** In a multi-threaded application, the application-defined logger
   1943 ** function must be threadsafe. </dd>
   1944 **
   1945 ** </dl>
   1946 */
   1947 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
   1948 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
   1949 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
   1950 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
   1951 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
   1952 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
   1953 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
   1954 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
   1955 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
   1956 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
   1957 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
   1958 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
   1959 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
   1960 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
   1961 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
   1962 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
   1963 
   1964 /*
   1965 ** CAPI3REF: Database Connection Configuration Options
   1966 **
   1967 ** These constants are the available integer configuration options that
   1968 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
   1969 **
   1970 ** New configuration options may be added in future releases of SQLite.
   1971 ** Existing configuration options might be discontinued.  Applications
   1972 ** should check the return code from [sqlite3_db_config()] to make sure that
   1973 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
   1974 ** non-zero [error code] if a discontinued or unsupported configuration option
   1975 ** is invoked.
   1976 **
   1977 ** <dl>
   1978 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
   1979 ** <dd> ^This option takes three additional arguments that determine the
   1980 ** [lookaside memory allocator] configuration for the [database connection].
   1981 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
   1982 ** pointer to an memory buffer to use for lookaside memory.
   1983 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
   1984 ** may be NULL in which case SQLite will allocate the
   1985 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
   1986 ** size of each lookaside buffer slot.  ^The third argument is the number of
   1987 ** slots.  The size of the buffer in the first argument must be greater than
   1988 ** or equal to the product of the second and third arguments.  The buffer
   1989 ** must be aligned to an 8-byte boundary.  ^If the second argument to
   1990 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
   1991 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
   1992 ** configuration for a database connection can only be changed when that
   1993 ** connection is not currently using lookaside memory, or in other words
   1994 ** when the "current value" returned by
   1995 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
   1996 ** Any attempt to change the lookaside memory configuration when lookaside
   1997 ** memory is in use leaves the configuration unchanged and returns
   1998 ** [SQLITE_BUSY].)^</dd>
   1999 **
   2000 ** </dl>
   2001 */
   2002 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
   2003 
   2004 
   2005 /*
   2006 ** CAPI3REF: Enable Or Disable Extended Result Codes
   2007 **
   2008 ** ^The sqlite3_extended_result_codes() routine enables or disables the
   2009 ** [extended result codes] feature of SQLite. ^The extended result
   2010 ** codes are disabled by default for historical compatibility.
   2011 */
   2012 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
   2013 
   2014 /*
   2015 ** CAPI3REF: Last Insert Rowid
   2016 **
   2017 ** ^Each entry in an SQLite table has a unique 64-bit signed
   2018 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
   2019 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
   2020 ** names are not also used by explicitly declared columns. ^If
   2021 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
   2022 ** is another alias for the rowid.
   2023 **
   2024 ** ^This routine returns the [rowid] of the most recent
   2025 ** successful [INSERT] into the database from the [database connection]
   2026 ** in the first argument.  ^If no successful [INSERT]s
   2027 ** have ever occurred on that database connection, zero is returned.
   2028 **
   2029 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
   2030 ** row is returned by this routine as long as the trigger is running.
   2031 ** But once the trigger terminates, the value returned by this routine
   2032 ** reverts to the last value inserted before the trigger fired.)^
   2033 **
   2034 ** ^An [INSERT] that fails due to a constraint violation is not a
   2035 ** successful [INSERT] and does not change the value returned by this
   2036 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
   2037 ** and INSERT OR ABORT make no changes to the return value of this
   2038 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
   2039 ** encounters a constraint violation, it does not fail.  The
   2040 ** INSERT continues to completion after deleting rows that caused
   2041 ** the constraint problem so INSERT OR REPLACE will always change
   2042 ** the return value of this interface.)^
   2043 **
   2044 ** ^For the purposes of this routine, an [INSERT] is considered to
   2045 ** be successful even if it is subsequently rolled back.
   2046 **
   2047 ** This function is accessible to SQL statements via the
   2048 ** [last_insert_rowid() SQL function].
   2049 **
   2050 ** If a separate thread performs a new [INSERT] on the same
   2051 ** database connection while the [sqlite3_last_insert_rowid()]
   2052 ** function is running and thus changes the last insert [rowid],
   2053 ** then the value returned by [sqlite3_last_insert_rowid()] is
   2054 ** unpredictable and might not equal either the old or the new
   2055 ** last insert [rowid].
   2056 */
   2057 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
   2058 
   2059 /*
   2060 ** CAPI3REF: Count The Number Of Rows Modified
   2061 **
   2062 ** ^This function returns the number of database rows that were changed
   2063 ** or inserted or deleted by the most recently completed SQL statement
   2064 ** on the [database connection] specified by the first parameter.
   2065 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
   2066 ** or [DELETE] statement are counted.  Auxiliary changes caused by
   2067 ** triggers or [foreign key actions] are not counted.)^ Use the
   2068 ** [sqlite3_total_changes()] function to find the total number of changes
   2069 ** including changes caused by triggers and foreign key actions.
   2070 **
   2071 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
   2072 ** are not counted.  Only real table changes are counted.
   2073 **
   2074 ** ^(A "row change" is a change to a single row of a single table
   2075 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
   2076 ** are changed as side effects of [REPLACE] constraint resolution,
   2077 ** rollback, ABORT processing, [DROP TABLE], or by any other
   2078 ** mechanisms do not count as direct row changes.)^
   2079 **
   2080 ** A "trigger context" is a scope of execution that begins and
   2081 ** ends with the script of a [CREATE TRIGGER | trigger].
   2082 ** Most SQL statements are
   2083 ** evaluated outside of any trigger.  This is the "top level"
   2084 ** trigger context.  If a trigger fires from the top level, a
   2085 ** new trigger context is entered for the duration of that one
   2086 ** trigger.  Subtriggers create subcontexts for their duration.
   2087 **
   2088 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
   2089 ** not create a new trigger context.
   2090 **
   2091 ** ^This function returns the number of direct row changes in the
   2092 ** most recent INSERT, UPDATE, or DELETE statement within the same
   2093 ** trigger context.
   2094 **
   2095 ** ^Thus, when called from the top level, this function returns the
   2096 ** number of changes in the most recent INSERT, UPDATE, or DELETE
   2097 ** that also occurred at the top level.  ^(Within the body of a trigger,
   2098 ** the sqlite3_changes() interface can be called to find the number of
   2099 ** changes in the most recently completed INSERT, UPDATE, or DELETE
   2100 ** statement within the body of the same trigger.
   2101 ** However, the number returned does not include changes
   2102 ** caused by subtriggers since those have their own context.)^
   2103 **
   2104 ** See also the [sqlite3_total_changes()] interface, the
   2105 ** [count_changes pragma], and the [changes() SQL function].
   2106 **
   2107 ** If a separate thread makes changes on the same database connection
   2108 ** while [sqlite3_changes()] is running then the value returned
   2109 ** is unpredictable and not meaningful.
   2110 */
   2111 SQLITE_API int sqlite3_changes(sqlite3*);
   2112 
   2113 /*
   2114 ** CAPI3REF: Total Number Of Rows Modified
   2115 **
   2116 ** ^This function returns the number of row changes caused by [INSERT],
   2117 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
   2118 ** ^(The count returned by sqlite3_total_changes() includes all changes
   2119 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
   2120 ** [foreign key actions]. However,
   2121 ** the count does not include changes used to implement [REPLACE] constraints,
   2122 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
   2123 ** count does not include rows of views that fire an [INSTEAD OF trigger],
   2124 ** though if the INSTEAD OF trigger makes changes of its own, those changes
   2125 ** are counted.)^
   2126 ** ^The sqlite3_total_changes() function counts the changes as soon as
   2127 ** the statement that makes them is completed (when the statement handle
   2128 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
   2129 **
   2130 ** See also the [sqlite3_changes()] interface, the
   2131 ** [count_changes pragma], and the [total_changes() SQL function].
   2132 **
   2133 ** If a separate thread makes changes on the same database connection
   2134 ** while [sqlite3_total_changes()] is running then the value
   2135 ** returned is unpredictable and not meaningful.
   2136 */
   2137 SQLITE_API int sqlite3_total_changes(sqlite3*);
   2138 
   2139 /*
   2140 ** CAPI3REF: Interrupt A Long-Running Query
   2141 **
   2142 ** ^This function causes any pending database operation to abort and
   2143 ** return at its earliest opportunity. This routine is typically
   2144 ** called in response to a user action such as pressing "Cancel"
   2145 ** or Ctrl-C where the user wants a long query operation to halt
   2146 ** immediately.
   2147 **
   2148 ** ^It is safe to call this routine from a thread different from the
   2149 ** thread that is currently running the database operation.  But it
   2150 ** is not safe to call this routine with a [database connection] that
   2151 ** is closed or might close before sqlite3_interrupt() returns.
   2152 **
   2153 ** ^If an SQL operation is very nearly finished at the time when
   2154 ** sqlite3_interrupt() is called, then it might not have an opportunity
   2155 ** to be interrupted and might continue to completion.
   2156 **
   2157 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
   2158 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
   2159 ** that is inside an explicit transaction, then the entire transaction
   2160 ** will be rolled back automatically.
   2161 **
   2162 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
   2163 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
   2164 ** that are started after the sqlite3_interrupt() call and before the
   2165 ** running statements reaches zero are interrupted as if they had been
   2166 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
   2167 ** that are started after the running statement count reaches zero are
   2168 ** not effected by the sqlite3_interrupt().
   2169 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
   2170 ** SQL statements is a no-op and has no effect on SQL statements
   2171 ** that are started after the sqlite3_interrupt() call returns.
   2172 **
   2173 ** If the database connection closes while [sqlite3_interrupt()]
   2174 ** is running then bad things will likely happen.
   2175 */
   2176 SQLITE_API void sqlite3_interrupt(sqlite3*);
   2177 
   2178 /*
   2179 ** CAPI3REF: Determine If An SQL Statement Is Complete
   2180 **
   2181 ** These routines are useful during command-line input to determine if the
   2182 ** currently entered text seems to form a complete SQL statement or
   2183 ** if additional input is needed before sending the text into
   2184 ** SQLite for parsing.  ^These routines return 1 if the input string
   2185 ** appears to be a complete SQL statement.  ^A statement is judged to be
   2186 ** complete if it ends with a semicolon token and is not a prefix of a
   2187 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
   2188 ** string literals or quoted identifier names or comments are not
   2189 ** independent tokens (they are part of the token in which they are
   2190 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
   2191 ** and comments that follow the final semicolon are ignored.
   2192 **
   2193 ** ^These routines return 0 if the statement is incomplete.  ^If a
   2194 ** memory allocation fails, then SQLITE_NOMEM is returned.
   2195 **
   2196 ** ^These routines do not parse the SQL statements thus
   2197 ** will not detect syntactically incorrect SQL.
   2198 **
   2199 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
   2200 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
   2201 ** automatically by sqlite3_complete16().  If that initialization fails,
   2202 ** then the return value from sqlite3_complete16() will be non-zero
   2203 ** regardless of whether or not the input SQL is complete.)^
   2204 **
   2205 ** The input to [sqlite3_complete()] must be a zero-terminated
   2206 ** UTF-8 string.
   2207 **
   2208 ** The input to [sqlite3_complete16()] must be a zero-terminated
   2209 ** UTF-16 string in native byte order.
   2210 */
   2211 SQLITE_API int sqlite3_complete(const char *sql);
   2212 SQLITE_API int sqlite3_complete16(const void *sql);
   2213 
   2214 /*
   2215 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
   2216 **
   2217 ** ^This routine sets a callback function that might be invoked whenever
   2218 ** an attempt is made to open a database table that another thread
   2219 ** or process has locked.
   2220 **
   2221 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
   2222 ** is returned immediately upon encountering the lock.  ^If the busy callback
   2223 ** is not NULL, then the callback might be invoked with two arguments.
   2224 **
   2225 ** ^The first argument to the busy handler is a copy of the void* pointer which
   2226 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
   2227 ** the busy handler callback is the number of times that the busy handler has
   2228 ** been invoked for this locking event.  ^If the
   2229 ** busy callback returns 0, then no additional attempts are made to
   2230 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
   2231 ** ^If the callback returns non-zero, then another attempt
   2232 ** is made to open the database for reading and the cycle repeats.
   2233 **
   2234 ** The presence of a busy handler does not guarantee that it will be invoked
   2235 ** when there is lock contention. ^If SQLite determines that invoking the busy
   2236 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
   2237 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
   2238 ** Consider a scenario where one process is holding a read lock that
   2239 ** it is trying to promote to a reserved lock and
   2240 ** a second process is holding a reserved lock that it is trying
   2241 ** to promote to an exclusive lock.  The first process cannot proceed
   2242 ** because it is blocked by the second and the second process cannot
   2243 ** proceed because it is blocked by the first.  If both processes
   2244 ** invoke the busy handlers, neither will make any progress.  Therefore,
   2245 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
   2246 ** will induce the first process to release its read lock and allow
   2247 ** the second process to proceed.
   2248 **
   2249 ** ^The default busy callback is NULL.
   2250 **
   2251 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
   2252 ** when SQLite is in the middle of a large transaction where all the
   2253 ** changes will not fit into the in-memory cache.  SQLite will
   2254 ** already hold a RESERVED lock on the database file, but it needs
   2255 ** to promote this lock to EXCLUSIVE so that it can spill cache
   2256 ** pages into the database file without harm to concurrent
   2257 ** readers.  ^If it is unable to promote the lock, then the in-memory
   2258 ** cache will be left in an inconsistent state and so the error
   2259 ** code is promoted from the relatively benign [SQLITE_BUSY] to
   2260 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
   2261 ** forces an automatic rollback of the changes.  See the
   2262 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
   2263 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
   2264 ** this is important.
   2265 **
   2266 ** ^(There can only be a single busy handler defined for each
   2267 ** [database connection].  Setting a new busy handler clears any
   2268 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
   2269 ** will also set or clear the busy handler.
   2270 **
   2271 ** The busy callback should not take any actions which modify the
   2272 ** database connection that invoked the busy handler.  Any such actions
   2273 ** result in undefined behavior.
   2274 **
   2275 ** A busy handler must not close the database connection
   2276 ** or [prepared statement] that invoked the busy handler.
   2277 */
   2278 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
   2279 
   2280 /*
   2281 ** CAPI3REF: Set A Busy Timeout
   2282 **
   2283 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
   2284 ** for a specified amount of time when a table is locked.  ^The handler
   2285 ** will sleep multiple times until at least "ms" milliseconds of sleeping
   2286 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
   2287 ** the handler returns 0 which causes [sqlite3_step()] to return
   2288 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
   2289 **
   2290 ** ^Calling this routine with an argument less than or equal to zero
   2291 ** turns off all busy handlers.
   2292 **
   2293 ** ^(There can only be a single busy handler for a particular
   2294 ** [database connection] any any given moment.  If another busy handler
   2295 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
   2296 ** this routine, that other busy handler is cleared.)^
   2297 */
   2298 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
   2299 
   2300 /*
   2301 ** CAPI3REF: Convenience Routines For Running Queries
   2302 **
   2303 ** This is a legacy interface that is preserved for backwards compatibility.
   2304 ** Use of this interface is not recommended.
   2305 **
   2306 ** Definition: A <b>result table</b> is memory data structure created by the
   2307 ** [sqlite3_get_table()] interface.  A result table records the
   2308 ** complete query results from one or more queries.
   2309 **
   2310 ** The table conceptually has a number of rows and columns.  But
   2311 ** these numbers are not part of the result table itself.  These
   2312 ** numbers are obtained separately.  Let N be the number of rows
   2313 ** and M be the number of columns.
   2314 **
   2315 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
   2316 ** There are (N+1)*M elements in the array.  The first M pointers point
   2317 ** to zero-terminated strings that  contain the names of the columns.
   2318 ** The remaining entries all point to query results.  NULL values result
   2319 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
   2320 ** string representation as returned by [sqlite3_column_text()].
   2321 **
   2322 ** A result table might consist of one or more memory allocations.
   2323 ** It is not safe to pass a result table directly to [sqlite3_free()].
   2324 ** A result table should be deallocated using [sqlite3_free_table()].
   2325 **
   2326 ** ^(As an example of the result table format, suppose a query result
   2327 ** is as follows:
   2328 **
   2329 ** <blockquote><pre>
   2330 **        Name        | Age
   2331 **        -----------------------
   2332 **        Alice       | 43
   2333 **        Bob         | 28
   2334 **        Cindy       | 21
   2335 ** </pre></blockquote>
   2336 **
   2337 ** There are two column (M==2) and three rows (N==3).  Thus the
   2338 ** result table has 8 entries.  Suppose the result table is stored
   2339 ** in an array names azResult.  Then azResult holds this content:
   2340 **
   2341 ** <blockquote><pre>
   2342 **        azResult&#91;0] = "Name";
   2343 **        azResult&#91;1] = "Age";
   2344 **        azResult&#91;2] = "Alice";
   2345 **        azResult&#91;3] = "43";
   2346 **        azResult&#91;4] = "Bob";
   2347 **        azResult&#91;5] = "28";
   2348 **        azResult&#91;6] = "Cindy";
   2349 **        azResult&#91;7] = "21";
   2350 ** </pre></blockquote>)^
   2351 **
   2352 ** ^The sqlite3_get_table() function evaluates one or more
   2353 ** semicolon-separated SQL statements in the zero-terminated UTF-8
   2354 ** string of its 2nd parameter and returns a result table to the
   2355 ** pointer given in its 3rd parameter.
   2356 **
   2357 ** After the application has finished with the result from sqlite3_get_table(),
   2358 ** it must pass the result table pointer to sqlite3_free_table() in order to
   2359 ** release the memory that was malloced.  Because of the way the
   2360 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
   2361 ** function must not try to call [sqlite3_free()] directly.  Only
   2362 ** [sqlite3_free_table()] is able to release the memory properly and safely.
   2363 **
   2364 ** The sqlite3_get_table() interface is implemented as a wrapper around
   2365 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
   2366 ** to any internal data structures of SQLite.  It uses only the public
   2367 ** interface defined here.  As a consequence, errors that occur in the
   2368 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
   2369 ** reflected in subsequent calls to [sqlite3_errcode()] or
   2370 ** [sqlite3_errmsg()].
   2371 */
   2372 SQLITE_API int sqlite3_get_table(
   2373   sqlite3 *db,          /* An open database */
   2374   const char *zSql,     /* SQL to be evaluated */
   2375   char ***pazResult,    /* Results of the query */
   2376   int *pnRow,           /* Number of result rows written here */
   2377   int *pnColumn,        /* Number of result columns written here */
   2378   char **pzErrmsg       /* Error msg written here */
   2379 );
   2380 SQLITE_API void sqlite3_free_table(char **result);
   2381 
   2382 /*
   2383 ** CAPI3REF: Formatted String Printing Functions
   2384 **
   2385 ** These routines are work-alikes of the "printf()" family of functions
   2386 ** from the standard C library.
   2387 **
   2388 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
   2389 ** results into memory obtained from [sqlite3_malloc()].
   2390 ** The strings returned by these two routines should be
   2391 ** released by [sqlite3_free()].  ^Both routines return a
   2392 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
   2393 ** memory to hold the resulting string.
   2394 **
   2395 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
   2396 ** the standard C library.  The result is written into the
   2397 ** buffer supplied as the second parameter whose size is given by
   2398 ** the first parameter. Note that the order of the
   2399 ** first two parameters is reversed from snprintf().)^  This is an
   2400 ** historical accident that cannot be fixed without breaking
   2401 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
   2402 ** returns a pointer to its buffer instead of the number of
   2403 ** characters actually written into the buffer.)^  We admit that
   2404 ** the number of characters written would be a more useful return
   2405 ** value but we cannot change the implementation of sqlite3_snprintf()
   2406 ** now without breaking compatibility.
   2407 **
   2408 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
   2409 ** guarantees that the buffer is always zero-terminated.  ^The first
   2410 ** parameter "n" is the total size of the buffer, including space for
   2411 ** the zero terminator.  So the longest string that can be completely
   2412 ** written will be n-1 characters.
   2413 **
   2414 ** These routines all implement some additional formatting
   2415 ** options that are useful for constructing SQL statements.
   2416 ** All of the usual printf() formatting options apply.  In addition, there
   2417 ** is are "%q", "%Q", and "%z" options.
   2418 **
   2419 ** ^(The %q option works like %s in that it substitutes a null-terminated
   2420 ** string from the argument list.  But %q also doubles every '\'' character.
   2421 ** %q is designed for use inside a string literal.)^  By doubling each '\''
   2422 ** character it escapes that character and allows it to be inserted into
   2423 ** the string.
   2424 **
   2425 ** For example, assume the string variable zText contains text as follows:
   2426 **
   2427 ** <blockquote><pre>
   2428 **  char *zText = "It's a happy day!";
   2429 ** </pre></blockquote>
   2430 **
   2431 ** One can use this text in an SQL statement as follows:
   2432 **
   2433 ** <blockquote><pre>
   2434 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
   2435 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2436 **  sqlite3_free(zSQL);
   2437 ** </pre></blockquote>
   2438 **
   2439 ** Because the %q format string is used, the '\'' character in zText
   2440 ** is escaped and the SQL generated is as follows:
   2441 **
   2442 ** <blockquote><pre>
   2443 **  INSERT INTO table1 VALUES('It''s a happy day!')
   2444 ** </pre></blockquote>
   2445 **
   2446 ** This is correct.  Had we used %s instead of %q, the generated SQL
   2447 ** would have looked like this:
   2448 **
   2449 ** <blockquote><pre>
   2450 **  INSERT INTO table1 VALUES('It's a happy day!');
   2451 ** </pre></blockquote>
   2452 **
   2453 ** This second example is an SQL syntax error.  As a general rule you should
   2454 ** always use %q instead of %s when inserting text into a string literal.
   2455 **
   2456 ** ^(The %Q option works like %q except it also adds single quotes around
   2457 ** the outside of the total string.  Additionally, if the parameter in the
   2458 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
   2459 ** single quotes).)^  So, for example, one could say:
   2460 **
   2461 ** <blockquote><pre>
   2462 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
   2463 **  sqlite3_exec(db, zSQL, 0, 0, 0);
   2464 **  sqlite3_free(zSQL);
   2465 ** </pre></blockquote>
   2466 **
   2467 ** The code above will render a correct SQL statement in the zSQL
   2468 ** variable even if the zText variable is a NULL pointer.
   2469 **
   2470 ** ^(The "%z" formatting option works like "%s" but with the
   2471 ** addition that after the string has been read and copied into
   2472 ** the result, [sqlite3_free()] is called on the input string.)^
   2473 */
   2474 SQLITE_API char *sqlite3_mprintf(const char*,...);
   2475 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
   2476 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
   2477 
   2478 /*
   2479 ** CAPI3REF: Memory Allocation Subsystem
   2480 **
   2481 ** The SQLite core uses these three routines for all of its own
   2482 ** internal memory allocation needs. "Core" in the previous sentence
   2483 ** does not include operating-system specific VFS implementation.  The
   2484 ** Windows VFS uses native malloc() and free() for some operations.
   2485 **
   2486 ** ^The sqlite3_malloc() routine returns a pointer to a block
   2487 ** of memory at least N bytes in length, where N is the parameter.
   2488 ** ^If sqlite3_malloc() is unable to obtain sufficient free
   2489 ** memory, it returns a NULL pointer.  ^If the parameter N to
   2490 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
   2491 ** a NULL pointer.
   2492 **
   2493 ** ^Calling sqlite3_free() with a pointer previously returned
   2494 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
   2495 ** that it might be reused.  ^The sqlite3_free() routine is
   2496 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
   2497 ** to sqlite3_free() is harmless.  After being freed, memory
   2498 ** should neither be read nor written.  Even reading previously freed
   2499 ** memory might result in a segmentation fault or other severe error.
   2500 ** Memory corruption, a segmentation fault, or other severe error
   2501 ** might result if sqlite3_free() is called with a non-NULL pointer that
   2502 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
   2503 **
   2504 ** ^(The sqlite3_realloc() interface attempts to resize a
   2505 ** prior memory allocation to be at least N bytes, where N is the
   2506 ** second parameter.  The memory allocation to be resized is the first
   2507 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
   2508 ** is a NULL pointer then its behavior is identical to calling
   2509 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
   2510 ** ^If the second parameter to sqlite3_realloc() is zero or
   2511 ** negative then the behavior is exactly the same as calling
   2512 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
   2513 ** ^sqlite3_realloc() returns a pointer to a memory allocation
   2514 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
   2515 ** ^If M is the size of the prior allocation, then min(N,M) bytes
   2516 ** of the prior allocation are copied into the beginning of buffer returned
   2517 ** by sqlite3_realloc() and the prior allocation is freed.
   2518 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
   2519 ** is not freed.
   2520 **
   2521 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
   2522 ** is always aligned to at least an 8 byte boundary, or to a
   2523 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
   2524 ** option is used.
   2525 **
   2526 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
   2527 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
   2528 ** implementation of these routines to be omitted.  That capability
   2529 ** is no longer provided.  Only built-in memory allocators can be used.
   2530 **
   2531 ** The Windows OS interface layer calls
   2532 ** the system malloc() and free() directly when converting
   2533 ** filenames between the UTF-8 encoding used by SQLite
   2534 ** and whatever filename encoding is used by the particular Windows
   2535 ** installation.  Memory allocation errors are detected, but
   2536 ** they are reported back as [SQLITE_CANTOPEN] or
   2537 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
   2538 **
   2539 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
   2540 ** must be either NULL or else pointers obtained from a prior
   2541 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
   2542 ** not yet been released.
   2543 **
   2544 ** The application must not read or write any part of
   2545 ** a block of memory after it has been released using
   2546 ** [sqlite3_free()] or [sqlite3_realloc()].
   2547 */
   2548 SQLITE_API void *sqlite3_malloc(int);
   2549 SQLITE_API void *sqlite3_realloc(void*, int);
   2550 SQLITE_API void sqlite3_free(void*);
   2551 
   2552 /*
   2553 ** CAPI3REF: Memory Allocator Statistics
   2554 **
   2555 ** SQLite provides these two interfaces for reporting on the status
   2556 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
   2557 ** routines, which form the built-in memory allocation subsystem.
   2558 **
   2559 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
   2560 ** of memory currently outstanding (malloced but not freed).
   2561 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
   2562 ** value of [sqlite3_memory_used()] since the high-water mark
   2563 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
   2564 ** [sqlite3_memory_highwater()] include any overhead
   2565 ** added by SQLite in its implementation of [sqlite3_malloc()],
   2566 ** but not overhead added by the any underlying system library
   2567 ** routines that [sqlite3_malloc()] may call.
   2568 **
   2569 ** ^The memory high-water mark is reset to the current value of
   2570 ** [sqlite3_memory_used()] if and only if the parameter to
   2571 ** [sqlite3_memory_highwater()] is true.  ^The value returned
   2572 ** by [sqlite3_memory_highwater(1)] is the high-water mark
   2573 ** prior to the reset.
   2574 */
   2575 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
   2576 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
   2577 
   2578 /*
   2579 ** CAPI3REF: Pseudo-Random Number Generator
   2580 **
   2581 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
   2582 ** select random [ROWID | ROWIDs] when inserting new records into a table that
   2583 ** already uses the largest possible [ROWID].  The PRNG is also used for
   2584 ** the build-in random() and randomblob() SQL functions.  This interface allows
   2585 ** applications to access the same PRNG for other purposes.
   2586 **
   2587 ** ^A call to this routine stores N bytes of randomness into buffer P.
   2588 **
   2589 ** ^The first time this routine is invoked (either internally or by
   2590 ** the application) the PRNG is seeded using randomness obtained
   2591 ** from the xRandomness method of the default [sqlite3_vfs] object.
   2592 ** ^On all subsequent invocations, the pseudo-randomness is generated
   2593 ** internally and without recourse to the [sqlite3_vfs] xRandomness
   2594 ** method.
   2595 */
   2596 SQLITE_API void sqlite3_randomness(int N, void *P);
   2597 
   2598 /*
   2599 ** CAPI3REF: Compile-Time Authorization Callbacks
   2600 **
   2601 ** ^This routine registers a authorizer callback with a particular
   2602 ** [database connection], supplied in the first argument.
   2603 ** ^The authorizer callback is invoked as SQL statements are being compiled
   2604 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
   2605 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
   2606 ** points during the compilation process, as logic is being created
   2607 ** to perform various actions, the authorizer callback is invoked to
   2608 ** see if those actions are allowed.  ^The authorizer callback should
   2609 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
   2610 ** specific action but allow the SQL statement to continue to be
   2611 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
   2612 ** rejected with an error.  ^If the authorizer callback returns
   2613 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
   2614 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
   2615 ** the authorizer will fail with an error message.
   2616 **
   2617 ** When the callback returns [SQLITE_OK], that means the operation
   2618 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
   2619 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
   2620 ** authorizer will fail with an error message explaining that
   2621 ** access is denied.
   2622 **
   2623 ** ^The first parameter to the authorizer callback is a copy of the third
   2624 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
   2625 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
   2626 ** the particular action to be authorized. ^The third through sixth parameters
   2627 ** to the callback are zero-terminated strings that contain additional
   2628 ** details about the action to be authorized.
   2629 **
   2630 ** ^If the action code is [SQLITE_READ]
   2631 ** and the callback returns [SQLITE_IGNORE] then the
   2632 ** [prepared statement] statement is constructed to substitute
   2633 ** a NULL value in place of the table column that would have
   2634 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
   2635 ** return can be used to deny an untrusted user access to individual
   2636 ** columns of a table.
   2637 ** ^If the action code is [SQLITE_DELETE] and the callback returns
   2638 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
   2639 ** [truncate optimization] is disabled and all rows are deleted individually.
   2640 **
   2641 ** An authorizer is used when [sqlite3_prepare | preparing]
   2642 ** SQL statements from an untrusted source, to ensure that the SQL statements
   2643 ** do not try to access data they are not allowed to see, or that they do not
   2644 ** try to execute malicious statements that damage the database.  For
   2645 ** example, an application may allow a user to enter arbitrary
   2646 ** SQL queries for evaluation by a database.  But the application does
   2647 ** not want the user to be able to make arbitrary changes to the
   2648 ** database.  An authorizer could then be put in place while the
   2649 ** user-entered SQL is being [sqlite3_prepare | prepared] that
   2650 ** disallows everything except [SELECT] statements.
   2651 **
   2652 ** Applications that need to process SQL from untrusted sources
   2653 ** might also consider lowering resource limits using [sqlite3_limit()]
   2654 ** and limiting database size using the [max_page_count] [PRAGMA]
   2655 ** in addition to using an authorizer.
   2656 **
   2657 ** ^(Only a single authorizer can be in place on a database connection
   2658 ** at a time.  Each call to sqlite3_set_authorizer overrides the
   2659 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
   2660 ** The authorizer is disabled by default.
   2661 **
   2662 ** The authorizer callback must not do anything that will modify
   2663 ** the database connection that invoked the authorizer callback.
   2664 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2665 ** database connections for the meaning of "modify" in this paragraph.
   2666 **
   2667 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
   2668 ** statement might be re-prepared during [sqlite3_step()] due to a
   2669 ** schema change.  Hence, the application should ensure that the
   2670 ** correct authorizer callback remains in place during the [sqlite3_step()].
   2671 **
   2672 ** ^Note that the authorizer callback is invoked only during
   2673 ** [sqlite3_prepare()] or its variants.  Authorization is not
   2674 ** performed during statement evaluation in [sqlite3_step()], unless
   2675 ** as stated in the previous paragraph, sqlite3_step() invokes
   2676 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
   2677 */
   2678 SQLITE_API int sqlite3_set_authorizer(
   2679   sqlite3*,
   2680   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   2681   void *pUserData
   2682 );
   2683 
   2684 /*
   2685 ** CAPI3REF: Authorizer Return Codes
   2686 **
   2687 ** The [sqlite3_set_authorizer | authorizer callback function] must
   2688 ** return either [SQLITE_OK] or one of these two constants in order
   2689 ** to signal SQLite whether or not the action is permitted.  See the
   2690 ** [sqlite3_set_authorizer | authorizer documentation] for additional
   2691 ** information.
   2692 */
   2693 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
   2694 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
   2695 
   2696 /*
   2697 ** CAPI3REF: Authorizer Action Codes
   2698 **
   2699 ** The [sqlite3_set_authorizer()] interface registers a callback function
   2700 ** that is invoked to authorize certain SQL statement actions.  The
   2701 ** second parameter to the callback is an integer code that specifies
   2702 ** what action is being authorized.  These are the integer action codes that
   2703 ** the authorizer callback may be passed.
   2704 **
   2705 ** These action code values signify what kind of operation is to be
   2706 ** authorized.  The 3rd and 4th parameters to the authorization
   2707 ** callback function will be parameters or NULL depending on which of these
   2708 ** codes is used as the second parameter.  ^(The 5th parameter to the
   2709 ** authorizer callback is the name of the database ("main", "temp",
   2710 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
   2711 ** is the name of the inner-most trigger or view that is responsible for
   2712 ** the access attempt or NULL if this access attempt is directly from
   2713 ** top-level SQL code.
   2714 */
   2715 /******************************************* 3rd ************ 4th ***********/
   2716 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
   2717 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
   2718 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
   2719 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
   2720 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
   2721 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
   2722 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
   2723 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
   2724 #define SQLITE_DELETE                9   /* Table Name      NULL            */
   2725 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
   2726 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
   2727 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
   2728 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
   2729 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
   2730 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
   2731 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
   2732 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
   2733 #define SQLITE_INSERT               18   /* Table Name      NULL            */
   2734 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
   2735 #define SQLITE_READ                 20   /* Table Name      Column Name     */
   2736 #define SQLITE_SELECT               21   /* NULL            NULL            */
   2737 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
   2738 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
   2739 #define SQLITE_ATTACH               24   /* Filename        NULL            */
   2740 #define SQLITE_DETACH               25   /* Database Name   NULL            */
   2741 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
   2742 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
   2743 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
   2744 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
   2745 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
   2746 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
   2747 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
   2748 #define SQLITE_COPY                  0   /* No longer used */
   2749 
   2750 /*
   2751 ** CAPI3REF: Tracing And Profiling Functions
   2752 **
   2753 ** These routines register callback functions that can be used for
   2754 ** tracing and profiling the execution of SQL statements.
   2755 **
   2756 ** ^The callback function registered by sqlite3_trace() is invoked at
   2757 ** various times when an SQL statement is being run by [sqlite3_step()].
   2758 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
   2759 ** SQL statement text as the statement first begins executing.
   2760 ** ^(Additional sqlite3_trace() callbacks might occur
   2761 ** as each triggered subprogram is entered.  The callbacks for triggers
   2762 ** contain a UTF-8 SQL comment that identifies the trigger.)^
   2763 **
   2764 ** ^The callback function registered by sqlite3_profile() is invoked
   2765 ** as each SQL statement finishes.  ^The profile callback contains
   2766 ** the original statement text and an estimate of wall-clock time
   2767 ** of how long that statement took to run.  ^The profile callback
   2768 ** time is in units of nanoseconds, however the current implementation
   2769 ** is only capable of millisecond resolution so the six least significant
   2770 ** digits in the time are meaningless.  Future versions of SQLite
   2771 ** might provide greater resolution on the profiler callback.  The
   2772 ** sqlite3_profile() function is considered experimental and is
   2773 ** subject to change in future versions of SQLite.
   2774 */
   2775 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
   2776 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
   2777    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
   2778 
   2779 /*
   2780 ** CAPI3REF: Query Progress Callbacks
   2781 **
   2782 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
   2783 ** function X to be invoked periodically during long running calls to
   2784 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
   2785 ** database connection D.  An example use for this
   2786 ** interface is to keep a GUI updated during a large query.
   2787 **
   2788 ** ^The parameter P is passed through as the only parameter to the
   2789 ** callback function X.  ^The parameter N is the number of
   2790 ** [virtual machine instructions] that are evaluated between successive
   2791 ** invocations of the callback X.
   2792 **
   2793 ** ^Only a single progress handler may be defined at one time per
   2794 ** [database connection]; setting a new progress handler cancels the
   2795 ** old one.  ^Setting parameter X to NULL disables the progress handler.
   2796 ** ^The progress handler is also disabled by setting N to a value less
   2797 ** than 1.
   2798 **
   2799 ** ^If the progress callback returns non-zero, the operation is
   2800 ** interrupted.  This feature can be used to implement a
   2801 ** "Cancel" button on a GUI progress dialog box.
   2802 **
   2803 ** The progress handler callback must not do anything that will modify
   2804 ** the database connection that invoked the progress handler.
   2805 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   2806 ** database connections for the meaning of "modify" in this paragraph.
   2807 **
   2808 */
   2809 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
   2810 
   2811 /*
   2812 ** CAPI3REF: Opening A New Database Connection
   2813 **
   2814 ** ^These routines open an SQLite database file whose name is given by the
   2815 ** filename argument. ^The filename argument is interpreted as UTF-8 for
   2816 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
   2817 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
   2818 ** returned in *ppDb, even if an error occurs.  The only exception is that
   2819 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
   2820 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
   2821 ** object.)^ ^(If the database is opened (and/or created) successfully, then
   2822 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
   2823 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
   2824 ** an English language description of the error following a failure of any
   2825 ** of the sqlite3_open() routines.
   2826 **
   2827 ** ^The default encoding for the database will be UTF-8 if
   2828 ** sqlite3_open() or sqlite3_open_v2() is called and
   2829 ** UTF-16 in the native byte order if sqlite3_open16() is used.
   2830 **
   2831 ** Whether or not an error occurs when it is opened, resources
   2832 ** associated with the [database connection] handle should be released by
   2833 ** passing it to [sqlite3_close()] when it is no longer required.
   2834 **
   2835 ** The sqlite3_open_v2() interface works like sqlite3_open()
   2836 ** except that it accepts two additional parameters for additional control
   2837 ** over the new database connection.  ^(The flags parameter to
   2838 ** sqlite3_open_v2() can take one of
   2839 ** the following three values, optionally combined with the
   2840 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
   2841 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
   2842 **
   2843 ** <dl>
   2844 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
   2845 ** <dd>The database is opened in read-only mode.  If the database does not
   2846 ** already exist, an error is returned.</dd>)^
   2847 **
   2848 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
   2849 ** <dd>The database is opened for reading and writing if possible, or reading
   2850 ** only if the file is write protected by the operating system.  In either
   2851 ** case the database must already exist, otherwise an error is returned.</dd>)^
   2852 **
   2853 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
   2854 ** <dd>The database is opened for reading and writing, and is creates it if
   2855 ** it does not already exist. This is the behavior that is always used for
   2856 ** sqlite3_open() and sqlite3_open16().</dd>)^
   2857 ** </dl>
   2858 **
   2859 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
   2860 ** combinations shown above or one of the combinations shown above combined
   2861 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
   2862 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
   2863 ** then the behavior is undefined.
   2864 **
   2865 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
   2866 ** opens in the multi-thread [threading mode] as long as the single-thread
   2867 ** mode has not been set at compile-time or start-time.  ^If the
   2868 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
   2869 ** in the serialized [threading mode] unless single-thread was
   2870 ** previously selected at compile-time or start-time.
   2871 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
   2872 ** eligible to use [shared cache mode], regardless of whether or not shared
   2873 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
   2874 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
   2875 ** participate in [shared cache mode] even if it is enabled.
   2876 **
   2877 ** ^If the filename is ":memory:", then a private, temporary in-memory database
   2878 ** is created for the connection.  ^This in-memory database will vanish when
   2879 ** the database connection is closed.  Future versions of SQLite might
   2880 ** make use of additional special filenames that begin with the ":" character.
   2881 ** It is recommended that when a database filename actually does begin with
   2882 ** a ":" character you should prefix the filename with a pathname such as
   2883 ** "./" to avoid ambiguity.
   2884 **
   2885 ** ^If the filename is an empty string, then a private, temporary
   2886 ** on-disk database will be created.  ^This private database will be
   2887 ** automatically deleted as soon as the database connection is closed.
   2888 **
   2889 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
   2890 ** [sqlite3_vfs] object that defines the operating system interface that
   2891 ** the new database connection should use.  ^If the fourth parameter is
   2892 ** a NULL pointer then the default [sqlite3_vfs] object is used.
   2893 **
   2894 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
   2895 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
   2896 ** codepage is currently defined.  Filenames containing international
   2897 ** characters must be converted to UTF-8 prior to passing them into
   2898 ** sqlite3_open() or sqlite3_open_v2().
   2899 */
   2900 SQLITE_API int sqlite3_open(
   2901   const char *filename,   /* Database filename (UTF-8) */
   2902   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2903 );
   2904 SQLITE_API int sqlite3_open16(
   2905   const void *filename,   /* Database filename (UTF-16) */
   2906   sqlite3 **ppDb          /* OUT: SQLite db handle */
   2907 );
   2908 SQLITE_API int sqlite3_open_v2(
   2909   const char *filename,   /* Database filename (UTF-8) */
   2910   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   2911   int flags,              /* Flags */
   2912   const char *zVfs        /* Name of VFS module to use */
   2913 );
   2914 
   2915 /*
   2916 ** CAPI3REF: Error Codes And Messages
   2917 **
   2918 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
   2919 ** [extended result code] for the most recent failed sqlite3_* API call
   2920 ** associated with a [database connection]. If a prior API call failed
   2921 ** but the most recent API call succeeded, the return value from
   2922 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
   2923 ** interface is the same except that it always returns the
   2924 ** [extended result code] even when extended result codes are
   2925 ** disabled.
   2926 **
   2927 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
   2928 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
   2929 ** ^(Memory to hold the error message string is managed internally.
   2930 ** The application does not need to worry about freeing the result.
   2931 ** However, the error string might be overwritten or deallocated by
   2932 ** subsequent calls to other SQLite interface functions.)^
   2933 **
   2934 ** When the serialized [threading mode] is in use, it might be the
   2935 ** case that a second error occurs on a separate thread in between
   2936 ** the time of the first error and the call to these interfaces.
   2937 ** When that happens, the second error will be reported since these
   2938 ** interfaces always report the most recent result.  To avoid
   2939 ** this, each thread can obtain exclusive use of the [database connection] D
   2940 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
   2941 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
   2942 ** all calls to the interfaces listed here are completed.
   2943 **
   2944 ** If an interface fails with SQLITE_MISUSE, that means the interface
   2945 ** was invoked incorrectly by the application.  In that case, the
   2946 ** error code and message may or may not be set.
   2947 */
   2948 SQLITE_API int sqlite3_errcode(sqlite3 *db);
   2949 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
   2950 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
   2951 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
   2952 
   2953 /*
   2954 ** CAPI3REF: SQL Statement Object
   2955 ** KEYWORDS: {prepared statement} {prepared statements}
   2956 **
   2957 ** An instance of this object represents a single SQL statement.
   2958 ** This object is variously known as a "prepared statement" or a
   2959 ** "compiled SQL statement" or simply as a "statement".
   2960 **
   2961 ** The life of a statement object goes something like this:
   2962 **
   2963 ** <ol>
   2964 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
   2965 **      function.
   2966 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
   2967 **      interfaces.
   2968 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
   2969 ** <li> Reset the statement using [sqlite3_reset()] then go back
   2970 **      to step 2.  Do this zero or more times.
   2971 ** <li> Destroy the object using [sqlite3_finalize()].
   2972 ** </ol>
   2973 **
   2974 ** Refer to documentation on individual methods above for additional
   2975 ** information.
   2976 */
   2977 typedef struct sqlite3_stmt sqlite3_stmt;
   2978 
   2979 /*
   2980 ** CAPI3REF: Run-time Limits
   2981 **
   2982 ** ^(This interface allows the size of various constructs to be limited
   2983 ** on a connection by connection basis.  The first parameter is the
   2984 ** [database connection] whose limit is to be set or queried.  The
   2985 ** second parameter is one of the [limit categories] that define a
   2986 ** class of constructs to be size limited.  The third parameter is the
   2987 ** new limit for that construct.)^
   2988 **
   2989 ** ^If the new limit is a negative number, the limit is unchanged.
   2990 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
   2991 ** [limits | hard upper bound]
   2992 ** set at compile-time by a C preprocessor macro called
   2993 ** [limits | SQLITE_MAX_<i>NAME</i>].
   2994 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
   2995 ** ^Attempts to increase a limit above its hard upper bound are
   2996 ** silently truncated to the hard upper bound.
   2997 **
   2998 ** ^Regardless of whether or not the limit was changed, the
   2999 ** [sqlite3_limit()] interface returns the prior value of the limit.
   3000 ** ^Hence, to find the current value of a limit without changing it,
   3001 ** simply invoke this interface with the third parameter set to -1.
   3002 **
   3003 ** Run-time limits are intended for use in applications that manage
   3004 ** both their own internal database and also databases that are controlled
   3005 ** by untrusted external sources.  An example application might be a
   3006 ** web browser that has its own databases for storing history and
   3007 ** separate databases controlled by JavaScript applications downloaded
   3008 ** off the Internet.  The internal databases can be given the
   3009 ** large, default limits.  Databases managed by external sources can
   3010 ** be given much smaller limits designed to prevent a denial of service
   3011 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
   3012 ** interface to further control untrusted SQL.  The size of the database
   3013 ** created by an untrusted script can be contained using the
   3014 ** [max_page_count] [PRAGMA].
   3015 **
   3016 ** New run-time limit categories may be added in future releases.
   3017 */
   3018 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
   3019 
   3020 /*
   3021 ** CAPI3REF: Run-Time Limit Categories
   3022 ** KEYWORDS: {limit category} {*limit categories}
   3023 **
   3024 ** These constants define various performance limits
   3025 ** that can be lowered at run-time using [sqlite3_limit()].
   3026 ** The synopsis of the meanings of the various limits is shown below.
   3027 ** Additional information is available at [limits | Limits in SQLite].
   3028 **
   3029 ** <dl>
   3030 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
   3031 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
   3032 **
   3033 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
   3034 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
   3035 **
   3036 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
   3037 ** <dd>The maximum number of columns in a table definition or in the
   3038 ** result set of a [SELECT] or the maximum number of columns in an index
   3039 ** or in an ORDER BY or GROUP BY clause.</dd>)^
   3040 **
   3041 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
   3042 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
   3043 **
   3044 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
   3045 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
   3046 **
   3047 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
   3048 ** <dd>The maximum number of instructions in a virtual machine program
   3049 ** used to implement an SQL statement.  This limit is not currently
   3050 ** enforced, though that might be added in some future release of
   3051 ** SQLite.</dd>)^
   3052 **
   3053 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
   3054 ** <dd>The maximum number of arguments on a function.</dd>)^
   3055 **
   3056 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
   3057 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
   3058 **
   3059 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
   3060 ** <dd>The maximum length of the pattern argument to the [LIKE] or
   3061 ** [GLOB] operators.</dd>)^
   3062 **
   3063 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
   3064 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
   3065 **
   3066 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
   3067 ** <dd>The maximum depth of recursion for triggers.</dd>)^
   3068 ** </dl>
   3069 */
   3070 #define SQLITE_LIMIT_LENGTH                    0
   3071 #define SQLITE_LIMIT_SQL_LENGTH                1
   3072 #define SQLITE_LIMIT_COLUMN                    2
   3073 #define SQLITE_LIMIT_EXPR_DEPTH                3
   3074 #define SQLITE_LIMIT_COMPOUND_SELECT           4
   3075 #define SQLITE_LIMIT_VDBE_OP                   5
   3076 #define SQLITE_LIMIT_FUNCTION_ARG              6
   3077 #define SQLITE_LIMIT_ATTACHED                  7
   3078 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   3079 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
   3080 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
   3081 
   3082 /*
   3083 ** CAPI3REF: Compiling An SQL Statement
   3084 ** KEYWORDS: {SQL statement compiler}
   3085 **
   3086 ** To execute an SQL query, it must first be compiled into a byte-code
   3087 ** program using one of these routines.
   3088 **
   3089 ** The first argument, "db", is a [database connection] obtained from a
   3090 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
   3091 ** [sqlite3_open16()].  The database connection must not have been closed.
   3092 **
   3093 ** The second argument, "zSql", is the statement to be compiled, encoded
   3094 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
   3095 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
   3096 ** use UTF-16.
   3097 **
   3098 ** ^If the nByte argument is less than zero, then zSql is read up to the
   3099 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
   3100 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
   3101 ** zSql string ends at either the first '\000' or '\u0000' character or
   3102 ** the nByte-th byte, whichever comes first. If the caller knows
   3103 ** that the supplied string is nul-terminated, then there is a small
   3104 ** performance advantage to be gained by passing an nByte parameter that
   3105 ** is equal to the number of bytes in the input string <i>including</i>
   3106 ** the nul-terminator bytes.
   3107 **
   3108 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
   3109 ** past the end of the first SQL statement in zSql.  These routines only
   3110 ** compile the first statement in zSql, so *pzTail is left pointing to
   3111 ** what remains uncompiled.
   3112 **
   3113 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
   3114 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
   3115 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
   3116 ** string or a comment) then *ppStmt is set to NULL.
   3117 ** The calling procedure is responsible for deleting the compiled
   3118 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
   3119 ** ppStmt may not be NULL.
   3120 **
   3121 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
   3122 ** otherwise an [error code] is returned.
   3123 **
   3124 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
   3125 ** recommended for all new programs. The two older interfaces are retained
   3126 ** for backwards compatibility, but their use is discouraged.
   3127 ** ^In the "v2" interfaces, the prepared statement
   3128 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
   3129 ** original SQL text. This causes the [sqlite3_step()] interface to
   3130 ** behave differently in three ways:
   3131 **
   3132 ** <ol>
   3133 ** <li>
   3134 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
   3135 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
   3136 ** statement and try to run it again.
   3137 ** </li>
   3138 **
   3139 ** <li>
   3140 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
   3141 ** [error codes] or [extended error codes].  ^The legacy behavior was that
   3142 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
   3143 ** and the application would have to make a second call to [sqlite3_reset()]
   3144 ** in order to find the underlying cause of the problem. With the "v2" prepare
   3145 ** interfaces, the underlying reason for the error is returned immediately.
   3146 ** </li>
   3147 **
   3148 ** <li>
   3149 ** ^If the specific value bound to [parameter | host parameter] in the
   3150 ** WHERE clause might influence the choice of query plan for a statement,
   3151 ** then the statement will be automatically recompiled, as if there had been
   3152 ** a schema change, on the first  [sqlite3_step()] call following any change
   3153 ** to the [sqlite3_bind_text | bindings] of that [parameter].
   3154 ** ^The specific value of WHERE-clause [parameter] might influence the
   3155 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
   3156 ** or [GLOB] operator or if the parameter is compared to an indexed column
   3157 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
   3158 ** the
   3159 ** </li>
   3160 ** </ol>
   3161 */
   3162 SQLITE_API int sqlite3_prepare(
   3163   sqlite3 *db,            /* Database handle */
   3164   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3165   int nByte,              /* Maximum length of zSql in bytes. */
   3166   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3167   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3168 );
   3169 SQLITE_API int sqlite3_prepare_v2(
   3170   sqlite3 *db,            /* Database handle */
   3171   const char *zSql,       /* SQL statement, UTF-8 encoded */
   3172   int nByte,              /* Maximum length of zSql in bytes. */
   3173   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3174   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
   3175 );
   3176 SQLITE_API int sqlite3_prepare16(
   3177   sqlite3 *db,            /* Database handle */
   3178   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3179   int nByte,              /* Maximum length of zSql in bytes. */
   3180   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3181   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3182 );
   3183 SQLITE_API int sqlite3_prepare16_v2(
   3184   sqlite3 *db,            /* Database handle */
   3185   const void *zSql,       /* SQL statement, UTF-16 encoded */
   3186   int nByte,              /* Maximum length of zSql in bytes. */
   3187   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
   3188   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
   3189 );
   3190 
   3191 /*
   3192 ** CAPI3REF: Retrieving Statement SQL
   3193 **
   3194 ** ^This interface can be used to retrieve a saved copy of the original
   3195 ** SQL text used to create a [prepared statement] if that statement was
   3196 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
   3197 */
   3198 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
   3199 
   3200 /*
   3201 ** CAPI3REF: Determine If An SQL Statement Writes The Database
   3202 **
   3203 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
   3204 ** the [prepared statement] X is [SELECT] statement and false (zero) if
   3205 ** X is an [INSERT], [UPDATE], [DELETE], CREATE, DROP, [ANALYZE],
   3206 ** [ALTER], or [REINDEX] statement.
   3207 ** If X is a NULL pointer or any other kind of statement, including but
   3208 ** not limited to [ATTACH], [DETACH], [COMMIT], [ROLLBACK], [RELEASE],
   3209 ** [SAVEPOINT], [PRAGMA], or [VACUUM] the result of sqlite3_stmt_readonly(X) is
   3210 ** undefined.
   3211 */
   3212 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
   3213 
   3214 /*
   3215 ** CAPI3REF: Dynamically Typed Value Object
   3216 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
   3217 **
   3218 ** SQLite uses the sqlite3_value object to represent all values
   3219 ** that can be stored in a database table. SQLite uses dynamic typing
   3220 ** for the values it stores.  ^Values stored in sqlite3_value objects
   3221 ** can be integers, floating point values, strings, BLOBs, or NULL.
   3222 **
   3223 ** An sqlite3_value object may be either "protected" or "unprotected".
   3224 ** Some interfaces require a protected sqlite3_value.  Other interfaces
   3225 ** will accept either a protected or an unprotected sqlite3_value.
   3226 ** Every interface that accepts sqlite3_value arguments specifies
   3227 ** whether or not it requires a protected sqlite3_value.
   3228 **
   3229 ** The terms "protected" and "unprotected" refer to whether or not
   3230 ** a mutex is held.  A internal mutex is held for a protected
   3231 ** sqlite3_value object but no mutex is held for an unprotected
   3232 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
   3233 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
   3234 ** or if SQLite is run in one of reduced mutex modes
   3235 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
   3236 ** then there is no distinction between protected and unprotected
   3237 ** sqlite3_value objects and they can be used interchangeably.  However,
   3238 ** for maximum code portability it is recommended that applications
   3239 ** still make the distinction between protected and unprotected
   3240 ** sqlite3_value objects even when not strictly required.
   3241 **
   3242 ** ^The sqlite3_value objects that are passed as parameters into the
   3243 ** implementation of [application-defined SQL functions] are protected.
   3244 ** ^The sqlite3_value object returned by
   3245 ** [sqlite3_column_value()] is unprotected.
   3246 ** Unprotected sqlite3_value objects may only be used with
   3247 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
   3248 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
   3249 ** interfaces require protected sqlite3_value objects.
   3250 */
   3251 typedef struct Mem sqlite3_value;
   3252 
   3253 /*
   3254 ** CAPI3REF: SQL Function Context Object
   3255 **
   3256 ** The context in which an SQL function executes is stored in an
   3257 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
   3258 ** is always first parameter to [application-defined SQL functions].
   3259 ** The application-defined SQL function implementation will pass this
   3260 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
   3261 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
   3262 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
   3263 ** and/or [sqlite3_set_auxdata()].
   3264 */
   3265 typedef struct sqlite3_context sqlite3_context;
   3266 
   3267 /*
   3268 ** CAPI3REF: Binding Values To Prepared Statements
   3269 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
   3270 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
   3271 **
   3272 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
   3273 ** literals may be replaced by a [parameter] that matches one of following
   3274 ** templates:
   3275 **
   3276 ** <ul>
   3277 ** <li>  ?
   3278 ** <li>  ?NNN
   3279 ** <li>  :VVV
   3280 ** <li>  @VVV
   3281 ** <li>  $VVV
   3282 ** </ul>
   3283 **
   3284 ** In the templates above, NNN represents an integer literal,
   3285 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
   3286 ** parameters (also called "host parameter names" or "SQL parameters")
   3287 ** can be set using the sqlite3_bind_*() routines defined here.
   3288 **
   3289 ** ^The first argument to the sqlite3_bind_*() routines is always
   3290 ** a pointer to the [sqlite3_stmt] object returned from
   3291 ** [sqlite3_prepare_v2()] or its variants.
   3292 **
   3293 ** ^The second argument is the index of the SQL parameter to be set.
   3294 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
   3295 ** SQL parameter is used more than once, second and subsequent
   3296 ** occurrences have the same index as the first occurrence.
   3297 ** ^The index for named parameters can be looked up using the
   3298 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
   3299 ** for "?NNN" parameters is the value of NNN.
   3300 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
   3301 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
   3302 **
   3303 ** ^The third argument is the value to bind to the parameter.
   3304 **
   3305 ** ^(In those routines that have a fourth argument, its value is the
   3306 ** number of bytes in the parameter.  To be clear: the value is the
   3307 ** number of <u>bytes</u> in the value, not the number of characters.)^
   3308 ** ^If the fourth parameter is negative, the length of the string is
   3309 ** the number of bytes up to the first zero terminator.
   3310 **
   3311 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
   3312 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
   3313 ** string after SQLite has finished with it.  ^The destructor is called
   3314 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
   3315 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
   3316 ** ^If the fifth argument is
   3317 ** the special value [SQLITE_STATIC], then SQLite assumes that the
   3318 ** information is in static, unmanaged space and does not need to be freed.
   3319 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
   3320 ** SQLite makes its own private copy of the data immediately, before
   3321 ** the sqlite3_bind_*() routine returns.
   3322 **
   3323 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
   3324 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
   3325 ** (just an integer to hold its size) while it is being processed.
   3326 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
   3327 ** content is later written using
   3328 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
   3329 ** ^A negative value for the zeroblob results in a zero-length BLOB.
   3330 **
   3331 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
   3332 ** for the [prepared statement] or with a prepared statement for which
   3333 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
   3334 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
   3335 ** routine is passed a [prepared statement] that has been finalized, the
   3336 ** result is undefined and probably harmful.
   3337 **
   3338 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
   3339 ** ^Unbound parameters are interpreted as NULL.
   3340 **
   3341 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
   3342 ** [error code] if anything goes wrong.
   3343 ** ^[SQLITE_RANGE] is returned if the parameter
   3344 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
   3345 **
   3346 ** See also: [sqlite3_bind_parameter_count()],
   3347 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
   3348 */
   3349 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
   3350 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
   3351 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
   3352 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
   3353 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
   3354 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
   3355 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
   3356 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
   3357 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
   3358 
   3359 /*
   3360 ** CAPI3REF: Number Of SQL Parameters
   3361 **
   3362 ** ^This routine can be used to find the number of [SQL parameters]
   3363 ** in a [prepared statement].  SQL parameters are tokens of the
   3364 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
   3365 ** placeholders for values that are [sqlite3_bind_blob | bound]
   3366 ** to the parameters at a later time.
   3367 **
   3368 ** ^(This routine actually returns the index of the largest (rightmost)
   3369 ** parameter. For all forms except ?NNN, this will correspond to the
   3370 ** number of unique parameters.  If parameters of the ?NNN form are used,
   3371 ** there may be gaps in the list.)^
   3372 **
   3373 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3374 ** [sqlite3_bind_parameter_name()], and
   3375 ** [sqlite3_bind_parameter_index()].
   3376 */
   3377 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
   3378 
   3379 /*
   3380 ** CAPI3REF: Name Of A Host Parameter
   3381 **
   3382 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
   3383 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
   3384 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3385 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
   3386 ** respectively.
   3387 ** In other words, the initial ":" or "$" or "@" or "?"
   3388 ** is included as part of the name.)^
   3389 ** ^Parameters of the form "?" without a following integer have no name
   3390 ** and are referred to as "nameless" or "anonymous parameters".
   3391 **
   3392 ** ^The first host parameter has an index of 1, not 0.
   3393 **
   3394 ** ^If the value N is out of range or if the N-th parameter is
   3395 ** nameless, then NULL is returned.  ^The returned string is
   3396 ** always in UTF-8 encoding even if the named parameter was
   3397 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
   3398 ** [sqlite3_prepare16_v2()].
   3399 **
   3400 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3401 ** [sqlite3_bind_parameter_count()], and
   3402 ** [sqlite3_bind_parameter_index()].
   3403 */
   3404 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
   3405 
   3406 /*
   3407 ** CAPI3REF: Index Of A Parameter With A Given Name
   3408 **
   3409 ** ^Return the index of an SQL parameter given its name.  ^The
   3410 ** index value returned is suitable for use as the second
   3411 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
   3412 ** is returned if no matching parameter is found.  ^The parameter
   3413 ** name must be given in UTF-8 even if the original statement
   3414 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
   3415 **
   3416 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
   3417 ** [sqlite3_bind_parameter_count()], and
   3418 ** [sqlite3_bind_parameter_index()].
   3419 */
   3420 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
   3421 
   3422 /*
   3423 ** CAPI3REF: Reset All Bindings On A Prepared Statement
   3424 **
   3425 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
   3426 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
   3427 ** ^Use this routine to reset all host parameters to NULL.
   3428 */
   3429 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
   3430 
   3431 /*
   3432 ** CAPI3REF: Number Of Columns In A Result Set
   3433 **
   3434 ** ^Return the number of columns in the result set returned by the
   3435 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
   3436 ** statement that does not return data (for example an [UPDATE]).
   3437 **
   3438 ** See also: [sqlite3_data_count()]
   3439 */
   3440 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
   3441 
   3442 /*
   3443 ** CAPI3REF: Column Names In A Result Set
   3444 **
   3445 ** ^These routines return the name assigned to a particular column
   3446 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
   3447 ** interface returns a pointer to a zero-terminated UTF-8 string
   3448 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
   3449 ** UTF-16 string.  ^The first parameter is the [prepared statement]
   3450 ** that implements the [SELECT] statement. ^The second parameter is the
   3451 ** column number.  ^The leftmost column is number 0.
   3452 **
   3453 ** ^The returned string pointer is valid until either the [prepared statement]
   3454 ** is destroyed by [sqlite3_finalize()] or until the next call to
   3455 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
   3456 **
   3457 ** ^If sqlite3_malloc() fails during the processing of either routine
   3458 ** (for example during a conversion from UTF-8 to UTF-16) then a
   3459 ** NULL pointer is returned.
   3460 **
   3461 ** ^The name of a result column is the value of the "AS" clause for
   3462 ** that column, if there is an AS clause.  If there is no AS clause
   3463 ** then the name of the column is unspecified and may change from
   3464 ** one release of SQLite to the next.
   3465 */
   3466 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
   3467 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
   3468 
   3469 /*
   3470 ** CAPI3REF: Source Of Data In A Query Result
   3471 **
   3472 ** ^These routines provide a means to determine the database, table, and
   3473 ** table column that is the origin of a particular result column in
   3474 ** [SELECT] statement.
   3475 ** ^The name of the database or table or column can be returned as
   3476 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
   3477 ** the database name, the _table_ routines return the table name, and
   3478 ** the origin_ routines return the column name.
   3479 ** ^The returned string is valid until the [prepared statement] is destroyed
   3480 ** using [sqlite3_finalize()] or until the same information is requested
   3481 ** again in a different encoding.
   3482 **
   3483 ** ^The names returned are the original un-aliased names of the
   3484 ** database, table, and column.
   3485 **
   3486 ** ^The first argument to these interfaces is a [prepared statement].
   3487 ** ^These functions return information about the Nth result column returned by
   3488 ** the statement, where N is the second function argument.
   3489 ** ^The left-most column is column 0 for these routines.
   3490 **
   3491 ** ^If the Nth column returned by the statement is an expression or
   3492 ** subquery and is not a column value, then all of these functions return
   3493 ** NULL.  ^These routine might also return NULL if a memory allocation error
   3494 ** occurs.  ^Otherwise, they return the name of the attached database, table,
   3495 ** or column that query result column was extracted from.
   3496 **
   3497 ** ^As with all other SQLite APIs, those whose names end with "16" return
   3498 ** UTF-16 encoded strings and the other functions return UTF-8.
   3499 **
   3500 ** ^These APIs are only available if the library was compiled with the
   3501 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
   3502 **
   3503 ** If two or more threads call one or more of these routines against the same
   3504 ** prepared statement and column at the same time then the results are
   3505 ** undefined.
   3506 **
   3507 ** If two or more threads call one or more
   3508 ** [sqlite3_column_database_name | column metadata interfaces]
   3509 ** for the same [prepared statement] and result column
   3510 ** at the same time then the results are undefined.
   3511 */
   3512 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
   3513 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
   3514 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
   3515 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
   3516 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
   3517 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
   3518 
   3519 /*
   3520 ** CAPI3REF: Declared Datatype Of A Query Result
   3521 **
   3522 ** ^(The first parameter is a [prepared statement].
   3523 ** If this statement is a [SELECT] statement and the Nth column of the
   3524 ** returned result set of that [SELECT] is a table column (not an
   3525 ** expression or subquery) then the declared type of the table
   3526 ** column is returned.)^  ^If the Nth column of the result set is an
   3527 ** expression or subquery, then a NULL pointer is returned.
   3528 ** ^The returned string is always UTF-8 encoded.
   3529 **
   3530 ** ^(For example, given the database schema:
   3531 **
   3532 ** CREATE TABLE t1(c1 VARIANT);
   3533 **
   3534 ** and the following statement to be compiled:
   3535 **
   3536 ** SELECT c1 + 1, c1 FROM t1;
   3537 **
   3538 ** this routine would return the string "VARIANT" for the second result
   3539 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
   3540 **
   3541 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
   3542 ** is declared to contain a particular type does not mean that the
   3543 ** data stored in that column is of the declared type.  SQLite is
   3544 ** strongly typed, but the typing is dynamic not static.  ^Type
   3545 ** is associated with individual values, not with the containers
   3546 ** used to hold those values.
   3547 */
   3548 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
   3549 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
   3550 
   3551 /*
   3552 ** CAPI3REF: Evaluate An SQL Statement
   3553 **
   3554 ** After a [prepared statement] has been prepared using either
   3555 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
   3556 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
   3557 ** must be called one or more times to evaluate the statement.
   3558 **
   3559 ** The details of the behavior of the sqlite3_step() interface depend
   3560 ** on whether the statement was prepared using the newer "v2" interface
   3561 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
   3562 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
   3563 ** new "v2" interface is recommended for new applications but the legacy
   3564 ** interface will continue to be supported.
   3565 **
   3566 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
   3567 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
   3568 ** ^With the "v2" interface, any of the other [result codes] or
   3569 ** [extended result codes] might be returned as well.
   3570 **
   3571 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
   3572 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
   3573 ** or occurs outside of an explicit transaction, then you can retry the
   3574 ** statement.  If the statement is not a [COMMIT] and occurs within a
   3575 ** explicit transaction then you should rollback the transaction before
   3576 ** continuing.
   3577 **
   3578 ** ^[SQLITE_DONE] means that the statement has finished executing
   3579 ** successfully.  sqlite3_step() should not be called again on this virtual
   3580 ** machine without first calling [sqlite3_reset()] to reset the virtual
   3581 ** machine back to its initial state.
   3582 **
   3583 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
   3584 ** is returned each time a new row of data is ready for processing by the
   3585 ** caller. The values may be accessed using the [column access functions].
   3586 ** sqlite3_step() is called again to retrieve the next row of data.
   3587 **
   3588 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
   3589 ** violation) has occurred.  sqlite3_step() should not be called again on
   3590 ** the VM. More information may be found by calling [sqlite3_errmsg()].
   3591 ** ^With the legacy interface, a more specific error code (for example,
   3592 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
   3593 ** can be obtained by calling [sqlite3_reset()] on the
   3594 ** [prepared statement].  ^In the "v2" interface,
   3595 ** the more specific error code is returned directly by sqlite3_step().
   3596 **
   3597 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
   3598 ** Perhaps it was called on a [prepared statement] that has
   3599 ** already been [sqlite3_finalize | finalized] or on one that had
   3600 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
   3601 ** be the case that the same database connection is being used by two or
   3602 ** more threads at the same moment in time.
   3603 **
   3604 ** For all versions of SQLite up to and including 3.6.23.1, it was required
   3605 ** after sqlite3_step() returned anything other than [SQLITE_ROW] that
   3606 ** [sqlite3_reset()] be called before any subsequent invocation of
   3607 ** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
   3608 ** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
   3609 ** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()]
   3610 ** automatically in this circumstance rather than returning [SQLITE_MISUSE].
   3611 **
   3612 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
   3613 ** API always returns a generic error code, [SQLITE_ERROR], following any
   3614 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
   3615 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
   3616 ** specific [error codes] that better describes the error.
   3617 ** We admit that this is a goofy design.  The problem has been fixed
   3618 ** with the "v2" interface.  If you prepare all of your SQL statements
   3619 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
   3620 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
   3621 ** then the more specific [error codes] are returned directly
   3622 ** by sqlite3_step().  The use of the "v2" interface is recommended.
   3623 */
   3624 SQLITE_API int sqlite3_step(sqlite3_stmt*);
   3625 
   3626 /*
   3627 ** CAPI3REF: Number of columns in a result set
   3628 **
   3629 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
   3630 ** current row of the result set of [prepared statement] P.
   3631 ** ^If prepared statement P does not have results ready to return
   3632 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
   3633 ** interfaces) then sqlite3_data_count(P) returns 0.
   3634 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
   3635 **
   3636 ** See also: [sqlite3_column_count()]
   3637 */
   3638 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
   3639 
   3640 /*
   3641 ** CAPI3REF: Fundamental Datatypes
   3642 ** KEYWORDS: SQLITE_TEXT
   3643 **
   3644 ** ^(Every value in SQLite has one of five fundamental datatypes:
   3645 **
   3646 ** <ul>
   3647 ** <li> 64-bit signed integer
   3648 ** <li> 64-bit IEEE floating point number
   3649 ** <li> string
   3650 ** <li> BLOB
   3651 ** <li> NULL
   3652 ** </ul>)^
   3653 **
   3654 ** These constants are codes for each of those types.
   3655 **
   3656 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
   3657 ** for a completely different meaning.  Software that links against both
   3658 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
   3659 ** SQLITE_TEXT.
   3660 */
   3661 #define SQLITE_INTEGER  1
   3662 #define SQLITE_FLOAT    2
   3663 #define SQLITE_BLOB     4
   3664 #define SQLITE_NULL     5
   3665 #ifdef SQLITE_TEXT
   3666 # undef SQLITE_TEXT
   3667 #else
   3668 # define SQLITE_TEXT     3
   3669 #endif
   3670 #define SQLITE3_TEXT     3
   3671 
   3672 /*
   3673 ** CAPI3REF: Result Values From A Query
   3674 ** KEYWORDS: {column access functions}
   3675 **
   3676 ** These routines form the "result set" interface.
   3677 **
   3678 ** ^These routines return information about a single column of the current
   3679 ** result row of a query.  ^In every case the first argument is a pointer
   3680 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
   3681 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
   3682 ** and the second argument is the index of the column for which information
   3683 ** should be returned. ^The leftmost column of the result set has the index 0.
   3684 ** ^The number of columns in the result can be determined using
   3685 ** [sqlite3_column_count()].
   3686 **
   3687 ** If the SQL statement does not currently point to a valid row, or if the
   3688 ** column index is out of range, the result is undefined.
   3689 ** These routines may only be called when the most recent call to
   3690 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
   3691 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
   3692 ** If any of these routines are called after [sqlite3_reset()] or
   3693 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
   3694 ** something other than [SQLITE_ROW], the results are undefined.
   3695 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
   3696 ** are called from a different thread while any of these routines
   3697 ** are pending, then the results are undefined.
   3698 **
   3699 ** ^The sqlite3_column_type() routine returns the
   3700 ** [SQLITE_INTEGER | datatype code] for the initial data type
   3701 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
   3702 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
   3703 ** returned by sqlite3_column_type() is only meaningful if no type
   3704 ** conversions have occurred as described below.  After a type conversion,
   3705 ** the value returned by sqlite3_column_type() is undefined.  Future
   3706 ** versions of SQLite may change the behavior of sqlite3_column_type()
   3707 ** following a type conversion.
   3708 **
   3709 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
   3710 ** routine returns the number of bytes in that BLOB or string.
   3711 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
   3712 ** the string to UTF-8 and then returns the number of bytes.
   3713 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
   3714 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
   3715 ** the number of bytes in that string.
   3716 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
   3717 **
   3718 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
   3719 ** routine returns the number of bytes in that BLOB or string.
   3720 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
   3721 ** the string to UTF-16 and then returns the number of bytes.
   3722 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
   3723 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
   3724 ** the number of bytes in that string.
   3725 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
   3726 **
   3727 ** ^The values returned by [sqlite3_column_bytes()] and
   3728 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
   3729 ** of the string.  ^For clarity: the values returned by
   3730 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
   3731 ** bytes in the string, not the number of characters.
   3732 **
   3733 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
   3734 ** even empty strings, are always zero terminated.  ^The return
   3735 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
   3736 **
   3737 ** ^The object returned by [sqlite3_column_value()] is an
   3738 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
   3739 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
   3740 ** If the [unprotected sqlite3_value] object returned by
   3741 ** [sqlite3_column_value()] is used in any other way, including calls
   3742 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
   3743 ** or [sqlite3_value_bytes()], then the behavior is undefined.
   3744 **
   3745 ** These routines attempt to convert the value where appropriate.  ^For
   3746 ** example, if the internal representation is FLOAT and a text result
   3747 ** is requested, [sqlite3_snprintf()] is used internally to perform the
   3748 ** conversion automatically.  ^(The following table details the conversions
   3749 ** that are applied:
   3750 **
   3751 ** <blockquote>
   3752 ** <table border="1">
   3753 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
   3754 **
   3755 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
   3756 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
   3757 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
   3758 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
   3759 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
   3760 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
   3761 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
   3762 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
   3763 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
   3764 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
   3765 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
   3766 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
   3767 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
   3768 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
   3769 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
   3770 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
   3771 ** </table>
   3772 ** </blockquote>)^
   3773 **
   3774 ** The table above makes reference to standard C library functions atoi()
   3775 ** and atof().  SQLite does not really use these functions.  It has its
   3776 ** own equivalent internal routines.  The atoi() and atof() names are
   3777 ** used in the table for brevity and because they are familiar to most
   3778 ** C programmers.
   3779 **
   3780 ** Note that when type conversions occur, pointers returned by prior
   3781 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
   3782 ** sqlite3_column_text16() may be invalidated.
   3783 ** Type conversions and pointer invalidations might occur
   3784 ** in the following cases:
   3785 **
   3786 ** <ul>
   3787 ** <li> The initial content is a BLOB and sqlite3_column_text() or
   3788 **      sqlite3_column_text16() is called.  A zero-terminator might
   3789 **      need to be added to the string.</li>
   3790 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
   3791 **      sqlite3_column_text16() is called.  The content must be converted
   3792 **      to UTF-16.</li>
   3793 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
   3794 **      sqlite3_column_text() is called.  The content must be converted
   3795 **      to UTF-8.</li>
   3796 ** </ul>
   3797 **
   3798 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
   3799 ** not invalidate a prior pointer, though of course the content of the buffer
   3800 ** that the prior pointer references will have been modified.  Other kinds
   3801 ** of conversion are done in place when it is possible, but sometimes they
   3802 ** are not possible and in those cases prior pointers are invalidated.
   3803 **
   3804 ** The safest and easiest to remember policy is to invoke these routines
   3805 ** in one of the following ways:
   3806 **
   3807 ** <ul>
   3808 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
   3809 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
   3810 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
   3811 ** </ul>
   3812 **
   3813 ** In other words, you should call sqlite3_column_text(),
   3814 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
   3815 ** into the desired format, then invoke sqlite3_column_bytes() or
   3816 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
   3817 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
   3818 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
   3819 ** with calls to sqlite3_column_bytes().
   3820 **
   3821 ** ^The pointers returned are valid until a type conversion occurs as
   3822 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
   3823 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
   3824 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
   3825 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
   3826 ** [sqlite3_free()].
   3827 **
   3828 ** ^(If a memory allocation error occurs during the evaluation of any
   3829 ** of these routines, a default value is returned.  The default value
   3830 ** is either the integer 0, the floating point number 0.0, or a NULL
   3831 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
   3832 ** [SQLITE_NOMEM].)^
   3833 */
   3834 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
   3835 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
   3836 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
   3837 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
   3838 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
   3839 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
   3840 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
   3841 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
   3842 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
   3843 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
   3844 
   3845 /*
   3846 ** CAPI3REF: Destroy A Prepared Statement Object
   3847 **
   3848 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
   3849 ** ^If the most recent evaluation of the statement encountered no errors or
   3850 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
   3851 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
   3852 ** sqlite3_finalize(S) returns the appropriate [error code] or
   3853 ** [extended error code].
   3854 **
   3855 ** ^The sqlite3_finalize(S) routine can be called at any point during
   3856 ** the life cycle of [prepared statement] S:
   3857 ** before statement S is ever evaluated, after
   3858 ** one or more calls to [sqlite3_reset()], or after any call
   3859 ** to [sqlite3_step()] regardless of whether or not the statement has
   3860 ** completed execution.
   3861 **
   3862 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
   3863 **
   3864 ** The application must finalize every [prepared statement] in order to avoid
   3865 ** resource leaks.  It is a grievous error for the application to try to use
   3866 ** a prepared statement after it has been finalized.  Any use of a prepared
   3867 ** statement after it has been finalized can result in undefined and
   3868 ** undesirable behavior such as segfaults and heap corruption.
   3869 */
   3870 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
   3871 
   3872 /*
   3873 ** CAPI3REF: Reset A Prepared Statement Object
   3874 **
   3875 ** The sqlite3_reset() function is called to reset a [prepared statement]
   3876 ** object back to its initial state, ready to be re-executed.
   3877 ** ^Any SQL statement variables that had values bound to them using
   3878 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
   3879 ** Use [sqlite3_clear_bindings()] to reset the bindings.
   3880 **
   3881 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
   3882 ** back to the beginning of its program.
   3883 **
   3884 ** ^If the most recent call to [sqlite3_step(S)] for the
   3885 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
   3886 ** or if [sqlite3_step(S)] has never before been called on S,
   3887 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
   3888 **
   3889 ** ^If the most recent call to [sqlite3_step(S)] for the
   3890 ** [prepared statement] S indicated an error, then
   3891 ** [sqlite3_reset(S)] returns an appropriate [error code].
   3892 **
   3893 ** ^The [sqlite3_reset(S)] interface does not change the values
   3894 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
   3895 */
   3896 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
   3897 
   3898 /*
   3899 ** CAPI3REF: Create Or Redefine SQL Functions
   3900 ** KEYWORDS: {function creation routines}
   3901 ** KEYWORDS: {application-defined SQL function}
   3902 ** KEYWORDS: {application-defined SQL functions}
   3903 **
   3904 ** ^These functions (collectively known as "function creation routines")
   3905 ** are used to add SQL functions or aggregates or to redefine the behavior
   3906 ** of existing SQL functions or aggregates.  The only differences between
   3907 ** these routines are the text encoding expected for
   3908 ** the the second parameter (the name of the function being created)
   3909 ** and the presence or absence of a destructor callback for
   3910 ** the application data pointer.
   3911 **
   3912 ** ^The first parameter is the [database connection] to which the SQL
   3913 ** function is to be added.  ^If an application uses more than one database
   3914 ** connection then application-defined SQL functions must be added
   3915 ** to each database connection separately.
   3916 **
   3917 ** ^The second parameter is the name of the SQL function to be created or
   3918 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
   3919 ** representation, exclusive of the zero-terminator.  ^Note that the name
   3920 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
   3921 ** ^Any attempt to create a function with a longer name
   3922 ** will result in [SQLITE_MISUSE] being returned.
   3923 **
   3924 ** ^The third parameter (nArg)
   3925 ** is the number of arguments that the SQL function or
   3926 ** aggregate takes. ^If this parameter is -1, then the SQL function or
   3927 ** aggregate may take any number of arguments between 0 and the limit
   3928 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
   3929 ** parameter is less than -1 or greater than 127 then the behavior is
   3930 ** undefined.
   3931 **
   3932 ** ^The fourth parameter, eTextRep, specifies what
   3933 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
   3934 ** its parameters.  Every SQL function implementation must be able to work
   3935 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
   3936 ** more efficient with one encoding than another.  ^An application may
   3937 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
   3938 ** times with the same function but with different values of eTextRep.
   3939 ** ^When multiple implementations of the same function are available, SQLite
   3940 ** will pick the one that involves the least amount of data conversion.
   3941 ** If there is only a single implementation which does not care what text
   3942 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
   3943 **
   3944 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
   3945 ** function can gain access to this pointer using [sqlite3_user_data()].)^
   3946 **
   3947 ** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
   3948 ** pointers to C-language functions that implement the SQL function or
   3949 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
   3950 ** callback only; NULL pointers must be passed as the xStep and xFinal
   3951 ** parameters. ^An aggregate SQL function requires an implementation of xStep
   3952 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
   3953 ** SQL function or aggregate, pass NULL poiners for all three function
   3954 ** callbacks.
   3955 **
   3956 ** ^(If the tenth parameter to sqlite3_create_function_v2() is not NULL,
   3957 ** then it is destructor for the application data pointer.
   3958 ** The destructor is invoked when the function is deleted, either by being
   3959 ** overloaded or when the database connection closes.)^
   3960 ** ^The destructor is also invoked if the call to
   3961 ** sqlite3_create_function_v2() fails.
   3962 ** ^When the destructor callback of the tenth parameter is invoked, it
   3963 ** is passed a single argument which is a copy of the application data
   3964 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
   3965 **
   3966 ** ^It is permitted to register multiple implementations of the same
   3967 ** functions with the same name but with either differing numbers of
   3968 ** arguments or differing preferred text encodings.  ^SQLite will use
   3969 ** the implementation that most closely matches the way in which the
   3970 ** SQL function is used.  ^A function implementation with a non-negative
   3971 ** nArg parameter is a better match than a function implementation with
   3972 ** a negative nArg.  ^A function where the preferred text encoding
   3973 ** matches the database encoding is a better
   3974 ** match than a function where the encoding is different.
   3975 ** ^A function where the encoding difference is between UTF16le and UTF16be
   3976 ** is a closer match than a function where the encoding difference is
   3977 ** between UTF8 and UTF16.
   3978 **
   3979 ** ^Built-in functions may be overloaded by new application-defined functions.
   3980 **
   3981 ** ^An application-defined function is permitted to call other
   3982 ** SQLite interfaces.  However, such calls must not
   3983 ** close the database connection nor finalize or reset the prepared
   3984 ** statement in which the function is running.
   3985 */
   3986 SQLITE_API int sqlite3_create_function(
   3987   sqlite3 *db,
   3988   const char *zFunctionName,
   3989   int nArg,
   3990   int eTextRep,
   3991   void *pApp,
   3992   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   3993   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   3994   void (*xFinal)(sqlite3_context*)
   3995 );
   3996 SQLITE_API int sqlite3_create_function16(
   3997   sqlite3 *db,
   3998   const void *zFunctionName,
   3999   int nArg,
   4000   int eTextRep,
   4001   void *pApp,
   4002   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4003   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4004   void (*xFinal)(sqlite3_context*)
   4005 );
   4006 SQLITE_API int sqlite3_create_function_v2(
   4007   sqlite3 *db,
   4008   const char *zFunctionName,
   4009   int nArg,
   4010   int eTextRep,
   4011   void *pApp,
   4012   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   4013   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   4014   void (*xFinal)(sqlite3_context*),
   4015   void(*xDestroy)(void*)
   4016 );
   4017 
   4018 /*
   4019 ** CAPI3REF: Text Encodings
   4020 **
   4021 ** These constant define integer codes that represent the various
   4022 ** text encodings supported by SQLite.
   4023 */
   4024 #define SQLITE_UTF8           1
   4025 #define SQLITE_UTF16LE        2
   4026 #define SQLITE_UTF16BE        3
   4027 #define SQLITE_UTF16          4    /* Use native byte order */
   4028 #define SQLITE_ANY            5    /* sqlite3_create_function only */
   4029 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
   4030 
   4031 /*
   4032 ** CAPI3REF: Deprecated Functions
   4033 ** DEPRECATED
   4034 **
   4035 ** These functions are [deprecated].  In order to maintain
   4036 ** backwards compatibility with older code, these functions continue
   4037 ** to be supported.  However, new applications should avoid
   4038 ** the use of these functions.  To help encourage people to avoid
   4039 ** using these functions, we are not going to tell you what they do.
   4040 */
   4041 #ifndef SQLITE_OMIT_DEPRECATED
   4042 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
   4043 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
   4044 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
   4045 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
   4046 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
   4047 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
   4048 #endif
   4049 
   4050 /*
   4051 ** CAPI3REF: Obtaining SQL Function Parameter Values
   4052 **
   4053 ** The C-language implementation of SQL functions and aggregates uses
   4054 ** this set of interface routines to access the parameter values on
   4055 ** the function or aggregate.
   4056 **
   4057 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
   4058 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
   4059 ** define callbacks that implement the SQL functions and aggregates.
   4060 ** The 4th parameter to these callbacks is an array of pointers to
   4061 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
   4062 ** each parameter to the SQL function.  These routines are used to
   4063 ** extract values from the [sqlite3_value] objects.
   4064 **
   4065 ** These routines work only with [protected sqlite3_value] objects.
   4066 ** Any attempt to use these routines on an [unprotected sqlite3_value]
   4067 ** object results in undefined behavior.
   4068 **
   4069 ** ^These routines work just like the corresponding [column access functions]
   4070 ** except that  these routines take a single [protected sqlite3_value] object
   4071 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
   4072 **
   4073 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
   4074 ** in the native byte-order of the host machine.  ^The
   4075 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
   4076 ** extract UTF-16 strings as big-endian and little-endian respectively.
   4077 **
   4078 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
   4079 ** numeric affinity to the value.  This means that an attempt is
   4080 ** made to convert the value to an integer or floating point.  If
   4081 ** such a conversion is possible without loss of information (in other
   4082 ** words, if the value is a string that looks like a number)
   4083 ** then the conversion is performed.  Otherwise no conversion occurs.
   4084 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
   4085 **
   4086 ** Please pay particular attention to the fact that the pointer returned
   4087 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
   4088 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
   4089 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
   4090 ** or [sqlite3_value_text16()].
   4091 **
   4092 ** These routines must be called from the same thread as
   4093 ** the SQL function that supplied the [sqlite3_value*] parameters.
   4094 */
   4095 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
   4096 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
   4097 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
   4098 SQLITE_API double sqlite3_value_double(sqlite3_value*);
   4099 SQLITE_API int sqlite3_value_int(sqlite3_value*);
   4100 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
   4101 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
   4102 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
   4103 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
   4104 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
   4105 SQLITE_API int sqlite3_value_type(sqlite3_value*);
   4106 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
   4107 
   4108 /*
   4109 ** CAPI3REF: Obtain Aggregate Function Context
   4110 **
   4111 ** Implementations of aggregate SQL functions use this
   4112 ** routine to allocate memory for storing their state.
   4113 **
   4114 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
   4115 ** for a particular aggregate function, SQLite
   4116 ** allocates N of memory, zeroes out that memory, and returns a pointer
   4117 ** to the new memory. ^On second and subsequent calls to
   4118 ** sqlite3_aggregate_context() for the same aggregate function instance,
   4119 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
   4120 ** called once for each invocation of the xStep callback and then one
   4121 ** last time when the xFinal callback is invoked.  ^(When no rows match
   4122 ** an aggregate query, the xStep() callback of the aggregate function
   4123 ** implementation is never called and xFinal() is called exactly once.
   4124 ** In those cases, sqlite3_aggregate_context() might be called for the
   4125 ** first time from within xFinal().)^
   4126 **
   4127 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
   4128 ** less than or equal to zero or if a memory allocate error occurs.
   4129 **
   4130 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
   4131 ** determined by the N parameter on first successful call.  Changing the
   4132 ** value of N in subsequent call to sqlite3_aggregate_context() within
   4133 ** the same aggregate function instance will not resize the memory
   4134 ** allocation.)^
   4135 **
   4136 ** ^SQLite automatically frees the memory allocated by
   4137 ** sqlite3_aggregate_context() when the aggregate query concludes.
   4138 **
   4139 ** The first parameter must be a copy of the
   4140 ** [sqlite3_context | SQL function context] that is the first parameter
   4141 ** to the xStep or xFinal callback routine that implements the aggregate
   4142 ** function.
   4143 **
   4144 ** This routine must be called from the same thread in which
   4145 ** the aggregate SQL function is running.
   4146 */
   4147 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
   4148 
   4149 /*
   4150 ** CAPI3REF: User Data For Functions
   4151 **
   4152 ** ^The sqlite3_user_data() interface returns a copy of
   4153 ** the pointer that was the pUserData parameter (the 5th parameter)
   4154 ** of the [sqlite3_create_function()]
   4155 ** and [sqlite3_create_function16()] routines that originally
   4156 ** registered the application defined function.
   4157 **
   4158 ** This routine must be called from the same thread in which
   4159 ** the application-defined function is running.
   4160 */
   4161 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
   4162 
   4163 /*
   4164 ** CAPI3REF: Database Connection For Functions
   4165 **
   4166 ** ^The sqlite3_context_db_handle() interface returns a copy of
   4167 ** the pointer to the [database connection] (the 1st parameter)
   4168 ** of the [sqlite3_create_function()]
   4169 ** and [sqlite3_create_function16()] routines that originally
   4170 ** registered the application defined function.
   4171 */
   4172 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
   4173 
   4174 /*
   4175 ** CAPI3REF: Function Auxiliary Data
   4176 **
   4177 ** The following two functions may be used by scalar SQL functions to
   4178 ** associate metadata with argument values. If the same value is passed to
   4179 ** multiple invocations of the same SQL function during query execution, under
   4180 ** some circumstances the associated metadata may be preserved. This may
   4181 ** be used, for example, to add a regular-expression matching scalar
   4182 ** function. The compiled version of the regular expression is stored as
   4183 ** metadata associated with the SQL value passed as the regular expression
   4184 ** pattern.  The compiled regular expression can be reused on multiple
   4185 ** invocations of the same function so that the original pattern string
   4186 ** does not need to be recompiled on each invocation.
   4187 **
   4188 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
   4189 ** associated by the sqlite3_set_auxdata() function with the Nth argument
   4190 ** value to the application-defined function. ^If no metadata has been ever
   4191 ** been set for the Nth argument of the function, or if the corresponding
   4192 ** function parameter has changed since the meta-data was set,
   4193 ** then sqlite3_get_auxdata() returns a NULL pointer.
   4194 **
   4195 ** ^The sqlite3_set_auxdata() interface saves the metadata
   4196 ** pointed to by its 3rd parameter as the metadata for the N-th
   4197 ** argument of the application-defined function.  Subsequent
   4198 ** calls to sqlite3_get_auxdata() might return this data, if it has
   4199 ** not been destroyed.
   4200 ** ^If it is not NULL, SQLite will invoke the destructor
   4201 ** function given by the 4th parameter to sqlite3_set_auxdata() on
   4202 ** the metadata when the corresponding function parameter changes
   4203 ** or when the SQL statement completes, whichever comes first.
   4204 **
   4205 ** SQLite is free to call the destructor and drop metadata on any
   4206 ** parameter of any function at any time.  ^The only guarantee is that
   4207 ** the destructor will be called before the metadata is dropped.
   4208 **
   4209 ** ^(In practice, metadata is preserved between function calls for
   4210 ** expressions that are constant at compile time. This includes literal
   4211 ** values and [parameters].)^
   4212 **
   4213 ** These routines must be called from the same thread in which
   4214 ** the SQL function is running.
   4215 */
   4216 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
   4217 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
   4218 
   4219 
   4220 /*
   4221 ** CAPI3REF: Constants Defining Special Destructor Behavior
   4222 **
   4223 ** These are special values for the destructor that is passed in as the
   4224 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
   4225 ** argument is SQLITE_STATIC, it means that the content pointer is constant
   4226 ** and will never change.  It does not need to be destroyed.  ^The
   4227 ** SQLITE_TRANSIENT value means that the content will likely change in
   4228 ** the near future and that SQLite should make its own private copy of
   4229 ** the content before returning.
   4230 **
   4231 ** The typedef is necessary to work around problems in certain
   4232 ** C++ compilers.  See ticket #2191.
   4233 */
   4234 typedef void (*sqlite3_destructor_type)(void*);
   4235 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
   4236 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
   4237 
   4238 /*
   4239 ** CAPI3REF: Setting The Result Of An SQL Function
   4240 **
   4241 ** These routines are used by the xFunc or xFinal callbacks that
   4242 ** implement SQL functions and aggregates.  See
   4243 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
   4244 ** for additional information.
   4245 **
   4246 ** These functions work very much like the [parameter binding] family of
   4247 ** functions used to bind values to host parameters in prepared statements.
   4248 ** Refer to the [SQL parameter] documentation for additional information.
   4249 **
   4250 ** ^The sqlite3_result_blob() interface sets the result from
   4251 ** an application-defined function to be the BLOB whose content is pointed
   4252 ** to by the second parameter and which is N bytes long where N is the
   4253 ** third parameter.
   4254 **
   4255 ** ^The sqlite3_result_zeroblob() interfaces set the result of
   4256 ** the application-defined function to be a BLOB containing all zero
   4257 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
   4258 **
   4259 ** ^The sqlite3_result_double() interface sets the result from
   4260 ** an application-defined function to be a floating point value specified
   4261 ** by its 2nd argument.
   4262 **
   4263 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
   4264 ** cause the implemented SQL function to throw an exception.
   4265 ** ^SQLite uses the string pointed to by the
   4266 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
   4267 ** as the text of an error message.  ^SQLite interprets the error
   4268 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
   4269 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
   4270 ** byte order.  ^If the third parameter to sqlite3_result_error()
   4271 ** or sqlite3_result_error16() is negative then SQLite takes as the error
   4272 ** message all text up through the first zero character.
   4273 ** ^If the third parameter to sqlite3_result_error() or
   4274 ** sqlite3_result_error16() is non-negative then SQLite takes that many
   4275 ** bytes (not characters) from the 2nd parameter as the error message.
   4276 ** ^The sqlite3_result_error() and sqlite3_result_error16()
   4277 ** routines make a private copy of the error message text before
   4278 ** they return.  Hence, the calling function can deallocate or
   4279 ** modify the text after they return without harm.
   4280 ** ^The sqlite3_result_error_code() function changes the error code
   4281 ** returned by SQLite as a result of an error in a function.  ^By default,
   4282 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
   4283 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
   4284 **
   4285 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
   4286 ** indicating that a string or BLOB is too long to represent.
   4287 **
   4288 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
   4289 ** indicating that a memory allocation failed.
   4290 **
   4291 ** ^The sqlite3_result_int() interface sets the return value
   4292 ** of the application-defined function to be the 32-bit signed integer
   4293 ** value given in the 2nd argument.
   4294 ** ^The sqlite3_result_int64() interface sets the return value
   4295 ** of the application-defined function to be the 64-bit signed integer
   4296 ** value given in the 2nd argument.
   4297 **
   4298 ** ^The sqlite3_result_null() interface sets the return value
   4299 ** of the application-defined function to be NULL.
   4300 **
   4301 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
   4302 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
   4303 ** set the return value of the application-defined function to be
   4304 ** a text string which is represented as UTF-8, UTF-16 native byte order,
   4305 ** UTF-16 little endian, or UTF-16 big endian, respectively.
   4306 ** ^SQLite takes the text result from the application from
   4307 ** the 2nd parameter of the sqlite3_result_text* interfaces.
   4308 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4309 ** is negative, then SQLite takes result text from the 2nd parameter
   4310 ** through the first zero character.
   4311 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
   4312 ** is non-negative, then as many bytes (not characters) of the text
   4313 ** pointed to by the 2nd parameter are taken as the application-defined
   4314 ** function result.
   4315 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4316 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
   4317 ** function as the destructor on the text or BLOB result when it has
   4318 ** finished using that result.
   4319 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
   4320 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
   4321 ** assumes that the text or BLOB result is in constant space and does not
   4322 ** copy the content of the parameter nor call a destructor on the content
   4323 ** when it has finished using that result.
   4324 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
   4325 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
   4326 ** then SQLite makes a copy of the result into space obtained from
   4327 ** from [sqlite3_malloc()] before it returns.
   4328 **
   4329 ** ^The sqlite3_result_value() interface sets the result of
   4330 ** the application-defined function to be a copy the
   4331 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
   4332 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
   4333 ** so that the [sqlite3_value] specified in the parameter may change or
   4334 ** be deallocated after sqlite3_result_value() returns without harm.
   4335 ** ^A [protected sqlite3_value] object may always be used where an
   4336 ** [unprotected sqlite3_value] object is required, so either
   4337 ** kind of [sqlite3_value] object can be used with this interface.
   4338 **
   4339 ** If these routines are called from within the different thread
   4340 ** than the one containing the application-defined function that received
   4341 ** the [sqlite3_context] pointer, the results are undefined.
   4342 */
   4343 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
   4344 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
   4345 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
   4346 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
   4347 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
   4348 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
   4349 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
   4350 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
   4351 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
   4352 SQLITE_API void sqlite3_result_null(sqlite3_context*);
   4353 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
   4354 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
   4355 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
   4356 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
   4357 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
   4358 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
   4359 
   4360 /*
   4361 ** CAPI3REF: Define New Collating Sequences
   4362 **
   4363 ** ^These functions add, remove, or modify a [collation] associated
   4364 ** with the [database connection] specified as the first argument.
   4365 **
   4366 ** ^The name of the collation is a UTF-8 string
   4367 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
   4368 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
   4369 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
   4370 ** considered to be the same name.
   4371 **
   4372 ** ^(The third argument (eTextRep) must be one of the constants:
   4373 ** <ul>
   4374 ** <li> [SQLITE_UTF8],
   4375 ** <li> [SQLITE_UTF16LE],
   4376 ** <li> [SQLITE_UTF16BE],
   4377 ** <li> [SQLITE_UTF16], or
   4378 ** <li> [SQLITE_UTF16_ALIGNED].
   4379 ** </ul>)^
   4380 ** ^The eTextRep argument determines the encoding of strings passed
   4381 ** to the collating function callback, xCallback.
   4382 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
   4383 ** force strings to be UTF16 with native byte order.
   4384 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
   4385 ** on an even byte address.
   4386 **
   4387 ** ^The fourth argument, pArg, is a application data pointer that is passed
   4388 ** through as the first argument to the collating function callback.
   4389 **
   4390 ** ^The fifth argument, xCallback, is a pointer to the collating function.
   4391 ** ^Multiple collating functions can be registered using the same name but
   4392 ** with different eTextRep parameters and SQLite will use whichever
   4393 ** function requires the least amount of data transformation.
   4394 ** ^If the xCallback argument is NULL then the collating function is
   4395 ** deleted.  ^When all collating functions having the same name are deleted,
   4396 ** that collation is no longer usable.
   4397 **
   4398 ** ^The collating function callback is invoked with a copy of the pArg
   4399 ** application data pointer and with two strings in the encoding specified
   4400 ** by the eTextRep argument.  The collating function must return an
   4401 ** integer that is negative, zero, or positive
   4402 ** if the first string is less than, equal to, or greater than the second,
   4403 ** respectively.  A collating function must alway return the same answer
   4404 ** given the same inputs.  If two or more collating functions are registered
   4405 ** to the same collation name (using different eTextRep values) then all
   4406 ** must give an equivalent answer when invoked with equivalent strings.
   4407 ** The collating function must obey the following properties for all
   4408 ** strings A, B, and C:
   4409 **
   4410 ** <ol>
   4411 ** <li> If A==B then B==A.
   4412 ** <li> If A==B and B==C then A==C.
   4413 ** <li> If A&lt;B THEN B&gt;A.
   4414 ** <li> If A&lt;B and B&lt;C then A&lt;C.
   4415 ** </ol>
   4416 **
   4417 ** If a collating function fails any of the above constraints and that
   4418 ** collating function is  registered and used, then the behavior of SQLite
   4419 ** is undefined.
   4420 **
   4421 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
   4422 ** with the addition that the xDestroy callback is invoked on pArg when
   4423 ** the collating function is deleted.
   4424 ** ^Collating functions are deleted when they are overridden by later
   4425 ** calls to the collation creation functions or when the
   4426 ** [database connection] is closed using [sqlite3_close()].
   4427 **
   4428 ** ^The xDestroy callback is <u>not</u> called if the
   4429 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
   4430 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
   4431 ** check the return code and dispose of the application data pointer
   4432 ** themselves rather than expecting SQLite to deal with it for them.
   4433 ** This is different from every other SQLite interface.  The inconsistency
   4434 ** is unfortunate but cannot be changed without breaking backwards
   4435 ** compatibility.
   4436 **
   4437 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
   4438 */
   4439 SQLITE_API int sqlite3_create_collation(
   4440   sqlite3*,
   4441   const char *zName,
   4442   int eTextRep,
   4443   void *pArg,
   4444   int(*xCompare)(void*,int,const void*,int,const void*)
   4445 );
   4446 SQLITE_API int sqlite3_create_collation_v2(
   4447   sqlite3*,
   4448   const char *zName,
   4449   int eTextRep,
   4450   void *pArg,
   4451   int(*xCompare)(void*,int,const void*,int,const void*),
   4452   void(*xDestroy)(void*)
   4453 );
   4454 SQLITE_API int sqlite3_create_collation16(
   4455   sqlite3*,
   4456   const void *zName,
   4457   int eTextRep,
   4458   void *pArg,
   4459   int(*xCompare)(void*,int,const void*,int,const void*)
   4460 );
   4461 
   4462 /*
   4463 ** CAPI3REF: Collation Needed Callbacks
   4464 **
   4465 ** ^To avoid having to register all collation sequences before a database
   4466 ** can be used, a single callback function may be registered with the
   4467 ** [database connection] to be invoked whenever an undefined collation
   4468 ** sequence is required.
   4469 **
   4470 ** ^If the function is registered using the sqlite3_collation_needed() API,
   4471 ** then it is passed the names of undefined collation sequences as strings
   4472 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
   4473 ** the names are passed as UTF-16 in machine native byte order.
   4474 ** ^A call to either function replaces the existing collation-needed callback.
   4475 **
   4476 ** ^(When the callback is invoked, the first argument passed is a copy
   4477 ** of the second argument to sqlite3_collation_needed() or
   4478 ** sqlite3_collation_needed16().  The second argument is the database
   4479 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
   4480 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
   4481 ** sequence function required.  The fourth parameter is the name of the
   4482 ** required collation sequence.)^
   4483 **
   4484 ** The callback function should register the desired collation using
   4485 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
   4486 ** [sqlite3_create_collation_v2()].
   4487 */
   4488 SQLITE_API int sqlite3_collation_needed(
   4489   sqlite3*,
   4490   void*,
   4491   void(*)(void*,sqlite3*,int eTextRep,const char*)
   4492 );
   4493 SQLITE_API int sqlite3_collation_needed16(
   4494   sqlite3*,
   4495   void*,
   4496   void(*)(void*,sqlite3*,int eTextRep,const void*)
   4497 );
   4498 
   4499 #ifdef SQLITE_HAS_CODEC
   4500 /*
   4501 ** Specify the key for an encrypted database.  This routine should be
   4502 ** called right after sqlite3_open().
   4503 **
   4504 ** The code to implement this API is not available in the public release
   4505 ** of SQLite.
   4506 */
   4507 SQLITE_API int sqlite3_key(
   4508   sqlite3 *db,                   /* Database to be rekeyed */
   4509   const void *pKey, int nKey     /* The key */
   4510 );
   4511 
   4512 /*
   4513 ** Change the key on an open database.  If the current database is not
   4514 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
   4515 ** database is decrypted.
   4516 **
   4517 ** The code to implement this API is not available in the public release
   4518 ** of SQLite.
   4519 */
   4520 SQLITE_API int sqlite3_rekey(
   4521   sqlite3 *db,                   /* Database to be rekeyed */
   4522   const void *pKey, int nKey     /* The new key */
   4523 );
   4524 
   4525 /*
   4526 ** Specify the activation key for a SEE database.  Unless
   4527 ** activated, none of the SEE routines will work.
   4528 */
   4529 SQLITE_API void sqlite3_activate_see(
   4530   const char *zPassPhrase        /* Activation phrase */
   4531 );
   4532 #endif
   4533 
   4534 #ifdef SQLITE_ENABLE_CEROD
   4535 /*
   4536 ** Specify the activation key for a CEROD database.  Unless
   4537 ** activated, none of the CEROD routines will work.
   4538 */
   4539 SQLITE_API void sqlite3_activate_cerod(
   4540   const char *zPassPhrase        /* Activation phrase */
   4541 );
   4542 #endif
   4543 
   4544 /*
   4545 ** CAPI3REF: Suspend Execution For A Short Time
   4546 **
   4547 ** The sqlite3_sleep() function causes the current thread to suspend execution
   4548 ** for at least a number of milliseconds specified in its parameter.
   4549 **
   4550 ** If the operating system does not support sleep requests with
   4551 ** millisecond time resolution, then the time will be rounded up to
   4552 ** the nearest second. The number of milliseconds of sleep actually
   4553 ** requested from the operating system is returned.
   4554 **
   4555 ** ^SQLite implements this interface by calling the xSleep()
   4556 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
   4557 ** of the default VFS is not implemented correctly, or not implemented at
   4558 ** all, then the behavior of sqlite3_sleep() may deviate from the description
   4559 ** in the previous paragraphs.
   4560 */
   4561 SQLITE_API int sqlite3_sleep(int);
   4562 
   4563 /*
   4564 ** CAPI3REF: Name Of The Folder Holding Temporary Files
   4565 **
   4566 ** ^(If this global variable is made to point to a string which is
   4567 ** the name of a folder (a.k.a. directory), then all temporary files
   4568 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
   4569 ** will be placed in that directory.)^  ^If this variable
   4570 ** is a NULL pointer, then SQLite performs a search for an appropriate
   4571 ** temporary file directory.
   4572 **
   4573 ** It is not safe to read or modify this variable in more than one
   4574 ** thread at a time.  It is not safe to read or modify this variable
   4575 ** if a [database connection] is being used at the same time in a separate
   4576 ** thread.
   4577 ** It is intended that this variable be set once
   4578 ** as part of process initialization and before any SQLite interface
   4579 ** routines have been called and that this variable remain unchanged
   4580 ** thereafter.
   4581 **
   4582 ** ^The [temp_store_directory pragma] may modify this variable and cause
   4583 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
   4584 ** the [temp_store_directory pragma] always assumes that any string
   4585 ** that this variable points to is held in memory obtained from
   4586 ** [sqlite3_malloc] and the pragma may attempt to free that memory
   4587 ** using [sqlite3_free].
   4588 ** Hence, if this variable is modified directly, either it should be
   4589 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
   4590 ** or else the use of the [temp_store_directory pragma] should be avoided.
   4591 */
   4592 SQLITE_API char *sqlite3_temp_directory;
   4593 
   4594 /*
   4595 ** CAPI3REF: Test For Auto-Commit Mode
   4596 ** KEYWORDS: {autocommit mode}
   4597 **
   4598 ** ^The sqlite3_get_autocommit() interface returns non-zero or
   4599 ** zero if the given database connection is or is not in autocommit mode,
   4600 ** respectively.  ^Autocommit mode is on by default.
   4601 ** ^Autocommit mode is disabled by a [BEGIN] statement.
   4602 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
   4603 **
   4604 ** If certain kinds of errors occur on a statement within a multi-statement
   4605 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
   4606 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
   4607 ** transaction might be rolled back automatically.  The only way to
   4608 ** find out whether SQLite automatically rolled back the transaction after
   4609 ** an error is to use this function.
   4610 **
   4611 ** If another thread changes the autocommit status of the database
   4612 ** connection while this routine is running, then the return value
   4613 ** is undefined.
   4614 */
   4615 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
   4616 
   4617 /*
   4618 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
   4619 **
   4620 ** ^The sqlite3_db_handle interface returns the [database connection] handle
   4621 ** to which a [prepared statement] belongs.  ^The [database connection]
   4622 ** returned by sqlite3_db_handle is the same [database connection]
   4623 ** that was the first argument
   4624 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
   4625 ** create the statement in the first place.
   4626 */
   4627 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
   4628 
   4629 /*
   4630 ** CAPI3REF: Find the next prepared statement
   4631 **
   4632 ** ^This interface returns a pointer to the next [prepared statement] after
   4633 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
   4634 ** then this interface returns a pointer to the first prepared statement
   4635 ** associated with the database connection pDb.  ^If no prepared statement
   4636 ** satisfies the conditions of this routine, it returns NULL.
   4637 **
   4638 ** The [database connection] pointer D in a call to
   4639 ** [sqlite3_next_stmt(D,S)] must refer to an open database
   4640 ** connection and in particular must not be a NULL pointer.
   4641 */
   4642 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
   4643 
   4644 /*
   4645 ** CAPI3REF: Commit And Rollback Notification Callbacks
   4646 **
   4647 ** ^The sqlite3_commit_hook() interface registers a callback
   4648 ** function to be invoked whenever a transaction is [COMMIT | committed].
   4649 ** ^Any callback set by a previous call to sqlite3_commit_hook()
   4650 ** for the same database connection is overridden.
   4651 ** ^The sqlite3_rollback_hook() interface registers a callback
   4652 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
   4653 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
   4654 ** for the same database connection is overridden.
   4655 ** ^The pArg argument is passed through to the callback.
   4656 ** ^If the callback on a commit hook function returns non-zero,
   4657 ** then the commit is converted into a rollback.
   4658 **
   4659 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
   4660 ** return the P argument from the previous call of the same function
   4661 ** on the same [database connection] D, or NULL for
   4662 ** the first call for each function on D.
   4663 **
   4664 ** The callback implementation must not do anything that will modify
   4665 ** the database connection that invoked the callback.  Any actions
   4666 ** to modify the database connection must be deferred until after the
   4667 ** completion of the [sqlite3_step()] call that triggered the commit
   4668 ** or rollback hook in the first place.
   4669 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4670 ** database connections for the meaning of "modify" in this paragraph.
   4671 **
   4672 ** ^Registering a NULL function disables the callback.
   4673 **
   4674 ** ^When the commit hook callback routine returns zero, the [COMMIT]
   4675 ** operation is allowed to continue normally.  ^If the commit hook
   4676 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
   4677 ** ^The rollback hook is invoked on a rollback that results from a commit
   4678 ** hook returning non-zero, just as it would be with any other rollback.
   4679 **
   4680 ** ^For the purposes of this API, a transaction is said to have been
   4681 ** rolled back if an explicit "ROLLBACK" statement is executed, or
   4682 ** an error or constraint causes an implicit rollback to occur.
   4683 ** ^The rollback callback is not invoked if a transaction is
   4684 ** automatically rolled back because the database connection is closed.
   4685 **
   4686 ** See also the [sqlite3_update_hook()] interface.
   4687 */
   4688 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
   4689 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
   4690 
   4691 /*
   4692 ** CAPI3REF: Data Change Notification Callbacks
   4693 **
   4694 ** ^The sqlite3_update_hook() interface registers a callback function
   4695 ** with the [database connection] identified by the first argument
   4696 ** to be invoked whenever a row is updated, inserted or deleted.
   4697 ** ^Any callback set by a previous call to this function
   4698 ** for the same database connection is overridden.
   4699 **
   4700 ** ^The second argument is a pointer to the function to invoke when a
   4701 ** row is updated, inserted or deleted.
   4702 ** ^The first argument to the callback is a copy of the third argument
   4703 ** to sqlite3_update_hook().
   4704 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
   4705 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
   4706 ** to be invoked.
   4707 ** ^The third and fourth arguments to the callback contain pointers to the
   4708 ** database and table name containing the affected row.
   4709 ** ^The final callback parameter is the [rowid] of the row.
   4710 ** ^In the case of an update, this is the [rowid] after the update takes place.
   4711 **
   4712 ** ^(The update hook is not invoked when internal system tables are
   4713 ** modified (i.e. sqlite_master and sqlite_sequence).)^
   4714 **
   4715 ** ^In the current implementation, the update hook
   4716 ** is not invoked when duplication rows are deleted because of an
   4717 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
   4718 ** invoked when rows are deleted using the [truncate optimization].
   4719 ** The exceptions defined in this paragraph might change in a future
   4720 ** release of SQLite.
   4721 **
   4722 ** The update hook implementation must not do anything that will modify
   4723 ** the database connection that invoked the update hook.  Any actions
   4724 ** to modify the database connection must be deferred until after the
   4725 ** completion of the [sqlite3_step()] call that triggered the update hook.
   4726 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
   4727 ** database connections for the meaning of "modify" in this paragraph.
   4728 **
   4729 ** ^The sqlite3_update_hook(D,C,P) function
   4730 ** returns the P argument from the previous call
   4731 ** on the same [database connection] D, or NULL for
   4732 ** the first call on D.
   4733 **
   4734 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
   4735 ** interfaces.
   4736 */
   4737 SQLITE_API void *sqlite3_update_hook(
   4738   sqlite3*,
   4739   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   4740   void*
   4741 );
   4742 
   4743 /*
   4744 ** CAPI3REF: Enable Or Disable Shared Pager Cache
   4745 ** KEYWORDS: {shared cache}
   4746 **
   4747 ** ^(This routine enables or disables the sharing of the database cache
   4748 ** and schema data structures between [database connection | connections]
   4749 ** to the same database. Sharing is enabled if the argument is true
   4750 ** and disabled if the argument is false.)^
   4751 **
   4752 ** ^Cache sharing is enabled and disabled for an entire process.
   4753 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
   4754 ** sharing was enabled or disabled for each thread separately.
   4755 **
   4756 ** ^(The cache sharing mode set by this interface effects all subsequent
   4757 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
   4758 ** Existing database connections continue use the sharing mode
   4759 ** that was in effect at the time they were opened.)^
   4760 **
   4761 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
   4762 ** successfully.  An [error code] is returned otherwise.)^
   4763 **
   4764 ** ^Shared cache is disabled by default. But this might change in
   4765 ** future releases of SQLite.  Applications that care about shared
   4766 ** cache setting should set it explicitly.
   4767 **
   4768 ** See Also:  [SQLite Shared-Cache Mode]
   4769 */
   4770 SQLITE_API int sqlite3_enable_shared_cache(int);
   4771 
   4772 /*
   4773 ** CAPI3REF: Attempt To Free Heap Memory
   4774 **
   4775 ** ^The sqlite3_release_memory() interface attempts to free N bytes
   4776 ** of heap memory by deallocating non-essential memory allocations
   4777 ** held by the database library.   Memory used to cache database
   4778 ** pages to improve performance is an example of non-essential memory.
   4779 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
   4780 ** which might be more or less than the amount requested.
   4781 ** ^The sqlite3_release_memory() routine is a no-op returning zero
   4782 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   4783 */
   4784 SQLITE_API int sqlite3_release_memory(int);
   4785 
   4786 /*
   4787 ** CAPI3REF: Impose A Limit On Heap Size
   4788 **
   4789 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
   4790 ** soft limit on the amount of heap memory that may be allocated by SQLite.
   4791 ** ^SQLite strives to keep heap memory utilization below the soft heap
   4792 ** limit by reducing the number of pages held in the page cache
   4793 ** as heap memory usages approaches the limit.
   4794 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
   4795 ** below the limit, it will exceed the limit rather than generate
   4796 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
   4797 ** is advisory only.
   4798 **
   4799 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
   4800 ** the soft heap limit prior to the call.  ^If the argument N is negative
   4801 ** then no change is made to the soft heap limit.  Hence, the current
   4802 ** size of the soft heap limit can be determined by invoking
   4803 ** sqlite3_soft_heap_limit64() with a negative argument.
   4804 **
   4805 ** ^If the argument N is zero then the soft heap limit is disabled.
   4806 **
   4807 ** ^(The soft heap limit is not enforced in the current implementation
   4808 ** if one or more of following conditions are true:
   4809 **
   4810 ** <ul>
   4811 ** <li> The soft heap limit is set to zero.
   4812 ** <li> Memory accounting is disabled using a combination of the
   4813 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
   4814 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
   4815 ** <li> An alternative page cache implementation is specifed using
   4816 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
   4817 ** <li> The page cache allocates from its own memory pool supplied
   4818 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
   4819 **      from the heap.
   4820 ** </ul>)^
   4821 **
   4822 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
   4823 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
   4824 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
   4825 ** the soft heap limit is enforced on every memory allocation.  Without
   4826 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
   4827 ** when memory is allocated by the page cache.  Testing suggests that because
   4828 ** the page cache is the predominate memory user in SQLite, most
   4829 ** applications will achieve adequate soft heap limit enforcement without
   4830 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
   4831 **
   4832 ** The circumstances under which SQLite will enforce the soft heap limit may
   4833 ** changes in future releases of SQLite.
   4834 */
   4835 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
   4836 
   4837 /*
   4838 ** CAPI3REF: Deprecated Soft Heap Limit Interface
   4839 ** DEPRECATED
   4840 **
   4841 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
   4842 ** interface.  This routine is provided for historical compatibility
   4843 ** only.  All new applications should use the
   4844 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
   4845 */
   4846 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
   4847 
   4848 
   4849 /*
   4850 ** CAPI3REF: Extract Metadata About A Column Of A Table
   4851 **
   4852 ** ^This routine returns metadata about a specific column of a specific
   4853 ** database table accessible using the [database connection] handle
   4854 ** passed as the first function argument.
   4855 **
   4856 ** ^The column is identified by the second, third and fourth parameters to
   4857 ** this function. ^The second parameter is either the name of the database
   4858 ** (i.e. "main", "temp", or an attached database) containing the specified
   4859 ** table or NULL. ^If it is NULL, then all attached databases are searched
   4860 ** for the table using the same algorithm used by the database engine to
   4861 ** resolve unqualified table references.
   4862 **
   4863 ** ^The third and fourth parameters to this function are the table and column
   4864 ** name of the desired column, respectively. Neither of these parameters
   4865 ** may be NULL.
   4866 **
   4867 ** ^Metadata is returned by writing to the memory locations passed as the 5th
   4868 ** and subsequent parameters to this function. ^Any of these arguments may be
   4869 ** NULL, in which case the corresponding element of metadata is omitted.
   4870 **
   4871 ** ^(<blockquote>
   4872 ** <table border="1">
   4873 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
   4874 **
   4875 ** <tr><td> 5th <td> const char* <td> Data type
   4876 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
   4877 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
   4878 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
   4879 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
   4880 ** </table>
   4881 ** </blockquote>)^
   4882 **
   4883 ** ^The memory pointed to by the character pointers returned for the
   4884 ** declaration type and collation sequence is valid only until the next
   4885 ** call to any SQLite API function.
   4886 **
   4887 ** ^If the specified table is actually a view, an [error code] is returned.
   4888 **
   4889 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
   4890 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
   4891 ** parameters are set for the explicitly declared column. ^(If there is no
   4892 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
   4893 ** parameters are set as follows:
   4894 **
   4895 ** <pre>
   4896 **     data type: "INTEGER"
   4897 **     collation sequence: "BINARY"
   4898 **     not null: 0
   4899 **     primary key: 1
   4900 **     auto increment: 0
   4901 ** </pre>)^
   4902 **
   4903 ** ^(This function may load one or more schemas from database files. If an
   4904 ** error occurs during this process, or if the requested table or column
   4905 ** cannot be found, an [error code] is returned and an error message left
   4906 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
   4907 **
   4908 ** ^This API is only available if the library was compiled with the
   4909 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
   4910 */
   4911 SQLITE_API int sqlite3_table_column_metadata(
   4912   sqlite3 *db,                /* Connection handle */
   4913   const char *zDbName,        /* Database name or NULL */
   4914   const char *zTableName,     /* Table name */
   4915   const char *zColumnName,    /* Column name */
   4916   char const **pzDataType,    /* OUTPUT: Declared data type */
   4917   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   4918   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   4919   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   4920   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   4921 );
   4922 
   4923 /*
   4924 ** CAPI3REF: Load An Extension
   4925 **
   4926 ** ^This interface loads an SQLite extension library from the named file.
   4927 **
   4928 ** ^The sqlite3_load_extension() interface attempts to load an
   4929 ** SQLite extension library contained in the file zFile.
   4930 **
   4931 ** ^The entry point is zProc.
   4932 ** ^zProc may be 0, in which case the name of the entry point
   4933 ** defaults to "sqlite3_extension_init".
   4934 ** ^The sqlite3_load_extension() interface returns
   4935 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
   4936 ** ^If an error occurs and pzErrMsg is not 0, then the
   4937 ** [sqlite3_load_extension()] interface shall attempt to
   4938 ** fill *pzErrMsg with error message text stored in memory
   4939 ** obtained from [sqlite3_malloc()]. The calling function
   4940 ** should free this memory by calling [sqlite3_free()].
   4941 **
   4942 ** ^Extension loading must be enabled using
   4943 ** [sqlite3_enable_load_extension()] prior to calling this API,
   4944 ** otherwise an error will be returned.
   4945 **
   4946 ** See also the [load_extension() SQL function].
   4947 */
   4948 SQLITE_API int sqlite3_load_extension(
   4949   sqlite3 *db,          /* Load the extension into this database connection */
   4950   const char *zFile,    /* Name of the shared library containing extension */
   4951   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
   4952   char **pzErrMsg       /* Put error message here if not 0 */
   4953 );
   4954 
   4955 /*
   4956 ** CAPI3REF: Enable Or Disable Extension Loading
   4957 **
   4958 ** ^So as not to open security holes in older applications that are
   4959 ** unprepared to deal with extension loading, and as a means of disabling
   4960 ** extension loading while evaluating user-entered SQL, the following API
   4961 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
   4962 **
   4963 ** ^Extension loading is off by default. See ticket #1863.
   4964 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
   4965 ** to turn extension loading on and call it with onoff==0 to turn
   4966 ** it back off again.
   4967 */
   4968 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
   4969 
   4970 /*
   4971 ** CAPI3REF: Automatically Load Statically Linked Extensions
   4972 **
   4973 ** ^This interface causes the xEntryPoint() function to be invoked for
   4974 ** each new [database connection] that is created.  The idea here is that
   4975 ** xEntryPoint() is the entry point for a statically linked SQLite extension
   4976 ** that is to be automatically loaded into all new database connections.
   4977 **
   4978 ** ^(Even though the function prototype shows that xEntryPoint() takes
   4979 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
   4980 ** arguments and expects and integer result as if the signature of the
   4981 ** entry point where as follows:
   4982 **
   4983 ** <blockquote><pre>
   4984 ** &nbsp;  int xEntryPoint(
   4985 ** &nbsp;    sqlite3 *db,
   4986 ** &nbsp;    const char **pzErrMsg,
   4987 ** &nbsp;    const struct sqlite3_api_routines *pThunk
   4988 ** &nbsp;  );
   4989 ** </pre></blockquote>)^
   4990 **
   4991 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
   4992 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
   4993 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
   4994 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
   4995 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
   4996 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
   4997 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
   4998 **
   4999 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
   5000 ** on the list of automatic extensions is a harmless no-op. ^No entry point
   5001 ** will be called more than once for each database connection that is opened.
   5002 **
   5003 ** See also: [sqlite3_reset_auto_extension()].
   5004 */
   5005 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
   5006 
   5007 /*
   5008 ** CAPI3REF: Reset Automatic Extension Loading
   5009 **
   5010 ** ^This interface disables all automatic extensions previously
   5011 ** registered using [sqlite3_auto_extension()].
   5012 */
   5013 SQLITE_API void sqlite3_reset_auto_extension(void);
   5014 
   5015 /*
   5016 ** The interface to the virtual-table mechanism is currently considered
   5017 ** to be experimental.  The interface might change in incompatible ways.
   5018 ** If this is a problem for you, do not use the interface at this time.
   5019 **
   5020 ** When the virtual-table mechanism stabilizes, we will declare the
   5021 ** interface fixed, support it indefinitely, and remove this comment.
   5022 */
   5023 
   5024 /*
   5025 ** Structures used by the virtual table interface
   5026 */
   5027 typedef struct sqlite3_vtab sqlite3_vtab;
   5028 typedef struct sqlite3_index_info sqlite3_index_info;
   5029 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
   5030 typedef struct sqlite3_module sqlite3_module;
   5031 
   5032 /*
   5033 ** CAPI3REF: Virtual Table Object
   5034 ** KEYWORDS: sqlite3_module {virtual table module}
   5035 **
   5036 ** This structure, sometimes called a a "virtual table module",
   5037 ** defines the implementation of a [virtual tables].
   5038 ** This structure consists mostly of methods for the module.
   5039 **
   5040 ** ^A virtual table module is created by filling in a persistent
   5041 ** instance of this structure and passing a pointer to that instance
   5042 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
   5043 ** ^The registration remains valid until it is replaced by a different
   5044 ** module or until the [database connection] closes.  The content
   5045 ** of this structure must not change while it is registered with
   5046 ** any database connection.
   5047 */
   5048 struct sqlite3_module {
   5049   int iVersion;
   5050   int (*xCreate)(sqlite3*, void *pAux,
   5051                int argc, const char *const*argv,
   5052                sqlite3_vtab **ppVTab, char**);
   5053   int (*xConnect)(sqlite3*, void *pAux,
   5054                int argc, const char *const*argv,
   5055                sqlite3_vtab **ppVTab, char**);
   5056   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
   5057   int (*xDisconnect)(sqlite3_vtab *pVTab);
   5058   int (*xDestroy)(sqlite3_vtab *pVTab);
   5059   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
   5060   int (*xClose)(sqlite3_vtab_cursor*);
   5061   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
   5062                 int argc, sqlite3_value **argv);
   5063   int (*xNext)(sqlite3_vtab_cursor*);
   5064   int (*xEof)(sqlite3_vtab_cursor*);
   5065   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
   5066   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
   5067   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
   5068   int (*xBegin)(sqlite3_vtab *pVTab);
   5069   int (*xSync)(sqlite3_vtab *pVTab);
   5070   int (*xCommit)(sqlite3_vtab *pVTab);
   5071   int (*xRollback)(sqlite3_vtab *pVTab);
   5072   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
   5073                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
   5074                        void **ppArg);
   5075   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
   5076 };
   5077 
   5078 /*
   5079 ** CAPI3REF: Virtual Table Indexing Information
   5080 ** KEYWORDS: sqlite3_index_info
   5081 **
   5082 ** The sqlite3_index_info structure and its substructures is used as part
   5083 ** of the [virtual table] interface to
   5084 ** pass information into and receive the reply from the [xBestIndex]
   5085 ** method of a [virtual table module].  The fields under **Inputs** are the
   5086 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
   5087 ** results into the **Outputs** fields.
   5088 **
   5089 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
   5090 **
   5091 ** <blockquote>column OP expr</blockquote>
   5092 **
   5093 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
   5094 ** stored in aConstraint[].op using one of the
   5095 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
   5096 ** ^(The index of the column is stored in
   5097 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
   5098 ** expr on the right-hand side can be evaluated (and thus the constraint
   5099 ** is usable) and false if it cannot.)^
   5100 **
   5101 ** ^The optimizer automatically inverts terms of the form "expr OP column"
   5102 ** and makes other simplifications to the WHERE clause in an attempt to
   5103 ** get as many WHERE clause terms into the form shown above as possible.
   5104 ** ^The aConstraint[] array only reports WHERE clause terms that are
   5105 ** relevant to the particular virtual table being queried.
   5106 **
   5107 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
   5108 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
   5109 **
   5110 ** The [xBestIndex] method must fill aConstraintUsage[] with information
   5111 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
   5112 ** the right-hand side of the corresponding aConstraint[] is evaluated
   5113 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
   5114 ** is true, then the constraint is assumed to be fully handled by the
   5115 ** virtual table and is not checked again by SQLite.)^
   5116 **
   5117 ** ^The idxNum and idxPtr values are recorded and passed into the
   5118 ** [xFilter] method.
   5119 ** ^[sqlite3_free()] is used to free idxPtr if and only if
   5120 ** needToFreeIdxPtr is true.
   5121 **
   5122 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
   5123 ** the correct order to satisfy the ORDER BY clause so that no separate
   5124 ** sorting step is required.
   5125 **
   5126 ** ^The estimatedCost value is an estimate of the cost of doing the
   5127 ** particular lookup.  A full scan of a table with N entries should have
   5128 ** a cost of N.  A binary search of a table of N entries should have a
   5129 ** cost of approximately log(N).
   5130 */
   5131 struct sqlite3_index_info {
   5132   /* Inputs */
   5133   int nConstraint;           /* Number of entries in aConstraint */
   5134   struct sqlite3_index_constraint {
   5135      int iColumn;              /* Column on left-hand side of constraint */
   5136      unsigned char op;         /* Constraint operator */
   5137      unsigned char usable;     /* True if this constraint is usable */
   5138      int iTermOffset;          /* Used internally - xBestIndex should ignore */
   5139   } *aConstraint;            /* Table of WHERE clause constraints */
   5140   int nOrderBy;              /* Number of terms in the ORDER BY clause */
   5141   struct sqlite3_index_orderby {
   5142      int iColumn;              /* Column number */
   5143      unsigned char desc;       /* True for DESC.  False for ASC. */
   5144   } *aOrderBy;               /* The ORDER BY clause */
   5145   /* Outputs */
   5146   struct sqlite3_index_constraint_usage {
   5147     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
   5148     unsigned char omit;      /* Do not code a test for this constraint */
   5149   } *aConstraintUsage;
   5150   int idxNum;                /* Number used to identify the index */
   5151   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
   5152   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
   5153   int orderByConsumed;       /* True if output is already ordered */
   5154   double estimatedCost;      /* Estimated cost of using this index */
   5155 };
   5156 
   5157 /*
   5158 ** CAPI3REF: Virtual Table Constraint Operator Codes
   5159 **
   5160 ** These macros defined the allowed values for the
   5161 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
   5162 ** an operator that is part of a constraint term in the wHERE clause of
   5163 ** a query that uses a [virtual table].
   5164 */
   5165 #define SQLITE_INDEX_CONSTRAINT_EQ    2
   5166 #define SQLITE_INDEX_CONSTRAINT_GT    4
   5167 #define SQLITE_INDEX_CONSTRAINT_LE    8
   5168 #define SQLITE_INDEX_CONSTRAINT_LT    16
   5169 #define SQLITE_INDEX_CONSTRAINT_GE    32
   5170 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
   5171 
   5172 /*
   5173 ** CAPI3REF: Register A Virtual Table Implementation
   5174 **
   5175 ** ^These routines are used to register a new [virtual table module] name.
   5176 ** ^Module names must be registered before
   5177 ** creating a new [virtual table] using the module and before using a
   5178 ** preexisting [virtual table] for the module.
   5179 **
   5180 ** ^The module name is registered on the [database connection] specified
   5181 ** by the first parameter.  ^The name of the module is given by the
   5182 ** second parameter.  ^The third parameter is a pointer to
   5183 ** the implementation of the [virtual table module].   ^The fourth
   5184 ** parameter is an arbitrary client data pointer that is passed through
   5185 ** into the [xCreate] and [xConnect] methods of the virtual table module
   5186 ** when a new virtual table is be being created or reinitialized.
   5187 **
   5188 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
   5189 ** is a pointer to a destructor for the pClientData.  ^SQLite will
   5190 ** invoke the destructor function (if it is not NULL) when SQLite
   5191 ** no longer needs the pClientData pointer.  ^The destructor will also
   5192 ** be invoked if the call to sqlite3_create_module_v2() fails.
   5193 ** ^The sqlite3_create_module()
   5194 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
   5195 ** destructor.
   5196 */
   5197 SQLITE_API int sqlite3_create_module(
   5198   sqlite3 *db,               /* SQLite connection to register module with */
   5199   const char *zName,         /* Name of the module */
   5200   const sqlite3_module *p,   /* Methods for the module */
   5201   void *pClientData          /* Client data for xCreate/xConnect */
   5202 );
   5203 SQLITE_API int sqlite3_create_module_v2(
   5204   sqlite3 *db,               /* SQLite connection to register module with */
   5205   const char *zName,         /* Name of the module */
   5206   const sqlite3_module *p,   /* Methods for the module */
   5207   void *pClientData,         /* Client data for xCreate/xConnect */
   5208   void(*xDestroy)(void*)     /* Module destructor function */
   5209 );
   5210 
   5211 /*
   5212 ** CAPI3REF: Virtual Table Instance Object
   5213 ** KEYWORDS: sqlite3_vtab
   5214 **
   5215 ** Every [virtual table module] implementation uses a subclass
   5216 ** of this object to describe a particular instance
   5217 ** of the [virtual table].  Each subclass will
   5218 ** be tailored to the specific needs of the module implementation.
   5219 ** The purpose of this superclass is to define certain fields that are
   5220 ** common to all module implementations.
   5221 **
   5222 ** ^Virtual tables methods can set an error message by assigning a
   5223 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
   5224 ** take care that any prior string is freed by a call to [sqlite3_free()]
   5225 ** prior to assigning a new string to zErrMsg.  ^After the error message
   5226 ** is delivered up to the client application, the string will be automatically
   5227 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
   5228 */
   5229 struct sqlite3_vtab {
   5230   const sqlite3_module *pModule;  /* The module for this virtual table */
   5231   int nRef;                       /* NO LONGER USED */
   5232   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
   5233   /* Virtual table implementations will typically add additional fields */
   5234 };
   5235 
   5236 /*
   5237 ** CAPI3REF: Virtual Table Cursor Object
   5238 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
   5239 **
   5240 ** Every [virtual table module] implementation uses a subclass of the
   5241 ** following structure to describe cursors that point into the
   5242 ** [virtual table] and are used
   5243 ** to loop through the virtual table.  Cursors are created using the
   5244 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
   5245 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
   5246 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
   5247 ** of the module.  Each module implementation will define
   5248 ** the content of a cursor structure to suit its own needs.
   5249 **
   5250 ** This superclass exists in order to define fields of the cursor that
   5251 ** are common to all implementations.
   5252 */
   5253 struct sqlite3_vtab_cursor {
   5254   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
   5255   /* Virtual table implementations will typically add additional fields */
   5256 };
   5257 
   5258 /*
   5259 ** CAPI3REF: Declare The Schema Of A Virtual Table
   5260 **
   5261 ** ^The [xCreate] and [xConnect] methods of a
   5262 ** [virtual table module] call this interface
   5263 ** to declare the format (the names and datatypes of the columns) of
   5264 ** the virtual tables they implement.
   5265 */
   5266 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
   5267 
   5268 /*
   5269 ** CAPI3REF: Overload A Function For A Virtual Table
   5270 **
   5271 ** ^(Virtual tables can provide alternative implementations of functions
   5272 ** using the [xFindFunction] method of the [virtual table module].
   5273 ** But global versions of those functions
   5274 ** must exist in order to be overloaded.)^
   5275 **
   5276 ** ^(This API makes sure a global version of a function with a particular
   5277 ** name and number of parameters exists.  If no such function exists
   5278 ** before this API is called, a new function is created.)^  ^The implementation
   5279 ** of the new function always causes an exception to be thrown.  So
   5280 ** the new function is not good for anything by itself.  Its only
   5281 ** purpose is to be a placeholder function that can be overloaded
   5282 ** by a [virtual table].
   5283 */
   5284 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
   5285 
   5286 /*
   5287 ** The interface to the virtual-table mechanism defined above (back up
   5288 ** to a comment remarkably similar to this one) is currently considered
   5289 ** to be experimental.  The interface might change in incompatible ways.
   5290 ** If this is a problem for you, do not use the interface at this time.
   5291 **
   5292 ** When the virtual-table mechanism stabilizes, we will declare the
   5293 ** interface fixed, support it indefinitely, and remove this comment.
   5294 */
   5295 
   5296 /*
   5297 ** CAPI3REF: A Handle To An Open BLOB
   5298 ** KEYWORDS: {BLOB handle} {BLOB handles}
   5299 **
   5300 ** An instance of this object represents an open BLOB on which
   5301 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
   5302 ** ^Objects of this type are created by [sqlite3_blob_open()]
   5303 ** and destroyed by [sqlite3_blob_close()].
   5304 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
   5305 ** can be used to read or write small subsections of the BLOB.
   5306 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
   5307 */
   5308 typedef struct sqlite3_blob sqlite3_blob;
   5309 
   5310 /*
   5311 ** CAPI3REF: Open A BLOB For Incremental I/O
   5312 **
   5313 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
   5314 ** in row iRow, column zColumn, table zTable in database zDb;
   5315 ** in other words, the same BLOB that would be selected by:
   5316 **
   5317 ** <pre>
   5318 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
   5319 ** </pre>)^
   5320 **
   5321 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
   5322 ** and write access. ^If it is zero, the BLOB is opened for read access.
   5323 ** ^It is not possible to open a column that is part of an index or primary
   5324 ** key for writing. ^If [foreign key constraints] are enabled, it is
   5325 ** not possible to open a column that is part of a [child key] for writing.
   5326 **
   5327 ** ^Note that the database name is not the filename that contains
   5328 ** the database but rather the symbolic name of the database that
   5329 ** appears after the AS keyword when the database is connected using [ATTACH].
   5330 ** ^For the main database file, the database name is "main".
   5331 ** ^For TEMP tables, the database name is "temp".
   5332 **
   5333 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
   5334 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
   5335 ** to be a null pointer.)^
   5336 ** ^This function sets the [database connection] error code and message
   5337 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
   5338 ** functions. ^Note that the *ppBlob variable is always initialized in a
   5339 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
   5340 ** regardless of the success or failure of this routine.
   5341 **
   5342 ** ^(If the row that a BLOB handle points to is modified by an
   5343 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
   5344 ** then the BLOB handle is marked as "expired".
   5345 ** This is true if any column of the row is changed, even a column
   5346 ** other than the one the BLOB handle is open on.)^
   5347 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
   5348 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
   5349 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
   5350 ** rolled back by the expiration of the BLOB.  Such changes will eventually
   5351 ** commit if the transaction continues to completion.)^
   5352 **
   5353 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
   5354 ** the opened blob.  ^The size of a blob may not be changed by this
   5355 ** interface.  Use the [UPDATE] SQL command to change the size of a
   5356 ** blob.
   5357 **
   5358 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
   5359 ** and the built-in [zeroblob] SQL function can be used, if desired,
   5360 ** to create an empty, zero-filled blob in which to read or write using
   5361 ** this interface.
   5362 **
   5363 ** To avoid a resource leak, every open [BLOB handle] should eventually
   5364 ** be released by a call to [sqlite3_blob_close()].
   5365 */
   5366 SQLITE_API int sqlite3_blob_open(
   5367   sqlite3*,
   5368   const char *zDb,
   5369   const char *zTable,
   5370   const char *zColumn,
   5371   sqlite3_int64 iRow,
   5372   int flags,
   5373   sqlite3_blob **ppBlob
   5374 );
   5375 
   5376 /*
   5377 ** CAPI3REF: Move a BLOB Handle to a New Row
   5378 **
   5379 ** ^This function is used to move an existing blob handle so that it points
   5380 ** to a different row of the same database table. ^The new row is identified
   5381 ** by the rowid value passed as the second argument. Only the row can be
   5382 ** changed. ^The database, table and column on which the blob handle is open
   5383 ** remain the same. Moving an existing blob handle to a new row can be
   5384 ** faster than closing the existing handle and opening a new one.
   5385 **
   5386 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
   5387 ** it must exist and there must be either a blob or text value stored in
   5388 ** the nominated column.)^ ^If the new row is not present in the table, or if
   5389 ** it does not contain a blob or text value, or if another error occurs, an
   5390 ** SQLite error code is returned and the blob handle is considered aborted.
   5391 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
   5392 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
   5393 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
   5394 ** always returns zero.
   5395 **
   5396 ** ^This function sets the database handle error code and message.
   5397 */
   5398 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
   5399 
   5400 /*
   5401 ** CAPI3REF: Close A BLOB Handle
   5402 **
   5403 ** ^Closes an open [BLOB handle].
   5404 **
   5405 ** ^Closing a BLOB shall cause the current transaction to commit
   5406 ** if there are no other BLOBs, no pending prepared statements, and the
   5407 ** database connection is in [autocommit mode].
   5408 ** ^If any writes were made to the BLOB, they might be held in cache
   5409 ** until the close operation if they will fit.
   5410 **
   5411 ** ^(Closing the BLOB often forces the changes
   5412 ** out to disk and so if any I/O errors occur, they will likely occur
   5413 ** at the time when the BLOB is closed.  Any errors that occur during
   5414 ** closing are reported as a non-zero return value.)^
   5415 **
   5416 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
   5417 ** an error code, the BLOB is still closed.)^
   5418 **
   5419 ** ^Calling this routine with a null pointer (such as would be returned
   5420 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
   5421 */
   5422 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
   5423 
   5424 /*
   5425 ** CAPI3REF: Return The Size Of An Open BLOB
   5426 **
   5427 ** ^Returns the size in bytes of the BLOB accessible via the
   5428 ** successfully opened [BLOB handle] in its only argument.  ^The
   5429 ** incremental blob I/O routines can only read or overwriting existing
   5430 ** blob content; they cannot change the size of a blob.
   5431 **
   5432 ** This routine only works on a [BLOB handle] which has been created
   5433 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5434 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5435 ** to this routine results in undefined and probably undesirable behavior.
   5436 */
   5437 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
   5438 
   5439 /*
   5440 ** CAPI3REF: Read Data From A BLOB Incrementally
   5441 **
   5442 ** ^(This function is used to read data from an open [BLOB handle] into a
   5443 ** caller-supplied buffer. N bytes of data are copied into buffer Z
   5444 ** from the open BLOB, starting at offset iOffset.)^
   5445 **
   5446 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5447 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
   5448 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
   5449 ** ^The size of the blob (and hence the maximum value of N+iOffset)
   5450 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5451 **
   5452 ** ^An attempt to read from an expired [BLOB handle] fails with an
   5453 ** error code of [SQLITE_ABORT].
   5454 **
   5455 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
   5456 ** Otherwise, an [error code] or an [extended error code] is returned.)^
   5457 **
   5458 ** This routine only works on a [BLOB handle] which has been created
   5459 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5460 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5461 ** to this routine results in undefined and probably undesirable behavior.
   5462 **
   5463 ** See also: [sqlite3_blob_write()].
   5464 */
   5465 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
   5466 
   5467 /*
   5468 ** CAPI3REF: Write Data Into A BLOB Incrementally
   5469 **
   5470 ** ^This function is used to write data into an open [BLOB handle] from a
   5471 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
   5472 ** into the open BLOB, starting at offset iOffset.
   5473 **
   5474 ** ^If the [BLOB handle] passed as the first argument was not opened for
   5475 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
   5476 ** this function returns [SQLITE_READONLY].
   5477 **
   5478 ** ^This function may only modify the contents of the BLOB; it is
   5479 ** not possible to increase the size of a BLOB using this API.
   5480 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
   5481 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
   5482 ** less than zero [SQLITE_ERROR] is returned and no data is written.
   5483 ** The size of the BLOB (and hence the maximum value of N+iOffset)
   5484 ** can be determined using the [sqlite3_blob_bytes()] interface.
   5485 **
   5486 ** ^An attempt to write to an expired [BLOB handle] fails with an
   5487 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
   5488 ** before the [BLOB handle] expired are not rolled back by the
   5489 ** expiration of the handle, though of course those changes might
   5490 ** have been overwritten by the statement that expired the BLOB handle
   5491 ** or by other independent statements.
   5492 **
   5493 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
   5494 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
   5495 **
   5496 ** This routine only works on a [BLOB handle] which has been created
   5497 ** by a prior successful call to [sqlite3_blob_open()] and which has not
   5498 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
   5499 ** to this routine results in undefined and probably undesirable behavior.
   5500 **
   5501 ** See also: [sqlite3_blob_read()].
   5502 */
   5503 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
   5504 
   5505 /*
   5506 ** CAPI3REF: Virtual File System Objects
   5507 **
   5508 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
   5509 ** that SQLite uses to interact
   5510 ** with the underlying operating system.  Most SQLite builds come with a
   5511 ** single default VFS that is appropriate for the host computer.
   5512 ** New VFSes can be registered and existing VFSes can be unregistered.
   5513 ** The following interfaces are provided.
   5514 **
   5515 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
   5516 ** ^Names are case sensitive.
   5517 ** ^Names are zero-terminated UTF-8 strings.
   5518 ** ^If there is no match, a NULL pointer is returned.
   5519 ** ^If zVfsName is NULL then the default VFS is returned.
   5520 **
   5521 ** ^New VFSes are registered with sqlite3_vfs_register().
   5522 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
   5523 ** ^The same VFS can be registered multiple times without injury.
   5524 ** ^To make an existing VFS into the default VFS, register it again
   5525 ** with the makeDflt flag set.  If two different VFSes with the
   5526 ** same name are registered, the behavior is undefined.  If a
   5527 ** VFS is registered with a name that is NULL or an empty string,
   5528 ** then the behavior is undefined.
   5529 **
   5530 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
   5531 ** ^(If the default VFS is unregistered, another VFS is chosen as
   5532 ** the default.  The choice for the new VFS is arbitrary.)^
   5533 */
   5534 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
   5535 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
   5536 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
   5537 
   5538 /*
   5539 ** CAPI3REF: Mutexes
   5540 **
   5541 ** The SQLite core uses these routines for thread
   5542 ** synchronization. Though they are intended for internal
   5543 ** use by SQLite, code that links against SQLite is
   5544 ** permitted to use any of these routines.
   5545 **
   5546 ** The SQLite source code contains multiple implementations
   5547 ** of these mutex routines.  An appropriate implementation
   5548 ** is selected automatically at compile-time.  ^(The following
   5549 ** implementations are available in the SQLite core:
   5550 **
   5551 ** <ul>
   5552 ** <li>   SQLITE_MUTEX_OS2
   5553 ** <li>   SQLITE_MUTEX_PTHREAD
   5554 ** <li>   SQLITE_MUTEX_W32
   5555 ** <li>   SQLITE_MUTEX_NOOP
   5556 ** </ul>)^
   5557 **
   5558 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
   5559 ** that does no real locking and is appropriate for use in
   5560 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
   5561 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
   5562 ** are appropriate for use on OS/2, Unix, and Windows.
   5563 **
   5564 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
   5565 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
   5566 ** implementation is included with the library. In this case the
   5567 ** application must supply a custom mutex implementation using the
   5568 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
   5569 ** before calling sqlite3_initialize() or any other public sqlite3_
   5570 ** function that calls sqlite3_initialize().)^
   5571 **
   5572 ** ^The sqlite3_mutex_alloc() routine allocates a new
   5573 ** mutex and returns a pointer to it. ^If it returns NULL
   5574 ** that means that a mutex could not be allocated.  ^SQLite
   5575 ** will unwind its stack and return an error.  ^(The argument
   5576 ** to sqlite3_mutex_alloc() is one of these integer constants:
   5577 **
   5578 ** <ul>
   5579 ** <li>  SQLITE_MUTEX_FAST
   5580 ** <li>  SQLITE_MUTEX_RECURSIVE
   5581 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   5582 ** <li>  SQLITE_MUTEX_STATIC_MEM
   5583 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   5584 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   5585 ** <li>  SQLITE_MUTEX_STATIC_LRU
   5586 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   5587 ** </ul>)^
   5588 **
   5589 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
   5590 ** cause sqlite3_mutex_alloc() to create
   5591 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   5592 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   5593 ** The mutex implementation does not need to make a distinction
   5594 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   5595 ** not want to.  ^SQLite will only request a recursive mutex in
   5596 ** cases where it really needs one.  ^If a faster non-recursive mutex
   5597 ** implementation is available on the host platform, the mutex subsystem
   5598 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   5599 **
   5600 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
   5601 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
   5602 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
   5603 ** used by the current version of SQLite.  Future versions of SQLite
   5604 ** may add additional static mutexes.  Static mutexes are for internal
   5605 ** use by SQLite only.  Applications that use SQLite mutexes should
   5606 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   5607 ** SQLITE_MUTEX_RECURSIVE.
   5608 **
   5609 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   5610 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   5611 ** returns a different mutex on every call.  ^But for the static
   5612 ** mutex types, the same mutex is returned on every call that has
   5613 ** the same type number.
   5614 **
   5615 ** ^The sqlite3_mutex_free() routine deallocates a previously
   5616 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
   5617 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
   5618 ** use when they are deallocated.  Attempting to deallocate a static
   5619 ** mutex results in undefined behavior.  ^SQLite never deallocates
   5620 ** a static mutex.
   5621 **
   5622 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   5623 ** to enter a mutex.  ^If another thread is already within the mutex,
   5624 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   5625 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
   5626 ** upon successful entry.  ^(Mutexes created using
   5627 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
   5628 ** In such cases the,
   5629 ** mutex must be exited an equal number of times before another thread
   5630 ** can enter.)^  ^(If the same thread tries to enter any other
   5631 ** kind of mutex more than once, the behavior is undefined.
   5632 ** SQLite will never exhibit
   5633 ** such behavior in its own use of mutexes.)^
   5634 **
   5635 ** ^(Some systems (for example, Windows 95) do not support the operation
   5636 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
   5637 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
   5638 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
   5639 **
   5640 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
   5641 ** previously entered by the same thread.   ^(The behavior
   5642 ** is undefined if the mutex is not currently entered by the
   5643 ** calling thread or is not currently allocated.  SQLite will
   5644 ** never do either.)^
   5645 **
   5646 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
   5647 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
   5648 ** behave as no-ops.
   5649 **
   5650 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
   5651 */
   5652 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
   5653 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
   5654 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
   5655 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
   5656 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
   5657 
   5658 /*
   5659 ** CAPI3REF: Mutex Methods Object
   5660 **
   5661 ** An instance of this structure defines the low-level routines
   5662 ** used to allocate and use mutexes.
   5663 **
   5664 ** Usually, the default mutex implementations provided by SQLite are
   5665 ** sufficient, however the user has the option of substituting a custom
   5666 ** implementation for specialized deployments or systems for which SQLite
   5667 ** does not provide a suitable implementation. In this case, the user
   5668 ** creates and populates an instance of this structure to pass
   5669 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
   5670 ** Additionally, an instance of this structure can be used as an
   5671 ** output variable when querying the system for the current mutex
   5672 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
   5673 **
   5674 ** ^The xMutexInit method defined by this structure is invoked as
   5675 ** part of system initialization by the sqlite3_initialize() function.
   5676 ** ^The xMutexInit routine is called by SQLite exactly once for each
   5677 ** effective call to [sqlite3_initialize()].
   5678 **
   5679 ** ^The xMutexEnd method defined by this structure is invoked as
   5680 ** part of system shutdown by the sqlite3_shutdown() function. The
   5681 ** implementation of this method is expected to release all outstanding
   5682 ** resources obtained by the mutex methods implementation, especially
   5683 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
   5684 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
   5685 **
   5686 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
   5687 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
   5688 ** xMutexNotheld) implement the following interfaces (respectively):
   5689 **
   5690 ** <ul>
   5691 **   <li>  [sqlite3_mutex_alloc()] </li>
   5692 **   <li>  [sqlite3_mutex_free()] </li>
   5693 **   <li>  [sqlite3_mutex_enter()] </li>
   5694 **   <li>  [sqlite3_mutex_try()] </li>
   5695 **   <li>  [sqlite3_mutex_leave()] </li>
   5696 **   <li>  [sqlite3_mutex_held()] </li>
   5697 **   <li>  [sqlite3_mutex_notheld()] </li>
   5698 ** </ul>)^
   5699 **
   5700 ** The only difference is that the public sqlite3_XXX functions enumerated
   5701 ** above silently ignore any invocations that pass a NULL pointer instead
   5702 ** of a valid mutex handle. The implementations of the methods defined
   5703 ** by this structure are not required to handle this case, the results
   5704 ** of passing a NULL pointer instead of a valid mutex handle are undefined
   5705 ** (i.e. it is acceptable to provide an implementation that segfaults if
   5706 ** it is passed a NULL pointer).
   5707 **
   5708 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
   5709 ** invoke xMutexInit() multiple times within the same process and without
   5710 ** intervening calls to xMutexEnd().  Second and subsequent calls to
   5711 ** xMutexInit() must be no-ops.
   5712 **
   5713 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
   5714 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
   5715 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
   5716 ** memory allocation for a fast or recursive mutex.
   5717 **
   5718 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
   5719 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
   5720 ** If xMutexInit fails in any way, it is expected to clean up after itself
   5721 ** prior to returning.
   5722 */
   5723 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
   5724 struct sqlite3_mutex_methods {
   5725   int (*xMutexInit)(void);
   5726   int (*xMutexEnd)(void);
   5727   sqlite3_mutex *(*xMutexAlloc)(int);
   5728   void (*xMutexFree)(sqlite3_mutex *);
   5729   void (*xMutexEnter)(sqlite3_mutex *);
   5730   int (*xMutexTry)(sqlite3_mutex *);
   5731   void (*xMutexLeave)(sqlite3_mutex *);
   5732   int (*xMutexHeld)(sqlite3_mutex *);
   5733   int (*xMutexNotheld)(sqlite3_mutex *);
   5734 };
   5735 
   5736 /*
   5737 ** CAPI3REF: Mutex Verification Routines
   5738 **
   5739 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
   5740 ** are intended for use inside assert() statements.  ^The SQLite core
   5741 ** never uses these routines except inside an assert() and applications
   5742 ** are advised to follow the lead of the core.  ^The SQLite core only
   5743 ** provides implementations for these routines when it is compiled
   5744 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
   5745 ** are only required to provide these routines if SQLITE_DEBUG is
   5746 ** defined and if NDEBUG is not defined.
   5747 **
   5748 ** ^These routines should return true if the mutex in their argument
   5749 ** is held or not held, respectively, by the calling thread.
   5750 **
   5751 ** ^The implementation is not required to provided versions of these
   5752 ** routines that actually work. If the implementation does not provide working
   5753 ** versions of these routines, it should at least provide stubs that always
   5754 ** return true so that one does not get spurious assertion failures.
   5755 **
   5756 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
   5757 ** the routine should return 1.   This seems counter-intuitive since
   5758 ** clearly the mutex cannot be held if it does not exist.  But the
   5759 ** the reason the mutex does not exist is because the build is not
   5760 ** using mutexes.  And we do not want the assert() containing the
   5761 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
   5762 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
   5763 ** interface should also return 1 when given a NULL pointer.
   5764 */
   5765 #ifndef NDEBUG
   5766 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
   5767 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
   5768 #endif
   5769 
   5770 /*
   5771 ** CAPI3REF: Mutex Types
   5772 **
   5773 ** The [sqlite3_mutex_alloc()] interface takes a single argument
   5774 ** which is one of these integer constants.
   5775 **
   5776 ** The set of static mutexes may change from one SQLite release to the
   5777 ** next.  Applications that override the built-in mutex logic must be
   5778 ** prepared to accommodate additional static mutexes.
   5779 */
   5780 #define SQLITE_MUTEX_FAST             0
   5781 #define SQLITE_MUTEX_RECURSIVE        1
   5782 #define SQLITE_MUTEX_STATIC_MASTER    2
   5783 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
   5784 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
   5785 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
   5786 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
   5787 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
   5788 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
   5789 
   5790 /*
   5791 ** CAPI3REF: Retrieve the mutex for a database connection
   5792 **
   5793 ** ^This interface returns a pointer the [sqlite3_mutex] object that
   5794 ** serializes access to the [database connection] given in the argument
   5795 ** when the [threading mode] is Serialized.
   5796 ** ^If the [threading mode] is Single-thread or Multi-thread then this
   5797 ** routine returns a NULL pointer.
   5798 */
   5799 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
   5800 
   5801 /*
   5802 ** CAPI3REF: Low-Level Control Of Database Files
   5803 **
   5804 ** ^The [sqlite3_file_control()] interface makes a direct call to the
   5805 ** xFileControl method for the [sqlite3_io_methods] object associated
   5806 ** with a particular database identified by the second argument. ^The
   5807 ** name of the database is "main" for the main database or "temp" for the
   5808 ** TEMP database, or the name that appears after the AS keyword for
   5809 ** databases that are added using the [ATTACH] SQL command.
   5810 ** ^A NULL pointer can be used in place of "main" to refer to the
   5811 ** main database file.
   5812 ** ^The third and fourth parameters to this routine
   5813 ** are passed directly through to the second and third parameters of
   5814 ** the xFileControl method.  ^The return value of the xFileControl
   5815 ** method becomes the return value of this routine.
   5816 **
   5817 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
   5818 ** a pointer to the underlying [sqlite3_file] object to be written into
   5819 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
   5820 ** case is a short-circuit path which does not actually invoke the
   5821 ** underlying sqlite3_io_methods.xFileControl method.
   5822 **
   5823 ** ^If the second parameter (zDbName) does not match the name of any
   5824 ** open database file, then SQLITE_ERROR is returned.  ^This error
   5825 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
   5826 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
   5827 ** also return SQLITE_ERROR.  There is no way to distinguish between
   5828 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
   5829 ** xFileControl method.
   5830 **
   5831 ** See also: [SQLITE_FCNTL_LOCKSTATE]
   5832 */
   5833 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
   5834 
   5835 /*
   5836 ** CAPI3REF: Testing Interface
   5837 **
   5838 ** ^The sqlite3_test_control() interface is used to read out internal
   5839 ** state of SQLite and to inject faults into SQLite for testing
   5840 ** purposes.  ^The first parameter is an operation code that determines
   5841 ** the number, meaning, and operation of all subsequent parameters.
   5842 **
   5843 ** This interface is not for use by applications.  It exists solely
   5844 ** for verifying the correct operation of the SQLite library.  Depending
   5845 ** on how the SQLite library is compiled, this interface might not exist.
   5846 **
   5847 ** The details of the operation codes, their meanings, the parameters
   5848 ** they take, and what they do are all subject to change without notice.
   5849 ** Unlike most of the SQLite API, this function is not guaranteed to
   5850 ** operate consistently from one release to the next.
   5851 */
   5852 SQLITE_API int sqlite3_test_control(int op, ...);
   5853 
   5854 /*
   5855 ** CAPI3REF: Testing Interface Operation Codes
   5856 **
   5857 ** These constants are the valid operation code parameters used
   5858 ** as the first argument to [sqlite3_test_control()].
   5859 **
   5860 ** These parameters and their meanings are subject to change
   5861 ** without notice.  These values are for testing purposes only.
   5862 ** Applications should not use any of these parameters or the
   5863 ** [sqlite3_test_control()] interface.
   5864 */
   5865 #define SQLITE_TESTCTRL_FIRST                    5
   5866 #define SQLITE_TESTCTRL_PRNG_SAVE                5
   5867 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
   5868 #define SQLITE_TESTCTRL_PRNG_RESET               7
   5869 #define SQLITE_TESTCTRL_BITVEC_TEST              8
   5870 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
   5871 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
   5872 #define SQLITE_TESTCTRL_PENDING_BYTE            11
   5873 #define SQLITE_TESTCTRL_ASSERT                  12
   5874 #define SQLITE_TESTCTRL_ALWAYS                  13
   5875 #define SQLITE_TESTCTRL_RESERVE                 14
   5876 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
   5877 #define SQLITE_TESTCTRL_ISKEYWORD               16
   5878 #define SQLITE_TESTCTRL_PGHDRSZ                 17
   5879 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
   5880 #define SQLITE_TESTCTRL_LAST                    18
   5881 
   5882 /*
   5883 ** CAPI3REF: SQLite Runtime Status
   5884 **
   5885 ** ^This interface is used to retrieve runtime status information
   5886 ** about the performance of SQLite, and optionally to reset various
   5887 ** highwater marks.  ^The first argument is an integer code for
   5888 ** the specific parameter to measure.  ^(Recognized integer codes
   5889 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
   5890 ** ^The current value of the parameter is returned into *pCurrent.
   5891 ** ^The highest recorded value is returned in *pHighwater.  ^If the
   5892 ** resetFlag is true, then the highest record value is reset after
   5893 ** *pHighwater is written.  ^(Some parameters do not record the highest
   5894 ** value.  For those parameters
   5895 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
   5896 ** ^(Other parameters record only the highwater mark and not the current
   5897 ** value.  For these latter parameters nothing is written into *pCurrent.)^
   5898 **
   5899 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
   5900 ** non-zero [error code] on failure.
   5901 **
   5902 ** This routine is threadsafe but is not atomic.  This routine can be
   5903 ** called while other threads are running the same or different SQLite
   5904 ** interfaces.  However the values returned in *pCurrent and
   5905 ** *pHighwater reflect the status of SQLite at different points in time
   5906 ** and it is possible that another thread might change the parameter
   5907 ** in between the times when *pCurrent and *pHighwater are written.
   5908 **
   5909 ** See also: [sqlite3_db_status()]
   5910 */
   5911 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
   5912 
   5913 
   5914 /*
   5915 ** CAPI3REF: Status Parameters
   5916 **
   5917 ** These integer constants designate various run-time status parameters
   5918 ** that can be returned by [sqlite3_status()].
   5919 **
   5920 ** <dl>
   5921 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
   5922 ** <dd>This parameter is the current amount of memory checked out
   5923 ** using [sqlite3_malloc()], either directly or indirectly.  The
   5924 ** figure includes calls made to [sqlite3_malloc()] by the application
   5925 ** and internal memory usage by the SQLite library.  Scratch memory
   5926 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
   5927 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
   5928 ** this parameter.  The amount returned is the sum of the allocation
   5929 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
   5930 **
   5931 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
   5932 ** <dd>This parameter records the largest memory allocation request
   5933 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
   5934 ** internal equivalents).  Only the value returned in the
   5935 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5936 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5937 **
   5938 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
   5939 ** <dd>This parameter records the number of separate memory allocations.</dd>)^
   5940 **
   5941 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
   5942 ** <dd>This parameter returns the number of pages used out of the
   5943 ** [pagecache memory allocator] that was configured using
   5944 ** [SQLITE_CONFIG_PAGECACHE].  The
   5945 ** value returned is in pages, not in bytes.</dd>)^
   5946 **
   5947 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
   5948 ** <dd>This parameter returns the number of bytes of page cache
   5949 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
   5950 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
   5951 ** returned value includes allocations that overflowed because they
   5952 ** where too large (they were larger than the "sz" parameter to
   5953 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
   5954 ** no space was left in the page cache.</dd>)^
   5955 **
   5956 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
   5957 ** <dd>This parameter records the largest memory allocation request
   5958 ** handed to [pagecache memory allocator].  Only the value returned in the
   5959 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5960 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5961 **
   5962 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
   5963 ** <dd>This parameter returns the number of allocations used out of the
   5964 ** [scratch memory allocator] configured using
   5965 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
   5966 ** in bytes.  Since a single thread may only have one scratch allocation
   5967 ** outstanding at time, this parameter also reports the number of threads
   5968 ** using scratch memory at the same time.</dd>)^
   5969 **
   5970 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
   5971 ** <dd>This parameter returns the number of bytes of scratch memory
   5972 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
   5973 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
   5974 ** returned include overflows because the requested allocation was too
   5975 ** larger (that is, because the requested allocation was larger than the
   5976 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
   5977 ** slots were available.
   5978 ** </dd>)^
   5979 **
   5980 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
   5981 ** <dd>This parameter records the largest memory allocation request
   5982 ** handed to [scratch memory allocator].  Only the value returned in the
   5983 ** *pHighwater parameter to [sqlite3_status()] is of interest.
   5984 ** The value written into the *pCurrent parameter is undefined.</dd>)^
   5985 **
   5986 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
   5987 ** <dd>This parameter records the deepest parser stack.  It is only
   5988 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
   5989 ** </dl>
   5990 **
   5991 ** New status parameters may be added from time to time.
   5992 */
   5993 #define SQLITE_STATUS_MEMORY_USED          0
   5994 #define SQLITE_STATUS_PAGECACHE_USED       1
   5995 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
   5996 #define SQLITE_STATUS_SCRATCH_USED         3
   5997 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
   5998 #define SQLITE_STATUS_MALLOC_SIZE          5
   5999 #define SQLITE_STATUS_PARSER_STACK         6
   6000 #define SQLITE_STATUS_PAGECACHE_SIZE       7
   6001 #define SQLITE_STATUS_SCRATCH_SIZE         8
   6002 #define SQLITE_STATUS_MALLOC_COUNT         9
   6003 
   6004 /*
   6005 ** CAPI3REF: Database Connection Status
   6006 **
   6007 ** ^This interface is used to retrieve runtime status information
   6008 ** about a single [database connection].  ^The first argument is the
   6009 ** database connection object to be interrogated.  ^The second argument
   6010 ** is an integer constant, taken from the set of
   6011 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
   6012 ** determines the parameter to interrogate.  The set of
   6013 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
   6014 ** to grow in future releases of SQLite.
   6015 **
   6016 ** ^The current value of the requested parameter is written into *pCur
   6017 ** and the highest instantaneous value is written into *pHiwtr.  ^If
   6018 ** the resetFlg is true, then the highest instantaneous value is
   6019 ** reset back down to the current value.
   6020 **
   6021 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
   6022 ** non-zero [error code] on failure.
   6023 **
   6024 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
   6025 */
   6026 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
   6027 
   6028 /*
   6029 ** CAPI3REF: Status Parameters for database connections
   6030 **
   6031 ** These constants are the available integer "verbs" that can be passed as
   6032 ** the second argument to the [sqlite3_db_status()] interface.
   6033 **
   6034 ** New verbs may be added in future releases of SQLite. Existing verbs
   6035 ** might be discontinued. Applications should check the return code from
   6036 ** [sqlite3_db_status()] to make sure that the call worked.
   6037 ** The [sqlite3_db_status()] interface will return a non-zero error code
   6038 ** if a discontinued or unsupported verb is invoked.
   6039 **
   6040 ** <dl>
   6041 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
   6042 ** <dd>This parameter returns the number of lookaside memory slots currently
   6043 ** checked out.</dd>)^
   6044 **
   6045 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
   6046 ** <dd>This parameter returns the approximate number of of bytes of heap
   6047 ** memory used by all pager caches associated with the database connection.)^
   6048 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
   6049 **
   6050 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
   6051 ** <dd>This parameter returns the approximate number of of bytes of heap
   6052 ** memory used to store the schema for all databases associated
   6053 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
   6054 ** ^The full amount of memory used by the schemas is reported, even if the
   6055 ** schema memory is shared with other database connections due to
   6056 ** [shared cache mode] being enabled.
   6057 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
   6058 **
   6059 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
   6060 ** <dd>This parameter returns the approximate number of of bytes of heap
   6061 ** and lookaside memory used by all prepared statements associated with
   6062 ** the database connection.)^
   6063 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
   6064 ** </dd>
   6065 ** </dl>
   6066 */
   6067 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
   6068 #define SQLITE_DBSTATUS_CACHE_USED         1
   6069 #define SQLITE_DBSTATUS_SCHEMA_USED        2
   6070 #define SQLITE_DBSTATUS_STMT_USED          3
   6071 #define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
   6072 
   6073 
   6074 /*
   6075 ** CAPI3REF: Prepared Statement Status
   6076 **
   6077 ** ^(Each prepared statement maintains various
   6078 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
   6079 ** of times it has performed specific operations.)^  These counters can
   6080 ** be used to monitor the performance characteristics of the prepared
   6081 ** statements.  For example, if the number of table steps greatly exceeds
   6082 ** the number of table searches or result rows, that would tend to indicate
   6083 ** that the prepared statement is using a full table scan rather than
   6084 ** an index.
   6085 **
   6086 ** ^(This interface is used to retrieve and reset counter values from
   6087 ** a [prepared statement].  The first argument is the prepared statement
   6088 ** object to be interrogated.  The second argument
   6089 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
   6090 ** to be interrogated.)^
   6091 ** ^The current value of the requested counter is returned.
   6092 ** ^If the resetFlg is true, then the counter is reset to zero after this
   6093 ** interface call returns.
   6094 **
   6095 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
   6096 */
   6097 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
   6098 
   6099 /*
   6100 ** CAPI3REF: Status Parameters for prepared statements
   6101 **
   6102 ** These preprocessor macros define integer codes that name counter
   6103 ** values associated with the [sqlite3_stmt_status()] interface.
   6104 ** The meanings of the various counters are as follows:
   6105 **
   6106 ** <dl>
   6107 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
   6108 ** <dd>^This is the number of times that SQLite has stepped forward in
   6109 ** a table as part of a full table scan.  Large numbers for this counter
   6110 ** may indicate opportunities for performance improvement through
   6111 ** careful use of indices.</dd>
   6112 **
   6113 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
   6114 ** <dd>^This is the number of sort operations that have occurred.
   6115 ** A non-zero value in this counter may indicate an opportunity to
   6116 ** improvement performance through careful use of indices.</dd>
   6117 **
   6118 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
   6119 ** <dd>^This is the number of rows inserted into transient indices that
   6120 ** were created automatically in order to help joins run faster.
   6121 ** A non-zero value in this counter may indicate an opportunity to
   6122 ** improvement performance by adding permanent indices that do not
   6123 ** need to be reinitialized each time the statement is run.</dd>
   6124 **
   6125 ** </dl>
   6126 */
   6127 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
   6128 #define SQLITE_STMTSTATUS_SORT              2
   6129 #define SQLITE_STMTSTATUS_AUTOINDEX         3
   6130 
   6131 /*
   6132 ** CAPI3REF: Custom Page Cache Object
   6133 **
   6134 ** The sqlite3_pcache type is opaque.  It is implemented by
   6135 ** the pluggable module.  The SQLite core has no knowledge of
   6136 ** its size or internal structure and never deals with the
   6137 ** sqlite3_pcache object except by holding and passing pointers
   6138 ** to the object.
   6139 **
   6140 ** See [sqlite3_pcache_methods] for additional information.
   6141 */
   6142 typedef struct sqlite3_pcache sqlite3_pcache;
   6143 
   6144 /*
   6145 ** CAPI3REF: Application Defined Page Cache.
   6146 ** KEYWORDS: {page cache}
   6147 **
   6148 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
   6149 ** register an alternative page cache implementation by passing in an
   6150 ** instance of the sqlite3_pcache_methods structure.)^
   6151 ** In many applications, most of the heap memory allocated by
   6152 ** SQLite is used for the page cache.
   6153 ** By implementing a
   6154 ** custom page cache using this API, an application can better control
   6155 ** the amount of memory consumed by SQLite, the way in which
   6156 ** that memory is allocated and released, and the policies used to
   6157 ** determine exactly which parts of a database file are cached and for
   6158 ** how long.
   6159 **
   6160 ** The alternative page cache mechanism is an
   6161 ** extreme measure that is only needed by the most demanding applications.
   6162 ** The built-in page cache is recommended for most uses.
   6163 **
   6164 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
   6165 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
   6166 ** the application may discard the parameter after the call to
   6167 ** [sqlite3_config()] returns.)^
   6168 **
   6169 ** ^(The xInit() method is called once for each effective
   6170 ** call to [sqlite3_initialize()])^
   6171 ** (usually only once during the lifetime of the process). ^(The xInit()
   6172 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
   6173 ** The intent of the xInit() method is to set up global data structures
   6174 ** required by the custom page cache implementation.
   6175 ** ^(If the xInit() method is NULL, then the
   6176 ** built-in default page cache is used instead of the application defined
   6177 ** page cache.)^
   6178 **
   6179 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
   6180 ** It can be used to clean up
   6181 ** any outstanding resources before process shutdown, if required.
   6182 ** ^The xShutdown() method may be NULL.
   6183 **
   6184 ** ^SQLite automatically serializes calls to the xInit method,
   6185 ** so the xInit method need not be threadsafe.  ^The
   6186 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
   6187 ** not need to be threadsafe either.  All other methods must be threadsafe
   6188 ** in multithreaded applications.
   6189 **
   6190 ** ^SQLite will never invoke xInit() more than once without an intervening
   6191 ** call to xShutdown().
   6192 **
   6193 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
   6194 ** SQLite will typically create one cache instance for each open database file,
   6195 ** though this is not guaranteed. ^The
   6196 ** first parameter, szPage, is the size in bytes of the pages that must
   6197 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
   6198 ** will the page size of the database file that is to be cached plus an
   6199 ** increment (here called "R") of about 100 or 200.  SQLite will use the
   6200 ** extra R bytes on each page to store metadata about the underlying
   6201 ** database page on disk.  The value of R depends
   6202 ** on the SQLite version, the target platform, and how SQLite was compiled.
   6203 ** ^R is constant for a particular build of SQLite.  ^The second argument to
   6204 ** xCreate(), bPurgeable, is true if the cache being created will
   6205 ** be used to cache database pages of a file stored on disk, or
   6206 ** false if it is used for an in-memory database. The cache implementation
   6207 ** does not have to do anything special based with the value of bPurgeable;
   6208 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
   6209 ** never invoke xUnpin() except to deliberately delete a page.
   6210 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
   6211 ** false will always have the "discard" flag set to true.
   6212 ** ^Hence, a cache created with bPurgeable false will
   6213 ** never contain any unpinned pages.
   6214 **
   6215 ** ^(The xCachesize() method may be called at any time by SQLite to set the
   6216 ** suggested maximum cache-size (number of pages stored by) the cache
   6217 ** instance passed as the first argument. This is the value configured using
   6218 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
   6219 ** parameter, the implementation is not required to do anything with this
   6220 ** value; it is advisory only.
   6221 **
   6222 ** The xPagecount() method must return the number of pages currently
   6223 ** stored in the cache, both pinned and unpinned.
   6224 **
   6225 ** The xFetch() method locates a page in the cache and returns a pointer to
   6226 ** the page, or a NULL pointer.
   6227 ** A "page", in this context, means a buffer of szPage bytes aligned at an
   6228 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
   6229 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page
   6230 ** is considered to be "pinned".
   6231 **
   6232 ** If the requested page is already in the page cache, then the page cache
   6233 ** implementation must return a pointer to the page buffer with its content
   6234 ** intact.  If the requested page is not already in the cache, then the
   6235 ** behavior of the cache implementation should use the value of the createFlag
   6236 ** parameter to help it determined what action to take:
   6237 **
   6238 ** <table border=1 width=85% align=center>
   6239 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
   6240 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
   6241 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
   6242 **                 Otherwise return NULL.
   6243 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
   6244 **                 NULL if allocating a new page is effectively impossible.
   6245 ** </table>
   6246 **
   6247 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
   6248 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
   6249 ** failed.)^  In between the to xFetch() calls, SQLite may
   6250 ** attempt to unpin one or more cache pages by spilling the content of
   6251 ** pinned pages to disk and synching the operating system disk cache.
   6252 **
   6253 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
   6254 ** as its second argument.  If the third parameter, discard, is non-zero,
   6255 ** then the page must be evicted from the cache.
   6256 ** ^If the discard parameter is
   6257 ** zero, then the page may be discarded or retained at the discretion of
   6258 ** page cache implementation. ^The page cache implementation
   6259 ** may choose to evict unpinned pages at any time.
   6260 **
   6261 ** The cache must not perform any reference counting. A single
   6262 ** call to xUnpin() unpins the page regardless of the number of prior calls
   6263 ** to xFetch().
   6264 **
   6265 ** The xRekey() method is used to change the key value associated with the
   6266 ** page passed as the second argument. If the cache
   6267 ** previously contains an entry associated with newKey, it must be
   6268 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
   6269 ** to be pinned.
   6270 **
   6271 ** When SQLite calls the xTruncate() method, the cache must discard all
   6272 ** existing cache entries with page numbers (keys) greater than or equal
   6273 ** to the value of the iLimit parameter passed to xTruncate(). If any
   6274 ** of these pages are pinned, they are implicitly unpinned, meaning that
   6275 ** they can be safely discarded.
   6276 **
   6277 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
   6278 ** All resources associated with the specified cache should be freed. ^After
   6279 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
   6280 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
   6281 ** functions.
   6282 */
   6283 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
   6284 struct sqlite3_pcache_methods {
   6285   void *pArg;
   6286   int (*xInit)(void*);
   6287   void (*xShutdown)(void*);
   6288   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
   6289   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
   6290   int (*xPagecount)(sqlite3_pcache*);
   6291   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   6292   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
   6293   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
   6294   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   6295   void (*xDestroy)(sqlite3_pcache*);
   6296 };
   6297 
   6298 /*
   6299 ** CAPI3REF: Online Backup Object
   6300 **
   6301 ** The sqlite3_backup object records state information about an ongoing
   6302 ** online backup operation.  ^The sqlite3_backup object is created by
   6303 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
   6304 ** [sqlite3_backup_finish()].
   6305 **
   6306 ** See Also: [Using the SQLite Online Backup API]
   6307 */
   6308 typedef struct sqlite3_backup sqlite3_backup;
   6309 
   6310 /*
   6311 ** CAPI3REF: Online Backup API.
   6312 **
   6313 ** The backup API copies the content of one database into another.
   6314 ** It is useful either for creating backups of databases or
   6315 ** for copying in-memory databases to or from persistent files.
   6316 **
   6317 ** See Also: [Using the SQLite Online Backup API]
   6318 **
   6319 ** ^Exclusive access is required to the destination database for the
   6320 ** duration of the operation. ^However the source database is only
   6321 ** read-locked while it is actually being read; it is not locked
   6322 ** continuously for the entire backup operation. ^Thus, the backup may be
   6323 ** performed on a live source database without preventing other users from
   6324 ** reading or writing to the source database while the backup is underway.
   6325 **
   6326 ** ^(To perform a backup operation:
   6327 **   <ol>
   6328 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
   6329 **         backup,
   6330 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
   6331 **         the data between the two databases, and finally
   6332 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
   6333 **         associated with the backup operation.
   6334 **   </ol>)^
   6335 ** There should be exactly one call to sqlite3_backup_finish() for each
   6336 ** successful call to sqlite3_backup_init().
   6337 **
   6338 ** <b>sqlite3_backup_init()</b>
   6339 **
   6340 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
   6341 ** [database connection] associated with the destination database
   6342 ** and the database name, respectively.
   6343 ** ^The database name is "main" for the main database, "temp" for the
   6344 ** temporary database, or the name specified after the AS keyword in
   6345 ** an [ATTACH] statement for an attached database.
   6346 ** ^The S and M arguments passed to
   6347 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
   6348 ** and database name of the source database, respectively.
   6349 ** ^The source and destination [database connections] (parameters S and D)
   6350 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
   6351 ** an error.
   6352 **
   6353 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
   6354 ** returned and an error code and error message are store3d in the
   6355 ** destination [database connection] D.
   6356 ** ^The error code and message for the failed call to sqlite3_backup_init()
   6357 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
   6358 ** [sqlite3_errmsg16()] functions.
   6359 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
   6360 ** [sqlite3_backup] object.
   6361 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
   6362 ** sqlite3_backup_finish() functions to perform the specified backup
   6363 ** operation.
   6364 **
   6365 ** <b>sqlite3_backup_step()</b>
   6366 **
   6367 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
   6368 ** the source and destination databases specified by [sqlite3_backup] object B.
   6369 ** ^If N is negative, all remaining source pages are copied.
   6370 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
   6371 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
   6372 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
   6373 ** from source to destination, then it returns [SQLITE_DONE].
   6374 ** ^If an error occurs while running sqlite3_backup_step(B,N),
   6375 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
   6376 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
   6377 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
   6378 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
   6379 **
   6380 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
   6381 ** <ol>
   6382 ** <li> the destination database was opened read-only, or
   6383 ** <li> the destination database is using write-ahead-log journaling
   6384 ** and the destination and source page sizes differ, or
   6385 ** <li> The destination database is an in-memory database and the
   6386 ** destination and source page sizes differ.
   6387 ** </ol>)^
   6388 **
   6389 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
   6390 ** the [sqlite3_busy_handler | busy-handler function]
   6391 ** is invoked (if one is specified). ^If the
   6392 ** busy-handler returns non-zero before the lock is available, then
   6393 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
   6394 ** sqlite3_backup_step() can be retried later. ^If the source
   6395 ** [database connection]
   6396 ** is being used to write to the source database when sqlite3_backup_step()
   6397 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
   6398 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
   6399 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
   6400 ** [SQLITE_READONLY] is returned, then
   6401 ** there is no point in retrying the call to sqlite3_backup_step(). These
   6402 ** errors are considered fatal.)^  The application must accept
   6403 ** that the backup operation has failed and pass the backup operation handle
   6404 ** to the sqlite3_backup_finish() to release associated resources.
   6405 **
   6406 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
   6407 ** on the destination file. ^The exclusive lock is not released until either
   6408 ** sqlite3_backup_finish() is called or the backup operation is complete
   6409 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
   6410 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
   6411 ** lasts for the duration of the sqlite3_backup_step() call.
   6412 ** ^Because the source database is not locked between calls to
   6413 ** sqlite3_backup_step(), the source database may be modified mid-way
   6414 ** through the backup process.  ^If the source database is modified by an
   6415 ** external process or via a database connection other than the one being
   6416 ** used by the backup operation, then the backup will be automatically
   6417 ** restarted by the next call to sqlite3_backup_step(). ^If the source
   6418 ** database is modified by the using the same database connection as is used
   6419 ** by the backup operation, then the backup database is automatically
   6420 ** updated at the same time.
   6421 **
   6422 ** <b>sqlite3_backup_finish()</b>
   6423 **
   6424 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
   6425 ** application wishes to abandon the backup operation, the application
   6426 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
   6427 ** ^The sqlite3_backup_finish() interfaces releases all
   6428 ** resources associated with the [sqlite3_backup] object.
   6429 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
   6430 ** active write-transaction on the destination database is rolled back.
   6431 ** The [sqlite3_backup] object is invalid
   6432 ** and may not be used following a call to sqlite3_backup_finish().
   6433 **
   6434 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
   6435 ** sqlite3_backup_step() errors occurred, regardless or whether or not
   6436 ** sqlite3_backup_step() completed.
   6437 ** ^If an out-of-memory condition or IO error occurred during any prior
   6438 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
   6439 ** sqlite3_backup_finish() returns the corresponding [error code].
   6440 **
   6441 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
   6442 ** is not a permanent error and does not affect the return value of
   6443 ** sqlite3_backup_finish().
   6444 **
   6445 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
   6446 **
   6447 ** ^Each call to sqlite3_backup_step() sets two values inside
   6448 ** the [sqlite3_backup] object: the number of pages still to be backed
   6449 ** up and the total number of pages in the source database file.
   6450 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
   6451 ** retrieve these two values, respectively.
   6452 **
   6453 ** ^The values returned by these functions are only updated by
   6454 ** sqlite3_backup_step(). ^If the source database is modified during a backup
   6455 ** operation, then the values are not updated to account for any extra
   6456 ** pages that need to be updated or the size of the source database file
   6457 ** changing.
   6458 **
   6459 ** <b>Concurrent Usage of Database Handles</b>
   6460 **
   6461 ** ^The source [database connection] may be used by the application for other
   6462 ** purposes while a backup operation is underway or being initialized.
   6463 ** ^If SQLite is compiled and configured to support threadsafe database
   6464 ** connections, then the source database connection may be used concurrently
   6465 ** from within other threads.
   6466 **
   6467 ** However, the application must guarantee that the destination
   6468 ** [database connection] is not passed to any other API (by any thread) after
   6469 ** sqlite3_backup_init() is called and before the corresponding call to
   6470 ** sqlite3_backup_finish().  SQLite does not currently check to see
   6471 ** if the application incorrectly accesses the destination [database connection]
   6472 ** and so no error code is reported, but the operations may malfunction
   6473 ** nevertheless.  Use of the destination database connection while a
   6474 ** backup is in progress might also also cause a mutex deadlock.
   6475 **
   6476 ** If running in [shared cache mode], the application must
   6477 ** guarantee that the shared cache used by the destination database
   6478 ** is not accessed while the backup is running. In practice this means
   6479 ** that the application must guarantee that the disk file being
   6480 ** backed up to is not accessed by any connection within the process,
   6481 ** not just the specific connection that was passed to sqlite3_backup_init().
   6482 **
   6483 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
   6484 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
   6485 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
   6486 ** APIs are not strictly speaking threadsafe. If they are invoked at the
   6487 ** same time as another thread is invoking sqlite3_backup_step() it is
   6488 ** possible that they return invalid values.
   6489 */
   6490 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   6491   sqlite3 *pDest,                        /* Destination database handle */
   6492   const char *zDestName,                 /* Destination database name */
   6493   sqlite3 *pSource,                      /* Source database handle */
   6494   const char *zSourceName                /* Source database name */
   6495 );
   6496 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
   6497 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
   6498 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
   6499 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
   6500 
   6501 /*
   6502 ** CAPI3REF: Unlock Notification
   6503 **
   6504 ** ^When running in shared-cache mode, a database operation may fail with
   6505 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
   6506 ** individual tables within the shared-cache cannot be obtained. See
   6507 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
   6508 ** ^This API may be used to register a callback that SQLite will invoke
   6509 ** when the connection currently holding the required lock relinquishes it.
   6510 ** ^This API is only available if the library was compiled with the
   6511 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
   6512 **
   6513 ** See Also: [Using the SQLite Unlock Notification Feature].
   6514 **
   6515 ** ^Shared-cache locks are released when a database connection concludes
   6516 ** its current transaction, either by committing it or rolling it back.
   6517 **
   6518 ** ^When a connection (known as the blocked connection) fails to obtain a
   6519 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
   6520 ** identity of the database connection (the blocking connection) that
   6521 ** has locked the required resource is stored internally. ^After an
   6522 ** application receives an SQLITE_LOCKED error, it may call the
   6523 ** sqlite3_unlock_notify() method with the blocked connection handle as
   6524 ** the first argument to register for a callback that will be invoked
   6525 ** when the blocking connections current transaction is concluded. ^The
   6526 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
   6527 ** call that concludes the blocking connections transaction.
   6528 **
   6529 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
   6530 ** there is a chance that the blocking connection will have already
   6531 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
   6532 ** If this happens, then the specified callback is invoked immediately,
   6533 ** from within the call to sqlite3_unlock_notify().)^
   6534 **
   6535 ** ^If the blocked connection is attempting to obtain a write-lock on a
   6536 ** shared-cache table, and more than one other connection currently holds
   6537 ** a read-lock on the same table, then SQLite arbitrarily selects one of
   6538 ** the other connections to use as the blocking connection.
   6539 **
   6540 ** ^(There may be at most one unlock-notify callback registered by a
   6541 ** blocked connection. If sqlite3_unlock_notify() is called when the
   6542 ** blocked connection already has a registered unlock-notify callback,
   6543 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
   6544 ** called with a NULL pointer as its second argument, then any existing
   6545 ** unlock-notify callback is canceled. ^The blocked connections
   6546 ** unlock-notify callback may also be canceled by closing the blocked
   6547 ** connection using [sqlite3_close()].
   6548 **
   6549 ** The unlock-notify callback is not reentrant. If an application invokes
   6550 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
   6551 ** crash or deadlock may be the result.
   6552 **
   6553 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
   6554 ** returns SQLITE_OK.
   6555 **
   6556 ** <b>Callback Invocation Details</b>
   6557 **
   6558 ** When an unlock-notify callback is registered, the application provides a
   6559 ** single void* pointer that is passed to the callback when it is invoked.
   6560 ** However, the signature of the callback function allows SQLite to pass
   6561 ** it an array of void* context pointers. The first argument passed to
   6562 ** an unlock-notify callback is a pointer to an array of void* pointers,
   6563 ** and the second is the number of entries in the array.
   6564 **
   6565 ** When a blocking connections transaction is concluded, there may be
   6566 ** more than one blocked connection that has registered for an unlock-notify
   6567 ** callback. ^If two or more such blocked connections have specified the
   6568 ** same callback function, then instead of invoking the callback function
   6569 ** multiple times, it is invoked once with the set of void* context pointers
   6570 ** specified by the blocked connections bundled together into an array.
   6571 ** This gives the application an opportunity to prioritize any actions
   6572 ** related to the set of unblocked database connections.
   6573 **
   6574 ** <b>Deadlock Detection</b>
   6575 **
   6576 ** Assuming that after registering for an unlock-notify callback a
   6577 ** database waits for the callback to be issued before taking any further
   6578 ** action (a reasonable assumption), then using this API may cause the
   6579 ** application to deadlock. For example, if connection X is waiting for
   6580 ** connection Y's transaction to be concluded, and similarly connection
   6581 ** Y is waiting on connection X's transaction, then neither connection
   6582 ** will proceed and the system may remain deadlocked indefinitely.
   6583 **
   6584 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
   6585 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
   6586 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
   6587 ** unlock-notify callback is registered. The system is said to be in
   6588 ** a deadlocked state if connection A has registered for an unlock-notify
   6589 ** callback on the conclusion of connection B's transaction, and connection
   6590 ** B has itself registered for an unlock-notify callback when connection
   6591 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
   6592 ** the system is also considered to be deadlocked if connection B has
   6593 ** registered for an unlock-notify callback on the conclusion of connection
   6594 ** C's transaction, where connection C is waiting on connection A. ^Any
   6595 ** number of levels of indirection are allowed.
   6596 **
   6597 ** <b>The "DROP TABLE" Exception</b>
   6598 **
   6599 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
   6600 ** always appropriate to call sqlite3_unlock_notify(). There is however,
   6601 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
   6602 ** SQLite checks if there are any currently executing SELECT statements
   6603 ** that belong to the same connection. If there are, SQLITE_LOCKED is
   6604 ** returned. In this case there is no "blocking connection", so invoking
   6605 ** sqlite3_unlock_notify() results in the unlock-notify callback being
   6606 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
   6607 ** or "DROP INDEX" query, an infinite loop might be the result.
   6608 **
   6609 ** One way around this problem is to check the extended error code returned
   6610 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
   6611 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
   6612 ** the special "DROP TABLE/INDEX" case, the extended error code is just
   6613 ** SQLITE_LOCKED.)^
   6614 */
   6615 SQLITE_API int sqlite3_unlock_notify(
   6616   sqlite3 *pBlocked,                          /* Waiting connection */
   6617   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
   6618   void *pNotifyArg                            /* Argument to pass to xNotify */
   6619 );
   6620 
   6621 
   6622 /*
   6623 ** CAPI3REF: String Comparison
   6624 **
   6625 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
   6626 ** compare the contents of two buffers containing UTF-8 strings in a
   6627 ** case-independent fashion, using the same definition of case independence
   6628 ** that SQLite uses internally when comparing identifiers.
   6629 */
   6630 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
   6631 
   6632 /*
   6633 ** CAPI3REF: Error Logging Interface
   6634 **
   6635 ** ^The [sqlite3_log()] interface writes a message into the error log
   6636 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
   6637 ** ^If logging is enabled, the zFormat string and subsequent arguments are
   6638 ** used with [sqlite3_snprintf()] to generate the final output string.
   6639 **
   6640 ** The sqlite3_log() interface is intended for use by extensions such as
   6641 ** virtual tables, collating functions, and SQL functions.  While there is
   6642 ** nothing to prevent an application from calling sqlite3_log(), doing so
   6643 ** is considered bad form.
   6644 **
   6645 ** The zFormat string must not be NULL.
   6646 **
   6647 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
   6648 ** will not use dynamically allocated memory.  The log message is stored in
   6649 ** a fixed-length buffer on the stack.  If the log message is longer than
   6650 ** a few hundred characters, it will be truncated to the length of the
   6651 ** buffer.
   6652 */
   6653 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
   6654 
   6655 /*
   6656 ** CAPI3REF: Write-Ahead Log Commit Hook
   6657 **
   6658 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
   6659 ** will be invoked each time a database connection commits data to a
   6660 ** [write-ahead log] (i.e. whenever a transaction is committed in
   6661 ** [journal_mode | journal_mode=WAL mode]).
   6662 **
   6663 ** ^The callback is invoked by SQLite after the commit has taken place and
   6664 ** the associated write-lock on the database released, so the implementation
   6665 ** may read, write or [checkpoint] the database as required.
   6666 **
   6667 ** ^The first parameter passed to the callback function when it is invoked
   6668 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
   6669 ** registering the callback. ^The second is a copy of the database handle.
   6670 ** ^The third parameter is the name of the database that was written to -
   6671 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
   6672 ** is the number of pages currently in the write-ahead log file,
   6673 ** including those that were just committed.
   6674 **
   6675 ** The callback function should normally return [SQLITE_OK].  ^If an error
   6676 ** code is returned, that error will propagate back up through the
   6677 ** SQLite code base to cause the statement that provoked the callback
   6678 ** to report an error, though the commit will have still occurred. If the
   6679 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
   6680 ** that does not correspond to any valid SQLite error code, the results
   6681 ** are undefined.
   6682 **
   6683 ** A single database handle may have at most a single write-ahead log callback
   6684 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
   6685 ** previously registered write-ahead log callback. ^Note that the
   6686 ** [sqlite3_wal_autocheckpoint()] interface and the
   6687 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
   6688 ** those overwrite any prior [sqlite3_wal_hook()] settings.
   6689 */
   6690 SQLITE_API void *sqlite3_wal_hook(
   6691   sqlite3*,
   6692   int(*)(void *,sqlite3*,const char*,int),
   6693   void*
   6694 );
   6695 
   6696 /*
   6697 ** CAPI3REF: Configure an auto-checkpoint
   6698 **
   6699 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
   6700 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
   6701 ** to automatically [checkpoint]
   6702 ** after committing a transaction if there are N or
   6703 ** more frames in the [write-ahead log] file.  ^Passing zero or
   6704 ** a negative value as the nFrame parameter disables automatic
   6705 ** checkpoints entirely.
   6706 **
   6707 ** ^The callback registered by this function replaces any existing callback
   6708 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
   6709 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
   6710 ** configured by this function.
   6711 **
   6712 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
   6713 ** from SQL.
   6714 **
   6715 ** ^Every new [database connection] defaults to having the auto-checkpoint
   6716 ** enabled with a threshold of 1000 pages.  The use of this interface
   6717 ** is only necessary if the default setting is found to be suboptimal
   6718 ** for a particular application.
   6719 */
   6720 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
   6721 
   6722 /*
   6723 ** CAPI3REF: Checkpoint a database
   6724 **
   6725 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
   6726 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
   6727 ** empty string, then a checkpoint is run on all databases of
   6728 ** connection D.  ^If the database connection D is not in
   6729 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
   6730 **
   6731 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
   6732 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
   6733 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
   6734 ** run whenever the WAL reaches a certain size threshold.
   6735 */
   6736 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
   6737 
   6738 /*
   6739 ** Undo the hack that converts floating point types to integer for
   6740 ** builds on processors without floating point support.
   6741 */
   6742 #ifdef SQLITE_OMIT_FLOATING_POINT
   6743 # undef double
   6744 #endif
   6745 
   6746 #if 0
   6747 }  /* End of the 'extern "C"' block */
   6748 #endif
   6749 #endif
   6750 
   6751 /*
   6752 ** 2010 August 30
   6753 **
   6754 ** The author disclaims copyright to this source code.  In place of
   6755 ** a legal notice, here is a blessing:
   6756 **
   6757 **    May you do good and not evil.
   6758 **    May you find forgiveness for yourself and forgive others.
   6759 **    May you share freely, never taking more than you give.
   6760 **
   6761 *************************************************************************
   6762 */
   6763 
   6764 #ifndef _SQLITE3RTREE_H_
   6765 #define _SQLITE3RTREE_H_
   6766 
   6767 
   6768 #if 0
   6769 extern "C" {
   6770 #endif
   6771 
   6772 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
   6773 
   6774 /*
   6775 ** Register a geometry callback named zGeom that can be used as part of an
   6776 ** R-Tree geometry query as follows:
   6777 **
   6778 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
   6779 */
   6780 SQLITE_API int sqlite3_rtree_geometry_callback(
   6781   sqlite3 *db,
   6782   const char *zGeom,
   6783   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
   6784   void *pContext
   6785 );
   6786 
   6787 
   6788 /*
   6789 ** A pointer to a structure of the following type is passed as the first
   6790 ** argument to callbacks registered using rtree_geometry_callback().
   6791 */
   6792 struct sqlite3_rtree_geometry {
   6793   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
   6794   int nParam;                     /* Size of array aParam[] */
   6795   double *aParam;                 /* Parameters passed to SQL geom function */
   6796   void *pUser;                    /* Callback implementation user data */
   6797   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
   6798 };
   6799 
   6800 
   6801 #if 0
   6802 }  /* end of the 'extern "C"' block */
   6803 #endif
   6804 
   6805 #endif  /* ifndef _SQLITE3RTREE_H_ */
   6806 
   6807 
   6808 /************** End of sqlite3.h *********************************************/
   6809 /************** Continuing where we left off in sqliteInt.h ******************/
   6810 /************** Include hash.h in the middle of sqliteInt.h ******************/
   6811 /************** Begin file hash.h ********************************************/
   6812 /*
   6813 ** 2001 September 22
   6814 **
   6815 ** The author disclaims copyright to this source code.  In place of
   6816 ** a legal notice, here is a blessing:
   6817 **
   6818 **    May you do good and not evil.
   6819 **    May you find forgiveness for yourself and forgive others.
   6820 **    May you share freely, never taking more than you give.
   6821 **
   6822 *************************************************************************
   6823 ** This is the header file for the generic hash-table implemenation
   6824 ** used in SQLite.
   6825 */
   6826 #ifndef _SQLITE_HASH_H_
   6827 #define _SQLITE_HASH_H_
   6828 
   6829 /* Forward declarations of structures. */
   6830 typedef struct Hash Hash;
   6831 typedef struct HashElem HashElem;
   6832 
   6833 /* A complete hash table is an instance of the following structure.
   6834 ** The internals of this structure are intended to be opaque -- client
   6835 ** code should not attempt to access or modify the fields of this structure
   6836 ** directly.  Change this structure only by using the routines below.
   6837 ** However, some of the "procedures" and "functions" for modifying and
   6838 ** accessing this structure are really macros, so we can't really make
   6839 ** this structure opaque.
   6840 **
   6841 ** All elements of the hash table are on a single doubly-linked list.
   6842 ** Hash.first points to the head of this list.
   6843 **
   6844 ** There are Hash.htsize buckets.  Each bucket points to a spot in
   6845 ** the global doubly-linked list.  The contents of the bucket are the
   6846 ** element pointed to plus the next _ht.count-1 elements in the list.
   6847 **
   6848 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
   6849 ** by a linear search of the global list.  For small tables, the
   6850 ** Hash.ht table is never allocated because if there are few elements
   6851 ** in the table, it is faster to do a linear search than to manage
   6852 ** the hash table.
   6853 */
   6854 struct Hash {
   6855   unsigned int htsize;      /* Number of buckets in the hash table */
   6856   unsigned int count;       /* Number of entries in this table */
   6857   HashElem *first;          /* The first element of the array */
   6858   struct _ht {              /* the hash table */
   6859     int count;                 /* Number of entries with this hash */
   6860     HashElem *chain;           /* Pointer to first entry with this hash */
   6861   } *ht;
   6862 };
   6863 
   6864 /* Each element in the hash table is an instance of the following
   6865 ** structure.  All elements are stored on a single doubly-linked list.
   6866 **
   6867 ** Again, this structure is intended to be opaque, but it can't really
   6868 ** be opaque because it is used by macros.
   6869 */
   6870 struct HashElem {
   6871   HashElem *next, *prev;       /* Next and previous elements in the table */
   6872   void *data;                  /* Data associated with this element */
   6873   const char *pKey; int nKey;  /* Key associated with this element */
   6874 };
   6875 
   6876 /*
   6877 ** Access routines.  To delete, insert a NULL pointer.
   6878 */
   6879 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
   6880 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
   6881 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
   6882 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
   6883 
   6884 /*
   6885 ** Macros for looping over all elements of a hash table.  The idiom is
   6886 ** like this:
   6887 **
   6888 **   Hash h;
   6889 **   HashElem *p;
   6890 **   ...
   6891 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
   6892 **     SomeStructure *pData = sqliteHashData(p);
   6893 **     // do something with pData
   6894 **   }
   6895 */
   6896 #define sqliteHashFirst(H)  ((H)->first)
   6897 #define sqliteHashNext(E)   ((E)->next)
   6898 #define sqliteHashData(E)   ((E)->data)
   6899 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
   6900 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
   6901 
   6902 /*
   6903 ** Number of entries in a hash table
   6904 */
   6905 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
   6906 
   6907 #endif /* _SQLITE_HASH_H_ */
   6908 
   6909 /************** End of hash.h ************************************************/
   6910 /************** Continuing where we left off in sqliteInt.h ******************/
   6911 /************** Include parse.h in the middle of sqliteInt.h *****************/
   6912 /************** Begin file parse.h *******************************************/
   6913 #define TK_SEMI                            1
   6914 #define TK_EXPLAIN                         2
   6915 #define TK_QUERY                           3
   6916 #define TK_PLAN                            4
   6917 #define TK_BEGIN                           5
   6918 #define TK_TRANSACTION                     6
   6919 #define TK_DEFERRED                        7
   6920 #define TK_IMMEDIATE                       8
   6921 #define TK_EXCLUSIVE                       9
   6922 #define TK_COMMIT                         10
   6923 #define TK_END                            11
   6924 #define TK_ROLLBACK                       12
   6925 #define TK_SAVEPOINT                      13
   6926 #define TK_RELEASE                        14
   6927 #define TK_TO                             15
   6928 #define TK_TABLE                          16
   6929 #define TK_CREATE                         17
   6930 #define TK_IF                             18
   6931 #define TK_NOT                            19
   6932 #define TK_EXISTS                         20
   6933 #define TK_TEMP                           21
   6934 #define TK_LP                             22
   6935 #define TK_RP                             23
   6936 #define TK_AS                             24
   6937 #define TK_COMMA                          25
   6938 #define TK_ID                             26
   6939 #define TK_INDEXED                        27
   6940 #define TK_ABORT                          28
   6941 #define TK_ACTION                         29
   6942 #define TK_AFTER                          30
   6943 #define TK_ANALYZE                        31
   6944 #define TK_ASC                            32
   6945 #define TK_ATTACH                         33
   6946 #define TK_BEFORE                         34
   6947 #define TK_BY                             35
   6948 #define TK_CASCADE                        36
   6949 #define TK_CAST                           37
   6950 #define TK_COLUMNKW                       38
   6951 #define TK_CONFLICT                       39
   6952 #define TK_DATABASE                       40
   6953 #define TK_DESC                           41
   6954 #define TK_DETACH                         42
   6955 #define TK_EACH                           43
   6956 #define TK_FAIL                           44
   6957 #define TK_FOR                            45
   6958 #define TK_IGNORE                         46
   6959 #define TK_INITIALLY                      47
   6960 #define TK_INSTEAD                        48
   6961 #define TK_LIKE_KW                        49
   6962 #define TK_MATCH                          50
   6963 #define TK_NO                             51
   6964 #define TK_KEY                            52
   6965 #define TK_OF                             53
   6966 #define TK_OFFSET                         54
   6967 #define TK_PRAGMA                         55
   6968 #define TK_RAISE                          56
   6969 #define TK_REPLACE                        57
   6970 #define TK_RESTRICT                       58
   6971 #define TK_ROW                            59
   6972 #define TK_TRIGGER                        60
   6973 #define TK_VACUUM                         61
   6974 #define TK_VIEW                           62
   6975 #define TK_VIRTUAL                        63
   6976 #define TK_REINDEX                        64
   6977 #define TK_RENAME                         65
   6978 #define TK_CTIME_KW                       66
   6979 #define TK_ANY                            67
   6980 #define TK_OR                             68
   6981 #define TK_AND                            69
   6982 #define TK_IS                             70
   6983 #define TK_BETWEEN                        71
   6984 #define TK_IN                             72
   6985 #define TK_ISNULL                         73
   6986 #define TK_NOTNULL                        74
   6987 #define TK_NE                             75
   6988 #define TK_EQ                             76
   6989 #define TK_GT                             77
   6990 #define TK_LE                             78
   6991 #define TK_LT                             79
   6992 #define TK_GE                             80
   6993 #define TK_ESCAPE                         81
   6994 #define TK_BITAND                         82
   6995 #define TK_BITOR                          83
   6996 #define TK_LSHIFT                         84
   6997 #define TK_RSHIFT                         85
   6998 #define TK_PLUS                           86
   6999 #define TK_MINUS                          87
   7000 #define TK_STAR                           88
   7001 #define TK_SLASH                          89
   7002 #define TK_REM                            90
   7003 #define TK_CONCAT                         91
   7004 #define TK_COLLATE                        92
   7005 #define TK_BITNOT                         93
   7006 #define TK_STRING                         94
   7007 #define TK_JOIN_KW                        95
   7008 #define TK_CONSTRAINT                     96
   7009 #define TK_DEFAULT                        97
   7010 #define TK_NULL                           98
   7011 #define TK_PRIMARY                        99
   7012 #define TK_UNIQUE                         100
   7013 #define TK_CHECK                          101
   7014 #define TK_REFERENCES                     102
   7015 #define TK_AUTOINCR                       103
   7016 #define TK_ON                             104
   7017 #define TK_INSERT                         105
   7018 #define TK_DELETE                         106
   7019 #define TK_UPDATE                         107
   7020 #define TK_SET                            108
   7021 #define TK_DEFERRABLE                     109
   7022 #define TK_FOREIGN                        110
   7023 #define TK_DROP                           111
   7024 #define TK_UNION                          112
   7025 #define TK_ALL                            113
   7026 #define TK_EXCEPT                         114
   7027 #define TK_INTERSECT                      115
   7028 #define TK_SELECT                         116
   7029 #define TK_DISTINCT                       117
   7030 #define TK_DOT                            118
   7031 #define TK_FROM                           119
   7032 #define TK_JOIN                           120
   7033 #define TK_USING                          121
   7034 #define TK_ORDER                          122
   7035 #define TK_GROUP                          123
   7036 #define TK_HAVING                         124
   7037 #define TK_LIMIT                          125
   7038 #define TK_WHERE                          126
   7039 #define TK_INTO                           127
   7040 #define TK_VALUES                         128
   7041 #define TK_INTEGER                        129
   7042 #define TK_FLOAT                          130
   7043 #define TK_BLOB                           131
   7044 #define TK_REGISTER                       132
   7045 #define TK_VARIABLE                       133
   7046 #define TK_CASE                           134
   7047 #define TK_WHEN                           135
   7048 #define TK_THEN                           136
   7049 #define TK_ELSE                           137
   7050 #define TK_INDEX                          138
   7051 #define TK_ALTER                          139
   7052 #define TK_ADD                            140
   7053 #define TK_TO_TEXT                        141
   7054 #define TK_TO_BLOB                        142
   7055 #define TK_TO_NUMERIC                     143
   7056 #define TK_TO_INT                         144
   7057 #define TK_TO_REAL                        145
   7058 #define TK_ISNOT                          146
   7059 #define TK_END_OF_FILE                    147
   7060 #define TK_ILLEGAL                        148
   7061 #define TK_SPACE                          149
   7062 #define TK_UNCLOSED_STRING                150
   7063 #define TK_FUNCTION                       151
   7064 #define TK_COLUMN                         152
   7065 #define TK_AGG_FUNCTION                   153
   7066 #define TK_AGG_COLUMN                     154
   7067 #define TK_CONST_FUNC                     155
   7068 #define TK_UMINUS                         156
   7069 #define TK_UPLUS                          157
   7070 
   7071 /************** End of parse.h ***********************************************/
   7072 /************** Continuing where we left off in sqliteInt.h ******************/
   7073 #include <stdio.h>
   7074 #include <stdlib.h>
   7075 #include <string.h>
   7076 #include <assert.h>
   7077 #include <stddef.h>
   7078 
   7079 /*
   7080 ** If compiling for a processor that lacks floating point support,
   7081 ** substitute integer for floating-point
   7082 */
   7083 #ifdef SQLITE_OMIT_FLOATING_POINT
   7084 # define double sqlite_int64
   7085 # define float sqlite_int64
   7086 # define LONGDOUBLE_TYPE sqlite_int64
   7087 # ifndef SQLITE_BIG_DBL
   7088 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
   7089 # endif
   7090 # define SQLITE_OMIT_DATETIME_FUNCS 1
   7091 # define SQLITE_OMIT_TRACE 1
   7092 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   7093 # undef SQLITE_HAVE_ISNAN
   7094 #endif
   7095 #ifndef SQLITE_BIG_DBL
   7096 # define SQLITE_BIG_DBL (1e99)
   7097 #endif
   7098 
   7099 /*
   7100 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
   7101 ** afterward. Having this macro allows us to cause the C compiler
   7102 ** to omit code used by TEMP tables without messy #ifndef statements.
   7103 */
   7104 #ifdef SQLITE_OMIT_TEMPDB
   7105 #define OMIT_TEMPDB 1
   7106 #else
   7107 #define OMIT_TEMPDB 0
   7108 #endif
   7109 
   7110 /*
   7111 ** The "file format" number is an integer that is incremented whenever
   7112 ** the VDBE-level file format changes.  The following macros define the
   7113 ** the default file format for new databases and the maximum file format
   7114 ** that the library can read.
   7115 */
   7116 #define SQLITE_MAX_FILE_FORMAT 4
   7117 #ifndef SQLITE_DEFAULT_FILE_FORMAT
   7118 # define SQLITE_DEFAULT_FILE_FORMAT 1
   7119 #endif
   7120 
   7121 /*
   7122 ** Determine whether triggers are recursive by default.  This can be
   7123 ** changed at run-time using a pragma.
   7124 */
   7125 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   7126 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
   7127 #endif
   7128 
   7129 /*
   7130 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
   7131 ** on the command-line
   7132 */
   7133 #ifndef SQLITE_TEMP_STORE
   7134 # define SQLITE_TEMP_STORE 1
   7135 #endif
   7136 
   7137 /*
   7138 ** GCC does not define the offsetof() macro so we'll have to do it
   7139 ** ourselves.
   7140 */
   7141 #ifndef offsetof
   7142 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
   7143 #endif
   7144 
   7145 /*
   7146 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
   7147 ** not, there are still machines out there that use EBCDIC.)
   7148 */
   7149 #if 'A' == '\301'
   7150 # define SQLITE_EBCDIC 1
   7151 #else
   7152 # define SQLITE_ASCII 1
   7153 #endif
   7154 
   7155 /*
   7156 ** Integers of known sizes.  These typedefs might change for architectures
   7157 ** where the sizes very.  Preprocessor macros are available so that the
   7158 ** types can be conveniently redefined at compile-type.  Like this:
   7159 **
   7160 **         cc '-DUINTPTR_TYPE=long long int' ...
   7161 */
   7162 #ifndef UINT32_TYPE
   7163 # ifdef HAVE_UINT32_T
   7164 #  define UINT32_TYPE uint32_t
   7165 # else
   7166 #  define UINT32_TYPE unsigned int
   7167 # endif
   7168 #endif
   7169 #ifndef UINT16_TYPE
   7170 # ifdef HAVE_UINT16_T
   7171 #  define UINT16_TYPE uint16_t
   7172 # else
   7173 #  define UINT16_TYPE unsigned short int
   7174 # endif
   7175 #endif
   7176 #ifndef INT16_TYPE
   7177 # ifdef HAVE_INT16_T
   7178 #  define INT16_TYPE int16_t
   7179 # else
   7180 #  define INT16_TYPE short int
   7181 # endif
   7182 #endif
   7183 #ifndef UINT8_TYPE
   7184 # ifdef HAVE_UINT8_T
   7185 #  define UINT8_TYPE uint8_t
   7186 # else
   7187 #  define UINT8_TYPE unsigned char
   7188 # endif
   7189 #endif
   7190 #ifndef INT8_TYPE
   7191 # ifdef HAVE_INT8_T
   7192 #  define INT8_TYPE int8_t
   7193 # else
   7194 #  define INT8_TYPE signed char
   7195 # endif
   7196 #endif
   7197 #ifndef LONGDOUBLE_TYPE
   7198 # define LONGDOUBLE_TYPE long double
   7199 #endif
   7200 typedef sqlite_int64 i64;          /* 8-byte signed integer */
   7201 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
   7202 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
   7203 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
   7204 typedef INT16_TYPE i16;            /* 2-byte signed integer */
   7205 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
   7206 typedef INT8_TYPE i8;              /* 1-byte signed integer */
   7207 
   7208 /*
   7209 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
   7210 ** that can be stored in a u32 without loss of data.  The value
   7211 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
   7212 ** have to specify the value in the less intuitive manner shown:
   7213 */
   7214 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
   7215 
   7216 /*
   7217 ** Macros to determine whether the machine is big or little endian,
   7218 ** evaluated at runtime.
   7219 */
   7220 #ifdef SQLITE_AMALGAMATION
   7221 SQLITE_PRIVATE const int sqlite3one = 1;
   7222 #else
   7223 SQLITE_PRIVATE const int sqlite3one;
   7224 #endif
   7225 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
   7226                              || defined(__x86_64) || defined(__x86_64__)
   7227 # define SQLITE_BIGENDIAN    0
   7228 # define SQLITE_LITTLEENDIAN 1
   7229 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
   7230 #else
   7231 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
   7232 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
   7233 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
   7234 #endif
   7235 
   7236 /*
   7237 ** Constants for the largest and smallest possible 64-bit signed integers.
   7238 ** These macros are designed to work correctly on both 32-bit and 64-bit
   7239 ** compilers.
   7240 */
   7241 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
   7242 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
   7243 
   7244 /*
   7245 ** Round up a number to the next larger multiple of 8.  This is used
   7246 ** to force 8-byte alignment on 64-bit architectures.
   7247 */
   7248 #define ROUND8(x)     (((x)+7)&~7)
   7249 
   7250 /*
   7251 ** Round down to the nearest multiple of 8
   7252 */
   7253 #define ROUNDDOWN8(x) ((x)&~7)
   7254 
   7255 /*
   7256 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
   7257 ** macro is used only within assert() to verify that the code gets
   7258 ** all alignment restrictions correct.
   7259 **
   7260 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
   7261 ** underlying malloc() implemention might return us 4-byte aligned
   7262 ** pointers.  In that case, only verify 4-byte alignment.
   7263 */
   7264 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   7265 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
   7266 #else
   7267 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
   7268 #endif
   7269 
   7270 
   7271 /*
   7272 ** An instance of the following structure is used to store the busy-handler
   7273 ** callback for a given sqlite handle.
   7274 **
   7275 ** The sqlite.busyHandler member of the sqlite struct contains the busy
   7276 ** callback for the database handle. Each pager opened via the sqlite
   7277 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
   7278 ** callback is currently invoked only from within pager.c.
   7279 */
   7280 typedef struct BusyHandler BusyHandler;
   7281 struct BusyHandler {
   7282   int (*xFunc)(void *,int);  /* The busy callback */
   7283   void *pArg;                /* First arg to busy callback */
   7284   int nBusy;                 /* Incremented with each busy call */
   7285 };
   7286 
   7287 /*
   7288 ** Name of the master database table.  The master database table
   7289 ** is a special table that holds the names and attributes of all
   7290 ** user tables and indices.
   7291 */
   7292 #define MASTER_NAME       "sqlite_master"
   7293 #define TEMP_MASTER_NAME  "sqlite_temp_master"
   7294 
   7295 /*
   7296 ** The root-page of the master database table.
   7297 */
   7298 #define MASTER_ROOT       1
   7299 
   7300 /*
   7301 ** The name of the schema table.
   7302 */
   7303 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
   7304 
   7305 /*
   7306 ** A convenience macro that returns the number of elements in
   7307 ** an array.
   7308 */
   7309 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
   7310 
   7311 /*
   7312 ** The following value as a destructor means to use sqlite3DbFree().
   7313 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
   7314 */
   7315 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
   7316 
   7317 /*
   7318 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
   7319 ** not support Writable Static Data (WSD) such as global and static variables.
   7320 ** All variables must either be on the stack or dynamically allocated from
   7321 ** the heap.  When WSD is unsupported, the variable declarations scattered
   7322 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
   7323 ** macro is used for this purpose.  And instead of referencing the variable
   7324 ** directly, we use its constant as a key to lookup the run-time allocated
   7325 ** buffer that holds real variable.  The constant is also the initializer
   7326 ** for the run-time allocated buffer.
   7327 **
   7328 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
   7329 ** macros become no-ops and have zero performance impact.
   7330 */
   7331 #ifdef SQLITE_OMIT_WSD
   7332   #define SQLITE_WSD const
   7333   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
   7334   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
   7335 SQLITE_API   int sqlite3_wsd_init(int N, int J);
   7336 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
   7337 #else
   7338   #define SQLITE_WSD
   7339   #define GLOBAL(t,v) v
   7340   #define sqlite3GlobalConfig sqlite3Config
   7341 #endif
   7342 
   7343 /*
   7344 ** The following macros are used to suppress compiler warnings and to
   7345 ** make it clear to human readers when a function parameter is deliberately
   7346 ** left unused within the body of a function. This usually happens when
   7347 ** a function is called via a function pointer. For example the
   7348 ** implementation of an SQL aggregate step callback may not use the
   7349 ** parameter indicating the number of arguments passed to the aggregate,
   7350 ** if it knows that this is enforced elsewhere.
   7351 **
   7352 ** When a function parameter is not used at all within the body of a function,
   7353 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
   7354 ** However, these macros may also be used to suppress warnings related to
   7355 ** parameters that may or may not be used depending on compilation options.
   7356 ** For example those parameters only used in assert() statements. In these
   7357 ** cases the parameters are named as per the usual conventions.
   7358 */
   7359 #define UNUSED_PARAMETER(x) (void)(x)
   7360 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
   7361 
   7362 /*
   7363 ** Forward references to structures
   7364 */
   7365 typedef struct AggInfo AggInfo;
   7366 typedef struct AuthContext AuthContext;
   7367 typedef struct AutoincInfo AutoincInfo;
   7368 typedef struct Bitvec Bitvec;
   7369 typedef struct CollSeq CollSeq;
   7370 typedef struct Column Column;
   7371 typedef struct Db Db;
   7372 typedef struct Schema Schema;
   7373 typedef struct Expr Expr;
   7374 typedef struct ExprList ExprList;
   7375 typedef struct ExprSpan ExprSpan;
   7376 typedef struct FKey FKey;
   7377 typedef struct FuncDestructor FuncDestructor;
   7378 typedef struct FuncDef FuncDef;
   7379 typedef struct FuncDefHash FuncDefHash;
   7380 typedef struct IdList IdList;
   7381 typedef struct Index Index;
   7382 typedef struct IndexSample IndexSample;
   7383 typedef struct KeyClass KeyClass;
   7384 typedef struct KeyInfo KeyInfo;
   7385 typedef struct Lookaside Lookaside;
   7386 typedef struct LookasideSlot LookasideSlot;
   7387 typedef struct Module Module;
   7388 typedef struct NameContext NameContext;
   7389 typedef struct Parse Parse;
   7390 typedef struct RowSet RowSet;
   7391 typedef struct Savepoint Savepoint;
   7392 typedef struct Select Select;
   7393 typedef struct SrcList SrcList;
   7394 typedef struct StrAccum StrAccum;
   7395 typedef struct Table Table;
   7396 typedef struct TableLock TableLock;
   7397 typedef struct Token Token;
   7398 typedef struct Trigger Trigger;
   7399 typedef struct TriggerPrg TriggerPrg;
   7400 typedef struct TriggerStep TriggerStep;
   7401 typedef struct UnpackedRecord UnpackedRecord;
   7402 typedef struct VTable VTable;
   7403 typedef struct Walker Walker;
   7404 typedef struct WherePlan WherePlan;
   7405 typedef struct WhereInfo WhereInfo;
   7406 typedef struct WhereLevel WhereLevel;
   7407 
   7408 /*
   7409 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
   7410 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
   7411 ** pointer types (i.e. FuncDef) defined above.
   7412 */
   7413 /************** Include btree.h in the middle of sqliteInt.h *****************/
   7414 /************** Begin file btree.h *******************************************/
   7415 /*
   7416 ** 2001 September 15
   7417 **
   7418 ** The author disclaims copyright to this source code.  In place of
   7419 ** a legal notice, here is a blessing:
   7420 **
   7421 **    May you do good and not evil.
   7422 **    May you find forgiveness for yourself and forgive others.
   7423 **    May you share freely, never taking more than you give.
   7424 **
   7425 *************************************************************************
   7426 ** This header file defines the interface that the sqlite B-Tree file
   7427 ** subsystem.  See comments in the source code for a detailed description
   7428 ** of what each interface routine does.
   7429 */
   7430 #ifndef _BTREE_H_
   7431 #define _BTREE_H_
   7432 
   7433 /* TODO: This definition is just included so other modules compile. It
   7434 ** needs to be revisited.
   7435 */
   7436 #define SQLITE_N_BTREE_META 10
   7437 
   7438 /*
   7439 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
   7440 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
   7441 */
   7442 #ifndef SQLITE_DEFAULT_AUTOVACUUM
   7443   #define SQLITE_DEFAULT_AUTOVACUUM 0
   7444 #endif
   7445 
   7446 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
   7447 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
   7448 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
   7449 
   7450 /*
   7451 ** Forward declarations of structure
   7452 */
   7453 typedef struct Btree Btree;
   7454 typedef struct BtCursor BtCursor;
   7455 typedef struct BtShared BtShared;
   7456 typedef struct BtreeMutexArray BtreeMutexArray;
   7457 
   7458 /*
   7459 ** This structure records all of the Btrees that need to hold
   7460 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
   7461 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
   7462 ** we can always lock and unlock them all quickly.
   7463 */
   7464 struct BtreeMutexArray {
   7465   int nMutex;
   7466   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
   7467 };
   7468 
   7469 
   7470 SQLITE_PRIVATE int sqlite3BtreeOpen(
   7471   const char *zFilename,   /* Name of database file to open */
   7472   sqlite3 *db,             /* Associated database connection */
   7473   Btree **ppBtree,         /* Return open Btree* here */
   7474   int flags,               /* Flags */
   7475   int vfsFlags             /* Flags passed through to VFS open */
   7476 );
   7477 
   7478 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
   7479 ** following values.
   7480 **
   7481 ** NOTE:  These values must match the corresponding PAGER_ values in
   7482 ** pager.h.
   7483 */
   7484 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
   7485 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
   7486 #define BTREE_MEMORY        4  /* This is an in-memory DB */
   7487 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
   7488 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
   7489 
   7490 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
   7491 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
   7492 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
   7493 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
   7494 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
   7495 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
   7496 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
   7497 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
   7498 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
   7499 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
   7500 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
   7501 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
   7502 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
   7503 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
   7504 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
   7505 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
   7506 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
   7507 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
   7508 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
   7509 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
   7510 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
   7511 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
   7512 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
   7513 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
   7514 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
   7515 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
   7516 
   7517 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
   7518 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
   7519 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
   7520 
   7521 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
   7522 
   7523 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
   7524 ** of the flags shown below.
   7525 **
   7526 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
   7527 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
   7528 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
   7529 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
   7530 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
   7531 ** indices.)
   7532 */
   7533 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
   7534 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
   7535 
   7536 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
   7537 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
   7538 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
   7539 
   7540 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
   7541 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
   7542 
   7543 /*
   7544 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
   7545 ** should be one of the following values. The integer values are assigned
   7546 ** to constants so that the offset of the corresponding field in an
   7547 ** SQLite database header may be found using the following formula:
   7548 **
   7549 **   offset = 36 + (idx * 4)
   7550 **
   7551 ** For example, the free-page-count field is located at byte offset 36 of
   7552 ** the database file header. The incr-vacuum-flag field is located at
   7553 ** byte offset 64 (== 36+4*7).
   7554 */
   7555 #define BTREE_FREE_PAGE_COUNT     0
   7556 #define BTREE_SCHEMA_VERSION      1
   7557 #define BTREE_FILE_FORMAT         2
   7558 #define BTREE_DEFAULT_CACHE_SIZE  3
   7559 #define BTREE_LARGEST_ROOT_PAGE   4
   7560 #define BTREE_TEXT_ENCODING       5
   7561 #define BTREE_USER_VERSION        6
   7562 #define BTREE_INCR_VACUUM         7
   7563 
   7564 SQLITE_PRIVATE int sqlite3BtreeCursor(
   7565   Btree*,                              /* BTree containing table to open */
   7566   int iTable,                          /* Index of root page */
   7567   int wrFlag,                          /* 1 for writing.  0 for read-only */
   7568   struct KeyInfo*,                     /* First argument to compare function */
   7569   BtCursor *pCursor                    /* Space to write cursor structure */
   7570 );
   7571 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
   7572 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
   7573 
   7574 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
   7575 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   7576   BtCursor*,
   7577   UnpackedRecord *pUnKey,
   7578   i64 intKey,
   7579   int bias,
   7580   int *pRes
   7581 );
   7582 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
   7583 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
   7584 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
   7585                                   const void *pData, int nData,
   7586                                   int nZero, int bias, int seekResult);
   7587 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
   7588 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
   7589 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
   7590 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
   7591 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
   7592 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   7593 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   7594 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
   7595 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
   7596 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   7597 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   7598 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
   7599 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
   7600 
   7601 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   7602 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
   7603 
   7604 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   7605 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
   7606 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
   7607 
   7608 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
   7609 
   7610 #ifndef NDEBUG
   7611 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
   7612 #endif
   7613 
   7614 #ifndef SQLITE_OMIT_BTREECOUNT
   7615 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
   7616 #endif
   7617 
   7618 #ifdef SQLITE_TEST
   7619 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
   7620 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
   7621 #endif
   7622 
   7623 #ifndef SQLITE_OMIT_WAL
   7624 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
   7625 #endif
   7626 
   7627 /*
   7628 ** If we are not using shared cache, then there is no need to
   7629 ** use mutexes to access the BtShared structures.  So make the
   7630 ** Enter and Leave procedures no-ops.
   7631 */
   7632 #ifndef SQLITE_OMIT_SHARED_CACHE
   7633 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
   7634 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
   7635 #else
   7636 # define sqlite3BtreeEnter(X)
   7637 # define sqlite3BtreeEnterAll(X)
   7638 #endif
   7639 
   7640 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
   7641 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
   7642 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
   7643 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
   7644 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
   7645 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
   7646 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
   7647 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
   7648 #ifndef NDEBUG
   7649   /* These routines are used inside assert() statements only. */
   7650 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
   7651 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
   7652 #endif
   7653 #else
   7654 
   7655 # define sqlite3BtreeLeave(X)
   7656 # define sqlite3BtreeEnterCursor(X)
   7657 # define sqlite3BtreeLeaveCursor(X)
   7658 # define sqlite3BtreeLeaveAll(X)
   7659 # define sqlite3BtreeMutexArrayEnter(X)
   7660 # define sqlite3BtreeMutexArrayLeave(X)
   7661 # define sqlite3BtreeMutexArrayInsert(X,Y)
   7662 
   7663 # define sqlite3BtreeHoldsMutex(X) 1
   7664 # define sqlite3BtreeHoldsAllMutexes(X) 1
   7665 #endif
   7666 
   7667 
   7668 #endif /* _BTREE_H_ */
   7669 
   7670 /************** End of btree.h ***********************************************/
   7671 /************** Continuing where we left off in sqliteInt.h ******************/
   7672 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
   7673 /************** Begin file vdbe.h ********************************************/
   7674 /*
   7675 ** 2001 September 15
   7676 **
   7677 ** The author disclaims copyright to this source code.  In place of
   7678 ** a legal notice, here is a blessing:
   7679 **
   7680 **    May you do good and not evil.
   7681 **    May you find forgiveness for yourself and forgive others.
   7682 **    May you share freely, never taking more than you give.
   7683 **
   7684 *************************************************************************
   7685 ** Header file for the Virtual DataBase Engine (VDBE)
   7686 **
   7687 ** This header defines the interface to the virtual database engine
   7688 ** or VDBE.  The VDBE implements an abstract machine that runs a
   7689 ** simple program to access and modify the underlying database.
   7690 */
   7691 #ifndef _SQLITE_VDBE_H_
   7692 #define _SQLITE_VDBE_H_
   7693 
   7694 /*
   7695 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
   7696 ** in the source file sqliteVdbe.c are allowed to see the insides
   7697 ** of this structure.
   7698 */
   7699 typedef struct Vdbe Vdbe;
   7700 
   7701 /*
   7702 ** The names of the following types declared in vdbeInt.h are required
   7703 ** for the VdbeOp definition.
   7704 */
   7705 typedef struct VdbeFunc VdbeFunc;
   7706 typedef struct Mem Mem;
   7707 typedef struct SubProgram SubProgram;
   7708 
   7709 /*
   7710 ** A single instruction of the virtual machine has an opcode
   7711 ** and as many as three operands.  The instruction is recorded
   7712 ** as an instance of the following structure:
   7713 */
   7714 struct VdbeOp {
   7715   u8 opcode;          /* What operation to perform */
   7716   signed char p4type; /* One of the P4_xxx constants for p4 */
   7717   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
   7718   u8 p5;              /* Fifth parameter is an unsigned character */
   7719   int p1;             /* First operand */
   7720   int p2;             /* Second parameter (often the jump destination) */
   7721   int p3;             /* The third parameter */
   7722   union {             /* fourth parameter */
   7723     int i;                 /* Integer value if p4type==P4_INT32 */
   7724     void *p;               /* Generic pointer */
   7725     char *z;               /* Pointer to data for string (char array) types */
   7726     i64 *pI64;             /* Used when p4type is P4_INT64 */
   7727     double *pReal;         /* Used when p4type is P4_REAL */
   7728     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
   7729     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
   7730     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
   7731     Mem *pMem;             /* Used when p4type is P4_MEM */
   7732     VTable *pVtab;         /* Used when p4type is P4_VTAB */
   7733     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
   7734     int *ai;               /* Used when p4type is P4_INTARRAY */
   7735     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
   7736   } p4;
   7737 #ifdef SQLITE_DEBUG
   7738   char *zComment;          /* Comment to improve readability */
   7739 #endif
   7740 #ifdef VDBE_PROFILE
   7741   int cnt;                 /* Number of times this instruction was executed */
   7742   u64 cycles;              /* Total time spent executing this instruction */
   7743 #endif
   7744 };
   7745 typedef struct VdbeOp VdbeOp;
   7746 
   7747 
   7748 /*
   7749 ** A sub-routine used to implement a trigger program.
   7750 */
   7751 struct SubProgram {
   7752   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
   7753   int nOp;                      /* Elements in aOp[] */
   7754   int nMem;                     /* Number of memory cells required */
   7755   int nCsr;                     /* Number of cursors required */
   7756   void *token;                  /* id that may be used to recursive triggers */
   7757   SubProgram *pNext;            /* Next sub-program already visited */
   7758 };
   7759 
   7760 /*
   7761 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
   7762 ** it takes up less space.
   7763 */
   7764 struct VdbeOpList {
   7765   u8 opcode;          /* What operation to perform */
   7766   signed char p1;     /* First operand */
   7767   signed char p2;     /* Second parameter (often the jump destination) */
   7768   signed char p3;     /* Third parameter */
   7769 };
   7770 typedef struct VdbeOpList VdbeOpList;
   7771 
   7772 /*
   7773 ** Allowed values of VdbeOp.p4type
   7774 */
   7775 #define P4_NOTUSED    0   /* The P4 parameter is not used */
   7776 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
   7777 #define P4_STATIC   (-2)  /* Pointer to a static string */
   7778 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
   7779 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
   7780 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
   7781 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
   7782 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
   7783 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
   7784 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
   7785 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
   7786 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
   7787 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
   7788 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
   7789 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
   7790 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
   7791 
   7792 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
   7793 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
   7794 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
   7795 ** gets freed when the Vdbe is finalized so it still should be obtained
   7796 ** from a single sqliteMalloc().  But no copy is made and the calling
   7797 ** function should *not* try to free the KeyInfo.
   7798 */
   7799 #define P4_KEYINFO_HANDOFF (-16)
   7800 #define P4_KEYINFO_STATIC  (-17)
   7801 
   7802 /*
   7803 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
   7804 ** number of columns of data returned by the statement.
   7805 */
   7806 #define COLNAME_NAME     0
   7807 #define COLNAME_DECLTYPE 1
   7808 #define COLNAME_DATABASE 2
   7809 #define COLNAME_TABLE    3
   7810 #define COLNAME_COLUMN   4
   7811 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   7812 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
   7813 #else
   7814 # ifdef SQLITE_OMIT_DECLTYPE
   7815 #   define COLNAME_N      1      /* Store only the name */
   7816 # else
   7817 #   define COLNAME_N      2      /* Store the name and decltype */
   7818 # endif
   7819 #endif
   7820 
   7821 /*
   7822 ** The following macro converts a relative address in the p2 field
   7823 ** of a VdbeOp structure into a negative number so that
   7824 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
   7825 ** the macro again restores the address.
   7826 */
   7827 #define ADDR(X)  (-1-(X))
   7828 
   7829 /*
   7830 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
   7831 ** header file that defines a number for each opcode used by the VDBE.
   7832 */
   7833 /************** Include opcodes.h in the middle of vdbe.h ********************/
   7834 /************** Begin file opcodes.h *****************************************/
   7835 /* Automatically generated.  Do not edit */
   7836 /* See the mkopcodeh.awk script for details */
   7837 #define OP_Goto                                 1
   7838 #define OP_Gosub                                2
   7839 #define OP_Return                               3
   7840 #define OP_Yield                                4
   7841 #define OP_HaltIfNull                           5
   7842 #define OP_Halt                                 6
   7843 #define OP_Integer                              7
   7844 #define OP_Int64                                8
   7845 #define OP_Real                               130   /* same as TK_FLOAT    */
   7846 #define OP_String8                             94   /* same as TK_STRING   */
   7847 #define OP_String                               9
   7848 #define OP_Null                                10
   7849 #define OP_Blob                                11
   7850 #define OP_Variable                            12
   7851 #define OP_Move                                13
   7852 #define OP_Copy                                14
   7853 #define OP_SCopy                               15
   7854 #define OP_ResultRow                           16
   7855 #define OP_Concat                              91   /* same as TK_CONCAT   */
   7856 #define OP_Add                                 86   /* same as TK_PLUS     */
   7857 #define OP_Subtract                            87   /* same as TK_MINUS    */
   7858 #define OP_Multiply                            88   /* same as TK_STAR     */
   7859 #define OP_Divide                              89   /* same as TK_SLASH    */
   7860 #define OP_Remainder                           90   /* same as TK_REM      */
   7861 #define OP_CollSeq                             17
   7862 #define OP_Function                            18
   7863 #define OP_BitAnd                              82   /* same as TK_BITAND   */
   7864 #define OP_BitOr                               83   /* same as TK_BITOR    */
   7865 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
   7866 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
   7867 #define OP_AddImm                              20
   7868 #define OP_MustBeInt                           21
   7869 #define OP_RealAffinity                        22
   7870 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
   7871 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
   7872 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
   7873 #define OP_ToInt                              144   /* same as TK_TO_INT   */
   7874 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
   7875 #define OP_Eq                                  76   /* same as TK_EQ       */
   7876 #define OP_Ne                                  75   /* same as TK_NE       */
   7877 #define OP_Lt                                  79   /* same as TK_LT       */
   7878 #define OP_Le                                  78   /* same as TK_LE       */
   7879 #define OP_Gt                                  77   /* same as TK_GT       */
   7880 #define OP_Ge                                  80   /* same as TK_GE       */
   7881 #define OP_Permutation                         23
   7882 #define OP_Compare                             24
   7883 #define OP_Jump                                25
   7884 #define OP_And                                 69   /* same as TK_AND      */
   7885 #define OP_Or                                  68   /* same as TK_OR       */
   7886 #define OP_Not                                 19   /* same as TK_NOT      */
   7887 #define OP_BitNot                              93   /* same as TK_BITNOT   */
   7888 #define OP_If                                  26
   7889 #define OP_IfNot                               27
   7890 #define OP_IsNull                              73   /* same as TK_ISNULL   */
   7891 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
   7892 #define OP_Column                              28
   7893 #define OP_Affinity                            29
   7894 #define OP_MakeRecord                          30
   7895 #define OP_Count                               31
   7896 #define OP_Savepoint                           32
   7897 #define OP_AutoCommit                          33
   7898 #define OP_Transaction                         34
   7899 #define OP_ReadCookie                          35
   7900 #define OP_SetCookie                           36
   7901 #define OP_VerifyCookie                        37
   7902 #define OP_OpenRead                            38
   7903 #define OP_OpenWrite                           39
   7904 #define OP_OpenAutoindex                       40
   7905 #define OP_OpenEphemeral                       41
   7906 #define OP_OpenPseudo                          42
   7907 #define OP_Close                               43
   7908 #define OP_SeekLt                              44
   7909 #define OP_SeekLe                              45
   7910 #define OP_SeekGe                              46
   7911 #define OP_SeekGt                              47
   7912 #define OP_Seek                                48
   7913 #define OP_NotFound                            49
   7914 #define OP_Found                               50
   7915 #define OP_IsUnique                            51
   7916 #define OP_NotExists                           52
   7917 #define OP_Sequence                            53
   7918 #define OP_NewRowid                            54
   7919 #define OP_Insert                              55
   7920 #define OP_InsertInt                           56
   7921 #define OP_Delete                              57
   7922 #define OP_ResetCount                          58
   7923 #define OP_RowKey                              59
   7924 #define OP_RowData                             60
   7925 #define OP_Rowid                               61
   7926 #define OP_NullRow                             62
   7927 #define OP_Last                                63
   7928 #define OP_Sort                                64
   7929 #define OP_Rewind                              65
   7930 #define OP_Prev                                66
   7931 #define OP_Next                                67
   7932 #define OP_IdxInsert                           70
   7933 #define OP_IdxDelete                           71
   7934 #define OP_IdxRowid                            72
   7935 #define OP_IdxLT                               81
   7936 #define OP_IdxGE                               92
   7937 #define OP_Destroy                             95
   7938 #define OP_Clear                               96
   7939 #define OP_CreateIndex                         97
   7940 #define OP_CreateTable                         98
   7941 #define OP_ParseSchema                         99
   7942 #define OP_LoadAnalysis                       100
   7943 #define OP_DropTable                          101
   7944 #define OP_DropIndex                          102
   7945 #define OP_DropTrigger                        103
   7946 #define OP_IntegrityCk                        104
   7947 #define OP_RowSetAdd                          105
   7948 #define OP_RowSetRead                         106
   7949 #define OP_RowSetTest                         107
   7950 #define OP_Program                            108
   7951 #define OP_Param                              109
   7952 #define OP_FkCounter                          110
   7953 #define OP_FkIfZero                           111
   7954 #define OP_MemMax                             112
   7955 #define OP_IfPos                              113
   7956 #define OP_IfNeg                              114
   7957 #define OP_IfZero                             115
   7958 #define OP_AggStep                            116
   7959 #define OP_AggFinal                           117
   7960 #define OP_Checkpoint                         118
   7961 #define OP_JournalMode                        119
   7962 #define OP_Vacuum                             120
   7963 #define OP_IncrVacuum                         121
   7964 #define OP_Expire                             122
   7965 #define OP_TableLock                          123
   7966 #define OP_VBegin                             124
   7967 #define OP_VCreate                            125
   7968 #define OP_VDestroy                           126
   7969 #define OP_VOpen                              127
   7970 #define OP_VFilter                            128
   7971 #define OP_VColumn                            129
   7972 #define OP_VNext                              131
   7973 #define OP_VRename                            132
   7974 #define OP_VUpdate                            133
   7975 #define OP_Pagecount                          134
   7976 #define OP_MaxPgcnt                           135
   7977 #define OP_Trace                              136
   7978 #define OP_Noop                               137
   7979 #define OP_Explain                            138
   7980 
   7981 /* The following opcode values are never used */
   7982 #define OP_NotUsed_139                        139
   7983 #define OP_NotUsed_140                        140
   7984 
   7985 
   7986 /* Properties such as "out2" or "jump" that are specified in
   7987 ** comments following the "case" for each opcode in the vdbe.c
   7988 ** are encoded into bitvectors as follows:
   7989 */
   7990 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
   7991 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
   7992 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
   7993 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
   7994 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
   7995 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
   7996 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
   7997 #define OPFLG_INITIALIZER {\
   7998 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
   7999 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
   8000 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
   8001 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
   8002 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
   8003 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
   8004 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
   8005 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
   8006 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
   8007 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
   8008 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
   8009 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
   8010 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
   8011 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
   8012 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
   8013 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
   8014 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
   8015 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
   8016 /* 144 */ 0x04, 0x04,}
   8017 
   8018 /************** End of opcodes.h *********************************************/
   8019 /************** Continuing where we left off in vdbe.h ***********************/
   8020 
   8021 /*
   8022 ** Prototypes for the VDBE interface.  See comments on the implementation
   8023 ** for a description of what each of these routines does.
   8024 */
   8025 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
   8026 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
   8027 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
   8028 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   8029 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   8030 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   8031 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   8032 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
   8033 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
   8034 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
   8035 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
   8036 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   8037 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
   8038 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
   8039 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
   8040 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
   8041 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   8042 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
   8043 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
   8044 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
   8045 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
   8046 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
   8047 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
   8048 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
   8049 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
   8050 #ifdef SQLITE_DEBUG
   8051 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
   8052 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
   8053 #endif
   8054 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
   8055 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
   8056 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
   8057 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   8058 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
   8059 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
   8060 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   8061 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   8062 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   8063 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
   8064 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
   8065 #ifndef SQLITE_OMIT_TRACE
   8066 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   8067 #endif
   8068 
   8069 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
   8070 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
   8071 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
   8072 
   8073 #ifndef SQLITE_OMIT_TRIGGER
   8074 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
   8075 #endif
   8076 
   8077 
   8078 #ifndef NDEBUG
   8079 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
   8080 # define VdbeComment(X)  sqlite3VdbeComment X
   8081 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
   8082 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
   8083 #else
   8084 # define VdbeComment(X)
   8085 # define VdbeNoopComment(X)
   8086 #endif
   8087 
   8088 #endif
   8089 
   8090 /************** End of vdbe.h ************************************************/
   8091 /************** Continuing where we left off in sqliteInt.h ******************/
   8092 /************** Include pager.h in the middle of sqliteInt.h *****************/
   8093 /************** Begin file pager.h *******************************************/
   8094 /*
   8095 ** 2001 September 15
   8096 **
   8097 ** The author disclaims copyright to this source code.  In place of
   8098 ** a legal notice, here is a blessing:
   8099 **
   8100 **    May you do good and not evil.
   8101 **    May you find forgiveness for yourself and forgive others.
   8102 **    May you share freely, never taking more than you give.
   8103 **
   8104 *************************************************************************
   8105 ** This header file defines the interface that the sqlite page cache
   8106 ** subsystem.  The page cache subsystem reads and writes a file a page
   8107 ** at a time and provides a journal for rollback.
   8108 */
   8109 
   8110 #ifndef _PAGER_H_
   8111 #define _PAGER_H_
   8112 
   8113 /*
   8114 ** Default maximum size for persistent journal files. A negative
   8115 ** value means no limit. This value may be overridden using the
   8116 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
   8117 */
   8118 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
   8119   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
   8120 #endif
   8121 
   8122 /*
   8123 ** The type used to represent a page number.  The first page in a file
   8124 ** is called page 1.  0 is used to represent "not a page".
   8125 */
   8126 typedef u32 Pgno;
   8127 
   8128 /*
   8129 ** Each open file is managed by a separate instance of the "Pager" structure.
   8130 */
   8131 typedef struct Pager Pager;
   8132 
   8133 /*
   8134 ** Handle type for pages.
   8135 */
   8136 typedef struct PgHdr DbPage;
   8137 
   8138 /*
   8139 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
   8140 ** reserved for working around a windows/posix incompatibility). It is
   8141 ** used in the journal to signify that the remainder of the journal file
   8142 ** is devoted to storing a master journal name - there are no more pages to
   8143 ** roll back. See comments for function writeMasterJournal() in pager.c
   8144 ** for details.
   8145 */
   8146 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
   8147 
   8148 /*
   8149 ** Allowed values for the flags parameter to sqlite3PagerOpen().
   8150 **
   8151 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
   8152 */
   8153 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
   8154 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
   8155 #define PAGER_MEMORY        0x0004    /* In-memory database */
   8156 
   8157 /*
   8158 ** Valid values for the second argument to sqlite3PagerLockingMode().
   8159 */
   8160 #define PAGER_LOCKINGMODE_QUERY      -1
   8161 #define PAGER_LOCKINGMODE_NORMAL      0
   8162 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
   8163 
   8164 /*
   8165 ** Numeric constants that encode the journalmode.
   8166 */
   8167 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
   8168 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
   8169 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
   8170 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
   8171 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
   8172 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
   8173 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
   8174 
   8175 /*
   8176 ** The remainder of this file contains the declarations of the functions
   8177 ** that make up the Pager sub-system API. See source code comments for
   8178 ** a detailed description of each routine.
   8179 */
   8180 
   8181 /* Open and close a Pager connection. */
   8182 SQLITE_PRIVATE int sqlite3PagerOpen(
   8183   sqlite3_vfs*,
   8184   Pager **ppPager,
   8185   const char*,
   8186   int,
   8187   int,
   8188   int,
   8189   void(*)(DbPage*)
   8190 );
   8191 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
   8192 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   8193 
   8194 /* Functions used to configure a Pager object. */
   8195 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   8196 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
   8197 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
   8198 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
   8199 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
   8200 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
   8201 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
   8202 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
   8203 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
   8204 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   8205 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
   8206 
   8207 /* Functions used to obtain and release page references. */
   8208 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
   8209 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
   8210 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
   8211 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
   8212 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
   8213 
   8214 /* Operations on page references. */
   8215 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
   8216 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
   8217 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
   8218 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
   8219 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
   8220 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
   8221 
   8222 /* Functions used to manage pager transactions and savepoints. */
   8223 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
   8224 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
   8225 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
   8226 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
   8227 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
   8228 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
   8229 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
   8230 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
   8231 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
   8232 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
   8233 
   8234 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
   8235 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
   8236 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
   8237 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
   8238 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
   8239 
   8240 /* Functions used to query pager state and configuration. */
   8241 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
   8242 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
   8243 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
   8244 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
   8245 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
   8246 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
   8247 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
   8248 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
   8249 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
   8250 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
   8251 
   8252 /* Functions used to truncate the database file. */
   8253 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
   8254 
   8255 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
   8256 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
   8257 #endif
   8258 
   8259 /* Functions to support testing and debugging. */
   8260 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   8261 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
   8262 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
   8263 #endif
   8264 #ifdef SQLITE_TEST
   8265 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
   8266 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
   8267   void disable_simulated_io_errors(void);
   8268   void enable_simulated_io_errors(void);
   8269 #else
   8270 # define disable_simulated_io_errors()
   8271 # define enable_simulated_io_errors()
   8272 #endif
   8273 
   8274 #endif /* _PAGER_H_ */
   8275 
   8276 /************** End of pager.h ***********************************************/
   8277 /************** Continuing where we left off in sqliteInt.h ******************/
   8278 /************** Include pcache.h in the middle of sqliteInt.h ****************/
   8279 /************** Begin file pcache.h ******************************************/
   8280 /*
   8281 ** 2008 August 05
   8282 **
   8283 ** The author disclaims copyright to this source code.  In place of
   8284 ** a legal notice, here is a blessing:
   8285 **
   8286 **    May you do good and not evil.
   8287 **    May you find forgiveness for yourself and forgive others.
   8288 **    May you share freely, never taking more than you give.
   8289 **
   8290 *************************************************************************
   8291 ** This header file defines the interface that the sqlite page cache
   8292 ** subsystem.
   8293 */
   8294 
   8295 #ifndef _PCACHE_H_
   8296 
   8297 typedef struct PgHdr PgHdr;
   8298 typedef struct PCache PCache;
   8299 
   8300 /*
   8301 ** Every page in the cache is controlled by an instance of the following
   8302 ** structure.
   8303 */
   8304 struct PgHdr {
   8305   void *pData;                   /* Content of this page */
   8306   void *pExtra;                  /* Extra content */
   8307   PgHdr *pDirty;                 /* Transient list of dirty pages */
   8308   Pgno pgno;                     /* Page number for this page */
   8309   Pager *pPager;                 /* The pager this page is part of */
   8310 #ifdef SQLITE_CHECK_PAGES
   8311   u32 pageHash;                  /* Hash of page content */
   8312 #endif
   8313   u16 flags;                     /* PGHDR flags defined below */
   8314 
   8315   /**********************************************************************
   8316   ** Elements above are public.  All that follows is private to pcache.c
   8317   ** and should not be accessed by other modules.
   8318   */
   8319   i16 nRef;                      /* Number of users of this page */
   8320   PCache *pCache;                /* Cache that owns this page */
   8321 
   8322   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
   8323   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
   8324 };
   8325 
   8326 /* Bit values for PgHdr.flags */
   8327 #define PGHDR_DIRTY             0x002  /* Page has changed */
   8328 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
   8329                                        ** writing this page to the database */
   8330 #define PGHDR_NEED_READ         0x008  /* Content is unread */
   8331 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
   8332 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
   8333 
   8334 /* Initialize and shutdown the page cache subsystem */
   8335 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
   8336 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
   8337 
   8338 /* Page cache buffer management:
   8339 ** These routines implement SQLITE_CONFIG_PAGECACHE.
   8340 */
   8341 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
   8342 
   8343 /* Create a new pager cache.
   8344 ** Under memory stress, invoke xStress to try to make pages clean.
   8345 ** Only clean and unpinned pages can be reclaimed.
   8346 */
   8347 SQLITE_PRIVATE void sqlite3PcacheOpen(
   8348   int szPage,                    /* Size of every page */
   8349   int szExtra,                   /* Extra space associated with each page */
   8350   int bPurgeable,                /* True if pages are on backing store */
   8351   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
   8352   void *pStress,                 /* Argument to xStress */
   8353   PCache *pToInit                /* Preallocated space for the PCache */
   8354 );
   8355 
   8356 /* Modify the page-size after the cache has been created. */
   8357 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
   8358 
   8359 /* Return the size in bytes of a PCache object.  Used to preallocate
   8360 ** storage space.
   8361 */
   8362 SQLITE_PRIVATE int sqlite3PcacheSize(void);
   8363 
   8364 /* One release per successful fetch.  Page is pinned until released.
   8365 ** Reference counted.
   8366 */
   8367 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
   8368 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
   8369 
   8370 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
   8371 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
   8372 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
   8373 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
   8374 
   8375 /* Change a page number.  Used by incr-vacuum. */
   8376 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
   8377 
   8378 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
   8379 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
   8380 
   8381 /* Get a list of all dirty pages in the cache, sorted by page number */
   8382 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
   8383 
   8384 /* Reset and close the cache object */
   8385 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
   8386 
   8387 /* Clear flags from pages of the page cache */
   8388 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
   8389 
   8390 /* Discard the contents of the cache */
   8391 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
   8392 
   8393 /* Return the total number of outstanding page references */
   8394 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
   8395 
   8396 /* Increment the reference count of an existing page */
   8397 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
   8398 
   8399 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
   8400 
   8401 /* Return the total number of pages stored in the cache */
   8402 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
   8403 
   8404 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   8405 /* Iterate through all dirty pages currently stored in the cache. This
   8406 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
   8407 ** library is built.
   8408 */
   8409 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
   8410 #endif
   8411 
   8412 /* Set and get the suggested cache-size for the specified pager-cache.
   8413 **
   8414 ** If no global maximum is configured, then the system attempts to limit
   8415 ** the total number of pages cached by purgeable pager-caches to the sum
   8416 ** of the suggested cache-sizes.
   8417 */
   8418 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
   8419 #ifdef SQLITE_TEST
   8420 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
   8421 #endif
   8422 
   8423 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   8424 /* Try to return memory used by the pcache module to the main memory heap */
   8425 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
   8426 #endif
   8427 
   8428 #ifdef SQLITE_TEST
   8429 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
   8430 #endif
   8431 
   8432 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
   8433 
   8434 #endif /* _PCACHE_H_ */
   8435 
   8436 /************** End of pcache.h **********************************************/
   8437 /************** Continuing where we left off in sqliteInt.h ******************/
   8438 
   8439 /************** Include os.h in the middle of sqliteInt.h ********************/
   8440 /************** Begin file os.h **********************************************/
   8441 /*
   8442 ** 2001 September 16
   8443 **
   8444 ** The author disclaims copyright to this source code.  In place of
   8445 ** a legal notice, here is a blessing:
   8446 **
   8447 **    May you do good and not evil.
   8448 **    May you find forgiveness for yourself and forgive others.
   8449 **    May you share freely, never taking more than you give.
   8450 **
   8451 ******************************************************************************
   8452 **
   8453 ** This header file (together with is companion C source-code file
   8454 ** "os.c") attempt to abstract the underlying operating system so that
   8455 ** the SQLite library will work on both POSIX and windows systems.
   8456 **
   8457 ** This header file is #include-ed by sqliteInt.h and thus ends up
   8458 ** being included by every source file.
   8459 */
   8460 #ifndef _SQLITE_OS_H_
   8461 #define _SQLITE_OS_H_
   8462 
   8463 /*
   8464 ** Figure out if we are dealing with Unix, Windows, or some other
   8465 ** operating system.  After the following block of preprocess macros,
   8466 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
   8467 ** will defined to either 1 or 0.  One of the four will be 1.  The other
   8468 ** three will be 0.
   8469 */
   8470 #if defined(SQLITE_OS_OTHER)
   8471 # if SQLITE_OS_OTHER==1
   8472 #   undef SQLITE_OS_UNIX
   8473 #   define SQLITE_OS_UNIX 0
   8474 #   undef SQLITE_OS_WIN
   8475 #   define SQLITE_OS_WIN 0
   8476 #   undef SQLITE_OS_OS2
   8477 #   define SQLITE_OS_OS2 0
   8478 # else
   8479 #   undef SQLITE_OS_OTHER
   8480 # endif
   8481 #endif
   8482 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
   8483 # define SQLITE_OS_OTHER 0
   8484 # ifndef SQLITE_OS_WIN
   8485 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
   8486 #     define SQLITE_OS_WIN 1
   8487 #     define SQLITE_OS_UNIX 0
   8488 #     define SQLITE_OS_OS2 0
   8489 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
   8490 #     define SQLITE_OS_WIN 0
   8491 #     define SQLITE_OS_UNIX 0
   8492 #     define SQLITE_OS_OS2 1
   8493 #   else
   8494 #     define SQLITE_OS_WIN 0
   8495 #     define SQLITE_OS_UNIX 1
   8496 #     define SQLITE_OS_OS2 0
   8497 #  endif
   8498 # else
   8499 #  define SQLITE_OS_UNIX 0
   8500 #  define SQLITE_OS_OS2 0
   8501 # endif
   8502 #else
   8503 # ifndef SQLITE_OS_WIN
   8504 #  define SQLITE_OS_WIN 0
   8505 # endif
   8506 #endif
   8507 
   8508 /*
   8509 ** Determine if we are dealing with WindowsCE - which has a much
   8510 ** reduced API.
   8511 */
   8512 #if defined(_WIN32_WCE)
   8513 # define SQLITE_OS_WINCE 1
   8514 #else
   8515 # define SQLITE_OS_WINCE 0
   8516 #endif
   8517 
   8518 
   8519 /*
   8520 ** Define the maximum size of a temporary filename
   8521 */
   8522 #if SQLITE_OS_WIN
   8523 # include <windows.h>
   8524 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
   8525 #elif SQLITE_OS_OS2
   8526 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
   8527 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
   8528 # endif
   8529 # define INCL_DOSDATETIME
   8530 # define INCL_DOSFILEMGR
   8531 # define INCL_DOSERRORS
   8532 # define INCL_DOSMISC
   8533 # define INCL_DOSPROCESS
   8534 # define INCL_DOSMODULEMGR
   8535 # define INCL_DOSSEMAPHORES
   8536 # include <os2.h>
   8537 # include <uconv.h>
   8538 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
   8539 #else
   8540 # define SQLITE_TEMPNAME_SIZE 200
   8541 #endif
   8542 
   8543 /* If the SET_FULLSYNC macro is not defined above, then make it
   8544 ** a no-op
   8545 */
   8546 #ifndef SET_FULLSYNC
   8547 # define SET_FULLSYNC(x,y)
   8548 #endif
   8549 
   8550 /*
   8551 ** The default size of a disk sector
   8552 */
   8553 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   8554 # define SQLITE_DEFAULT_SECTOR_SIZE 512
   8555 #endif
   8556 
   8557 /*
   8558 ** Temporary files are named starting with this prefix followed by 16 random
   8559 ** alphanumeric characters, and no file extension. They are stored in the
   8560 ** OS's standard temporary file directory, and are deleted prior to exit.
   8561 ** If sqlite is being embedded in another program, you may wish to change the
   8562 ** prefix to reflect your program's name, so that if your program exits
   8563 ** prematurely, old temporary files can be easily identified. This can be done
   8564 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
   8565 **
   8566 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
   8567 ** Mcafee started using SQLite in their anti-virus product and it
   8568 ** started putting files with the "sqlite" name in the c:/temp folder.
   8569 ** This annoyed many windows users.  Those users would then do a
   8570 ** Google search for "sqlite", find the telephone numbers of the
   8571 ** developers and call to wake them up at night and complain.
   8572 ** For this reason, the default name prefix is changed to be "sqlite"
   8573 ** spelled backwards.  So the temp files are still identified, but
   8574 ** anybody smart enough to figure out the code is also likely smart
   8575 ** enough to know that calling the developer will not help get rid
   8576 ** of the file.
   8577 */
   8578 #ifndef SQLITE_TEMP_FILE_PREFIX
   8579 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
   8580 #endif
   8581 
   8582 /*
   8583 ** The following values may be passed as the second argument to
   8584 ** sqlite3OsLock(). The various locks exhibit the following semantics:
   8585 **
   8586 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
   8587 ** RESERVED:  A single process may hold a RESERVED lock on a file at
   8588 **            any time. Other processes may hold and obtain new SHARED locks.
   8589 ** PENDING:   A single process may hold a PENDING lock on a file at
   8590 **            any one time. Existing SHARED locks may persist, but no new
   8591 **            SHARED locks may be obtained by other processes.
   8592 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
   8593 **
   8594 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
   8595 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
   8596 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
   8597 ** sqlite3OsLock().
   8598 */
   8599 #define NO_LOCK         0
   8600 #define SHARED_LOCK     1
   8601 #define RESERVED_LOCK   2
   8602 #define PENDING_LOCK    3
   8603 #define EXCLUSIVE_LOCK  4
   8604 
   8605 /*
   8606 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
   8607 **
   8608 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
   8609 ** those functions are not available.  So we use only LockFile() and
   8610 ** UnlockFile().
   8611 **
   8612 ** LockFile() prevents not just writing but also reading by other processes.
   8613 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
   8614 ** byte out of a specific range of bytes. The lock byte is obtained at
   8615 ** random so two separate readers can probably access the file at the
   8616 ** same time, unless they are unlucky and choose the same lock byte.
   8617 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
   8618 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
   8619 ** a single byte of the file that is designated as the reserved lock byte.
   8620 ** A PENDING_LOCK is obtained by locking a designated byte different from
   8621 ** the RESERVED_LOCK byte.
   8622 **
   8623 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
   8624 ** which means we can use reader/writer locks.  When reader/writer locks
   8625 ** are used, the lock is placed on the same range of bytes that is used
   8626 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
   8627 ** will support two or more Win95 readers or two or more WinNT readers.
   8628 ** But a single Win95 reader will lock out all WinNT readers and a single
   8629 ** WinNT reader will lock out all other Win95 readers.
   8630 **
   8631 ** The following #defines specify the range of bytes used for locking.
   8632 ** SHARED_SIZE is the number of bytes available in the pool from which
   8633 ** a random byte is selected for a shared lock.  The pool of bytes for
   8634 ** shared locks begins at SHARED_FIRST.
   8635 **
   8636 ** The same locking strategy and
   8637 ** byte ranges are used for Unix.  This leaves open the possiblity of having
   8638 ** clients on win95, winNT, and unix all talking to the same shared file
   8639 ** and all locking correctly.  To do so would require that samba (or whatever
   8640 ** tool is being used for file sharing) implements locks correctly between
   8641 ** windows and unix.  I'm guessing that isn't likely to happen, but by
   8642 ** using the same locking range we are at least open to the possibility.
   8643 **
   8644 ** Locking in windows is manditory.  For this reason, we cannot store
   8645 ** actual data in the bytes used for locking.  The pager never allocates
   8646 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
   8647 ** that all locks will fit on a single page even at the minimum page size.
   8648 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
   8649 ** is set high so that we don't have to allocate an unused page except
   8650 ** for very large databases.  But one should test the page skipping logic
   8651 ** by setting PENDING_BYTE low and running the entire regression suite.
   8652 **
   8653 ** Changing the value of PENDING_BYTE results in a subtly incompatible
   8654 ** file format.  Depending on how it is changed, you might not notice
   8655 ** the incompatibility right away, even running a full regression test.
   8656 ** The default location of PENDING_BYTE is the first byte past the
   8657 ** 1GB boundary.
   8658 **
   8659 */
   8660 #ifdef SQLITE_OMIT_WSD
   8661 # define PENDING_BYTE     (0x40000000)
   8662 #else
   8663 # define PENDING_BYTE      sqlite3PendingByte
   8664 #endif
   8665 #define RESERVED_BYTE     (PENDING_BYTE+1)
   8666 #define SHARED_FIRST      (PENDING_BYTE+2)
   8667 #define SHARED_SIZE       510
   8668 
   8669 /*
   8670 ** Wrapper around OS specific sqlite3_os_init() function.
   8671 */
   8672 SQLITE_PRIVATE int sqlite3OsInit(void);
   8673 
   8674 /*
   8675 ** Functions for accessing sqlite3_file methods
   8676 */
   8677 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
   8678 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
   8679 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
   8680 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
   8681 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
   8682 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
   8683 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
   8684 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
   8685 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
   8686 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
   8687 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
   8688 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
   8689 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
   8690 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
   8691 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
   8692 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
   8693 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
   8694 
   8695 /*
   8696 ** Functions for accessing sqlite3_vfs methods
   8697 */
   8698 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
   8699 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
   8700 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
   8701 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
   8702 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   8703 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
   8704 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
   8705 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
   8706 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
   8707 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   8708 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
   8709 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
   8710 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
   8711 
   8712 /*
   8713 ** Convenience functions for opening and closing files using
   8714 ** sqlite3_malloc() to obtain space for the file-handle structure.
   8715 */
   8716 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
   8717 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
   8718 
   8719 #endif /* _SQLITE_OS_H_ */
   8720 
   8721 /************** End of os.h **************************************************/
   8722 /************** Continuing where we left off in sqliteInt.h ******************/
   8723 /************** Include mutex.h in the middle of sqliteInt.h *****************/
   8724 /************** Begin file mutex.h *******************************************/
   8725 /*
   8726 ** 2007 August 28
   8727 **
   8728 ** The author disclaims copyright to this source code.  In place of
   8729 ** a legal notice, here is a blessing:
   8730 **
   8731 **    May you do good and not evil.
   8732 **    May you find forgiveness for yourself and forgive others.
   8733 **    May you share freely, never taking more than you give.
   8734 **
   8735 *************************************************************************
   8736 **
   8737 ** This file contains the common header for all mutex implementations.
   8738 ** The sqliteInt.h header #includes this file so that it is available
   8739 ** to all source files.  We break it out in an effort to keep the code
   8740 ** better organized.
   8741 **
   8742 ** NOTE:  source files should *not* #include this header file directly.
   8743 ** Source files should #include the sqliteInt.h file and let that file
   8744 ** include this one indirectly.
   8745 */
   8746 
   8747 
   8748 /*
   8749 ** Figure out what version of the code to use.  The choices are
   8750 **
   8751 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
   8752 **                             mutexes implemention cannot be overridden
   8753 **                             at start-time.
   8754 **
   8755 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
   8756 **                             mutual exclusion is provided.  But this
   8757 **                             implementation can be overridden at
   8758 **                             start-time.
   8759 **
   8760 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
   8761 **
   8762 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
   8763 **
   8764 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
   8765 */
   8766 #if !SQLITE_THREADSAFE
   8767 # define SQLITE_MUTEX_OMIT
   8768 #endif
   8769 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
   8770 #  if SQLITE_OS_UNIX
   8771 #    define SQLITE_MUTEX_PTHREADS
   8772 #  elif SQLITE_OS_WIN
   8773 #    define SQLITE_MUTEX_W32
   8774 #  elif SQLITE_OS_OS2
   8775 #    define SQLITE_MUTEX_OS2
   8776 #  else
   8777 #    define SQLITE_MUTEX_NOOP
   8778 #  endif
   8779 #endif
   8780 
   8781 #ifdef SQLITE_MUTEX_OMIT
   8782 /*
   8783 ** If this is a no-op implementation, implement everything as macros.
   8784 */
   8785 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
   8786 #define sqlite3_mutex_free(X)
   8787 #define sqlite3_mutex_enter(X)
   8788 #define sqlite3_mutex_try(X)      SQLITE_OK
   8789 #define sqlite3_mutex_leave(X)
   8790 #define sqlite3_mutex_held(X)     ((void)(X),1)
   8791 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
   8792 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
   8793 #define sqlite3MutexInit()        SQLITE_OK
   8794 #define sqlite3MutexEnd()
   8795 #endif /* defined(SQLITE_MUTEX_OMIT) */
   8796 
   8797 /************** End of mutex.h ***********************************************/
   8798 /************** Continuing where we left off in sqliteInt.h ******************/
   8799 
   8800 
   8801 /*
   8802 ** Each database file to be accessed by the system is an instance
   8803 ** of the following structure.  There are normally two of these structures
   8804 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
   8805 ** aDb[1] is the database file used to hold temporary tables.  Additional
   8806 ** databases may be attached.
   8807 */
   8808 struct Db {
   8809   char *zName;         /* Name of this database */
   8810   Btree *pBt;          /* The B*Tree structure for this database file */
   8811   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
   8812   u8 safety_level;     /* How aggressive at syncing data to disk */
   8813   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
   8814 };
   8815 
   8816 /*
   8817 ** An instance of the following structure stores a database schema.
   8818 */
   8819 struct Schema {
   8820   int schema_cookie;   /* Database schema version number for this file */
   8821   Hash tblHash;        /* All tables indexed by name */
   8822   Hash idxHash;        /* All (named) indices indexed by name */
   8823   Hash trigHash;       /* All triggers indexed by name */
   8824   Hash fkeyHash;       /* All foreign keys by referenced table name */
   8825   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
   8826   u8 file_format;      /* Schema format version for this file */
   8827   u8 enc;              /* Text encoding used by this database */
   8828   u16 flags;           /* Flags associated with this schema */
   8829   int cache_size;      /* Number of pages to use in the cache */
   8830 };
   8831 
   8832 /*
   8833 ** These macros can be used to test, set, or clear bits in the
   8834 ** Db.pSchema->flags field.
   8835 */
   8836 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
   8837 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
   8838 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
   8839 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
   8840 
   8841 /*
   8842 ** Allowed values for the DB.pSchema->flags field.
   8843 **
   8844 ** The DB_SchemaLoaded flag is set after the database schema has been
   8845 ** read into internal hash tables.
   8846 **
   8847 ** DB_UnresetViews means that one or more views have column names that
   8848 ** have been filled out.  If the schema changes, these column names might
   8849 ** changes and so the view will need to be reset.
   8850 */
   8851 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
   8852 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
   8853 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
   8854 
   8855 /*
   8856 ** The number of different kinds of things that can be limited
   8857 ** using the sqlite3_limit() interface.
   8858 */
   8859 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
   8860 
   8861 /*
   8862 ** Lookaside malloc is a set of fixed-size buffers that can be used
   8863 ** to satisfy small transient memory allocation requests for objects
   8864 ** associated with a particular database connection.  The use of
   8865 ** lookaside malloc provides a significant performance enhancement
   8866 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
   8867 ** SQL statements.
   8868 **
   8869 ** The Lookaside structure holds configuration information about the
   8870 ** lookaside malloc subsystem.  Each available memory allocation in
   8871 ** the lookaside subsystem is stored on a linked list of LookasideSlot
   8872 ** objects.
   8873 **
   8874 ** Lookaside allocations are only allowed for objects that are associated
   8875 ** with a particular database connection.  Hence, schema information cannot
   8876 ** be stored in lookaside because in shared cache mode the schema information
   8877 ** is shared by multiple database connections.  Therefore, while parsing
   8878 ** schema information, the Lookaside.bEnabled flag is cleared so that
   8879 ** lookaside allocations are not used to construct the schema objects.
   8880 */
   8881 struct Lookaside {
   8882   u16 sz;                 /* Size of each buffer in bytes */
   8883   u8 bEnabled;            /* False to disable new lookaside allocations */
   8884   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   8885   int nOut;               /* Number of buffers currently checked out */
   8886   int mxOut;              /* Highwater mark for nOut */
   8887   LookasideSlot *pFree;   /* List of available buffers */
   8888   void *pStart;           /* First byte of available memory space */
   8889   void *pEnd;             /* First byte past end of available space */
   8890 };
   8891 struct LookasideSlot {
   8892   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
   8893 };
   8894 
   8895 /*
   8896 ** A hash table for function definitions.
   8897 **
   8898 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
   8899 ** Collisions are on the FuncDef.pHash chain.
   8900 */
   8901 struct FuncDefHash {
   8902   FuncDef *a[23];       /* Hash table for functions */
   8903 };
   8904 
   8905 /*
   8906 ** Each database connection is an instance of the following structure.
   8907 **
   8908 ** The sqlite.lastRowid records the last insert rowid generated by an
   8909 ** insert statement.  Inserts on views do not affect its value.  Each
   8910 ** trigger has its own context, so that lastRowid can be updated inside
   8911 ** triggers as usual.  The previous value will be restored once the trigger
   8912 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
   8913 ** longer (since after version 2.8.12) reset to -1.
   8914 **
   8915 ** The sqlite.nChange does not count changes within triggers and keeps no
   8916 ** context.  It is reset at start of sqlite3_exec.
   8917 ** The sqlite.lsChange represents the number of changes made by the last
   8918 ** insert, update, or delete statement.  It remains constant throughout the
   8919 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
   8920 ** context stack just like lastRowid so that the count of changes
   8921 ** within a trigger is not seen outside the trigger.  Changes to views do not
   8922 ** affect the value of lsChange.
   8923 ** The sqlite.csChange keeps track of the number of current changes (since
   8924 ** the last statement) and is used to update sqlite_lsChange.
   8925 **
   8926 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
   8927 ** store the most recent error code and, if applicable, string. The
   8928 ** internal function sqlite3Error() is used to set these variables
   8929 ** consistently.
   8930 */
   8931 struct sqlite3 {
   8932   sqlite3_vfs *pVfs;            /* OS Interface */
   8933   int nDb;                      /* Number of backends currently in use */
   8934   Db *aDb;                      /* All backends */
   8935   int flags;                    /* Miscellaneous flags. See below */
   8936   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
   8937   int errCode;                  /* Most recent error code (SQLITE_*) */
   8938   int errMask;                  /* & result codes with this before returning */
   8939   u8 autoCommit;                /* The auto-commit flag. */
   8940   u8 temp_store;                /* 1: file 2: memory 0: default */
   8941   u8 mallocFailed;              /* True if we have seen a malloc failure */
   8942   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
   8943   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
   8944   u8 suppressErr;               /* Do not issue error messages if true */
   8945   int nextPagesize;             /* Pagesize after VACUUM if >0 */
   8946   int nTable;                   /* Number of tables in the database */
   8947   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
   8948   i64 lastRowid;                /* ROWID of most recent insert (see above) */
   8949   u32 magic;                    /* Magic number for detect library misuse */
   8950   int nChange;                  /* Value returned by sqlite3_changes() */
   8951   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
   8952   sqlite3_mutex *mutex;         /* Connection mutex */
   8953   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   8954   struct sqlite3InitInfo {      /* Information used during initialization */
   8955     int iDb;                    /* When back is being initialized */
   8956     int newTnum;                /* Rootpage of table being initialized */
   8957     u8 busy;                    /* TRUE if currently initializing */
   8958     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
   8959   } init;
   8960   int nExtension;               /* Number of loaded extensions */
   8961   void **aExtension;            /* Array of shared library handles */
   8962   struct Vdbe *pVdbe;           /* List of active virtual machines */
   8963   int activeVdbeCnt;            /* Number of VDBEs currently executing */
   8964   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
   8965   void (*xTrace)(void*,const char*);        /* Trace function */
   8966   void *pTraceArg;                          /* Argument to the trace function */
   8967   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
   8968   void *pProfileArg;                        /* Argument to profile function */
   8969   void *pCommitArg;                 /* Argument to xCommitCallback() */
   8970   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
   8971   void *pRollbackArg;               /* Argument to xRollbackCallback() */
   8972   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
   8973   void *pUpdateArg;
   8974   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
   8975 #ifndef SQLITE_OMIT_WAL
   8976   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
   8977   void *pWalArg;
   8978 #endif
   8979   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
   8980   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
   8981   void *pCollNeededArg;
   8982   sqlite3_value *pErr;          /* Most recent error message */
   8983   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
   8984   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
   8985   union {
   8986     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
   8987     double notUsed1;            /* Spacer */
   8988   } u1;
   8989   Lookaside lookaside;          /* Lookaside malloc configuration */
   8990 #ifndef SQLITE_OMIT_AUTHORIZATION
   8991   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   8992                                 /* Access authorization function */
   8993   void *pAuthArg;               /* 1st argument to the access auth function */
   8994 #endif
   8995 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   8996   int (*xProgress)(void *);     /* The progress callback */
   8997   void *pProgressArg;           /* Argument to the progress callback */
   8998   int nProgressOps;             /* Number of opcodes for progress callback */
   8999 #endif
   9000 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9001   Hash aModule;                 /* populated by sqlite3_create_module() */
   9002   Table *pVTab;                 /* vtab with active Connect/Create method */
   9003   VTable **aVTrans;             /* Virtual tables with open transactions */
   9004   int nVTrans;                  /* Allocated size of aVTrans */
   9005   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
   9006 #endif
   9007   FuncDefHash aFunc;            /* Hash table of connection functions */
   9008   Hash aCollSeq;                /* All collating sequences */
   9009   BusyHandler busyHandler;      /* Busy callback */
   9010   int busyTimeout;              /* Busy handler timeout, in msec */
   9011   Db aDbStatic[2];              /* Static space for the 2 default backends */
   9012   Savepoint *pSavepoint;        /* List of active savepoints */
   9013   int nSavepoint;               /* Number of non-transaction savepoints */
   9014   int nStatement;               /* Number of nested statement-transactions  */
   9015   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
   9016   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
   9017   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
   9018 
   9019 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   9020   /* The following variables are all protected by the STATIC_MASTER
   9021   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   9022   **
   9023   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
   9024   ** unlock so that it can proceed.
   9025   **
   9026   ** When X.pBlockingConnection==Y, that means that something that X tried
   9027   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
   9028   ** held by Y.
   9029   */
   9030   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
   9031   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
   9032   void *pUnlockArg;                     /* Argument to xUnlockNotify */
   9033   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
   9034   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
   9035 #endif
   9036 };
   9037 
   9038 /*
   9039 ** A macro to discover the encoding of a database.
   9040 */
   9041 #define ENC(db) ((db)->aDb[0].pSchema->enc)
   9042 
   9043 /*
   9044 ** Possible values for the sqlite3.flags.
   9045 */
   9046 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
   9047 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
   9048 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
   9049 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
   9050 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
   9051                                           /*   DELETE, or UPDATE and return */
   9052                                           /*   the count using a callback. */
   9053 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
   9054                                           /*   result set is empty */
   9055 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
   9056 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
   9057 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
   9058 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
   9059                                           ** accessing read-only databases */
   9060 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
   9061 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
   9062 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
   9063 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
   9064 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
   9065 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
   9066 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
   9067 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
   9068 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
   9069 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
   9070 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
   9071 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
   9072 
   9073 /*
   9074 ** Bits of the sqlite3.flags field that are used by the
   9075 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
   9076 ** These must be the low-order bits of the flags field.
   9077 */
   9078 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
   9079 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
   9080 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
   9081 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
   9082 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
   9083 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
   9084 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
   9085 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
   9086 
   9087 /*
   9088 ** Possible values for the sqlite.magic field.
   9089 ** The numbers are obtained at random and have no special meaning, other
   9090 ** than being distinct from one another.
   9091 */
   9092 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
   9093 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
   9094 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
   9095 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
   9096 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
   9097 
   9098 /*
   9099 ** Each SQL function is defined by an instance of the following
   9100 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
   9101 ** hash table.  When multiple functions have the same name, the hash table
   9102 ** points to a linked list of these structures.
   9103 */
   9104 struct FuncDef {
   9105   i16 nArg;            /* Number of arguments.  -1 means unlimited */
   9106   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
   9107   u8 flags;            /* Some combination of SQLITE_FUNC_* */
   9108   void *pUserData;     /* User data parameter */
   9109   FuncDef *pNext;      /* Next function with same name */
   9110   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
   9111   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
   9112   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
   9113   char *zName;         /* SQL name of the function. */
   9114   FuncDef *pHash;      /* Next with a different name but the same hash */
   9115   FuncDestructor *pDestructor;   /* Reference counted destructor function */
   9116 };
   9117 
   9118 /*
   9119 ** This structure encapsulates a user-function destructor callback (as
   9120 ** configured using create_function_v2()) and a reference counter. When
   9121 ** create_function_v2() is called to create a function with a destructor,
   9122 ** a single object of this type is allocated. FuncDestructor.nRef is set to
   9123 ** the number of FuncDef objects created (either 1 or 3, depending on whether
   9124 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
   9125 ** member of each of the new FuncDef objects is set to point to the allocated
   9126 ** FuncDestructor.
   9127 **
   9128 ** Thereafter, when one of the FuncDef objects is deleted, the reference
   9129 ** count on this object is decremented. When it reaches 0, the destructor
   9130 ** is invoked and the FuncDestructor structure freed.
   9131 */
   9132 struct FuncDestructor {
   9133   int nRef;
   9134   void (*xDestroy)(void *);
   9135   void *pUserData;
   9136 };
   9137 
   9138 /*
   9139 ** Possible values for FuncDef.flags
   9140 */
   9141 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
   9142 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
   9143 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
   9144 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
   9145 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
   9146 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
   9147 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
   9148 
   9149 /*
   9150 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
   9151 ** used to create the initializers for the FuncDef structures.
   9152 **
   9153 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
   9154 **     Used to create a scalar function definition of a function zName
   9155 **     implemented by C function xFunc that accepts nArg arguments. The
   9156 **     value passed as iArg is cast to a (void*) and made available
   9157 **     as the user-data (sqlite3_user_data()) for the function. If
   9158 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
   9159 **
   9160 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
   9161 **     Used to create an aggregate function definition implemented by
   9162 **     the C functions xStep and xFinal. The first four parameters
   9163 **     are interpreted in the same way as the first 4 parameters to
   9164 **     FUNCTION().
   9165 **
   9166 **   LIKEFUNC(zName, nArg, pArg, flags)
   9167 **     Used to create a scalar function definition of a function zName
   9168 **     that accepts nArg arguments and is implemented by a call to C
   9169 **     function likeFunc. Argument pArg is cast to a (void *) and made
   9170 **     available as the function user-data (sqlite3_user_data()). The
   9171 **     FuncDef.flags variable is set to the value passed as the flags
   9172 **     parameter.
   9173 */
   9174 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
   9175   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   9176    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
   9177 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
   9178   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
   9179    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
   9180 #define LIKEFUNC(zName, nArg, arg, flags) \
   9181   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
   9182 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
   9183   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
   9184    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
   9185 
   9186 /*
   9187 ** All current savepoints are stored in a linked list starting at
   9188 ** sqlite3.pSavepoint. The first element in the list is the most recently
   9189 ** opened savepoint. Savepoints are added to the list by the vdbe
   9190 ** OP_Savepoint instruction.
   9191 */
   9192 struct Savepoint {
   9193   char *zName;                        /* Savepoint name (nul-terminated) */
   9194   i64 nDeferredCons;                  /* Number of deferred fk violations */
   9195   Savepoint *pNext;                   /* Parent savepoint (if any) */
   9196 };
   9197 
   9198 /*
   9199 ** The following are used as the second parameter to sqlite3Savepoint(),
   9200 ** and as the P1 argument to the OP_Savepoint instruction.
   9201 */
   9202 #define SAVEPOINT_BEGIN      0
   9203 #define SAVEPOINT_RELEASE    1
   9204 #define SAVEPOINT_ROLLBACK   2
   9205 
   9206 
   9207 /*
   9208 ** Each SQLite module (virtual table definition) is defined by an
   9209 ** instance of the following structure, stored in the sqlite3.aModule
   9210 ** hash table.
   9211 */
   9212 struct Module {
   9213   const sqlite3_module *pModule;       /* Callback pointers */
   9214   const char *zName;                   /* Name passed to create_module() */
   9215   void *pAux;                          /* pAux passed to create_module() */
   9216   void (*xDestroy)(void *);            /* Module destructor function */
   9217 };
   9218 
   9219 /*
   9220 ** information about each column of an SQL table is held in an instance
   9221 ** of this structure.
   9222 */
   9223 struct Column {
   9224   char *zName;     /* Name of this column */
   9225   Expr *pDflt;     /* Default value of this column */
   9226   char *zDflt;     /* Original text of the default value */
   9227   char *zType;     /* Data type for this column */
   9228   char *zColl;     /* Collating sequence.  If NULL, use the default */
   9229   u8 notNull;      /* True if there is a NOT NULL constraint */
   9230   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
   9231   char affinity;   /* One of the SQLITE_AFF_... values */
   9232 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9233   u8 isHidden;     /* True if this column is 'hidden' */
   9234 #endif
   9235 };
   9236 
   9237 /*
   9238 ** A "Collating Sequence" is defined by an instance of the following
   9239 ** structure. Conceptually, a collating sequence consists of a name and
   9240 ** a comparison routine that defines the order of that sequence.
   9241 **
   9242 ** There may two separate implementations of the collation function, one
   9243 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
   9244 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
   9245 ** native byte order. When a collation sequence is invoked, SQLite selects
   9246 ** the version that will require the least expensive encoding
   9247 ** translations, if any.
   9248 **
   9249 ** The CollSeq.pUser member variable is an extra parameter that passed in
   9250 ** as the first argument to the UTF-8 comparison function, xCmp.
   9251 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
   9252 ** xCmp16.
   9253 **
   9254 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
   9255 ** collating sequence is undefined.  Indices built on an undefined
   9256 ** collating sequence may not be read or written.
   9257 */
   9258 struct CollSeq {
   9259   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
   9260   u8 enc;               /* Text encoding handled by xCmp() */
   9261   u8 type;              /* One of the SQLITE_COLL_... values below */
   9262   void *pUser;          /* First argument to xCmp() */
   9263   int (*xCmp)(void*,int, const void*, int, const void*);
   9264   void (*xDel)(void*);  /* Destructor for pUser */
   9265 };
   9266 
   9267 /*
   9268 ** Allowed values of CollSeq.type:
   9269 */
   9270 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
   9271 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
   9272 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
   9273 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
   9274 
   9275 /*
   9276 ** A sort order can be either ASC or DESC.
   9277 */
   9278 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
   9279 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
   9280 
   9281 /*
   9282 ** Column affinity types.
   9283 **
   9284 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
   9285 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
   9286 ** the speed a little by numbering the values consecutively.
   9287 **
   9288 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
   9289 ** when multiple affinity types are concatenated into a string and
   9290 ** used as the P4 operand, they will be more readable.
   9291 **
   9292 ** Note also that the numeric types are grouped together so that testing
   9293 ** for a numeric type is a single comparison.
   9294 */
   9295 #define SQLITE_AFF_TEXT     'a'
   9296 #define SQLITE_AFF_NONE     'b'
   9297 #define SQLITE_AFF_NUMERIC  'c'
   9298 #define SQLITE_AFF_INTEGER  'd'
   9299 #define SQLITE_AFF_REAL     'e'
   9300 
   9301 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
   9302 
   9303 /*
   9304 ** The SQLITE_AFF_MASK values masks off the significant bits of an
   9305 ** affinity value.
   9306 */
   9307 #define SQLITE_AFF_MASK     0x67
   9308 
   9309 /*
   9310 ** Additional bit values that can be ORed with an affinity without
   9311 ** changing the affinity.
   9312 */
   9313 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
   9314 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
   9315 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
   9316 
   9317 /*
   9318 ** An object of this type is created for each virtual table present in
   9319 ** the database schema.
   9320 **
   9321 ** If the database schema is shared, then there is one instance of this
   9322 ** structure for each database connection (sqlite3*) that uses the shared
   9323 ** schema. This is because each database connection requires its own unique
   9324 ** instance of the sqlite3_vtab* handle used to access the virtual table
   9325 ** implementation. sqlite3_vtab* handles can not be shared between
   9326 ** database connections, even when the rest of the in-memory database
   9327 ** schema is shared, as the implementation often stores the database
   9328 ** connection handle passed to it via the xConnect() or xCreate() method
   9329 ** during initialization internally. This database connection handle may
   9330 ** then used by the virtual table implementation to access real tables
   9331 ** within the database. So that they appear as part of the callers
   9332 ** transaction, these accesses need to be made via the same database
   9333 ** connection as that used to execute SQL operations on the virtual table.
   9334 **
   9335 ** All VTable objects that correspond to a single table in a shared
   9336 ** database schema are initially stored in a linked-list pointed to by
   9337 ** the Table.pVTable member variable of the corresponding Table object.
   9338 ** When an sqlite3_prepare() operation is required to access the virtual
   9339 ** table, it searches the list for the VTable that corresponds to the
   9340 ** database connection doing the preparing so as to use the correct
   9341 ** sqlite3_vtab* handle in the compiled query.
   9342 **
   9343 ** When an in-memory Table object is deleted (for example when the
   9344 ** schema is being reloaded for some reason), the VTable objects are not
   9345 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
   9346 ** immediately. Instead, they are moved from the Table.pVTable list to
   9347 ** another linked list headed by the sqlite3.pDisconnect member of the
   9348 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
   9349 ** next time a statement is prepared using said sqlite3*. This is done
   9350 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
   9351 ** Refer to comments above function sqlite3VtabUnlockList() for an
   9352 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
   9353 ** list without holding the corresponding sqlite3.mutex mutex.
   9354 **
   9355 ** The memory for objects of this type is always allocated by
   9356 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
   9357 ** the first argument.
   9358 */
   9359 struct VTable {
   9360   sqlite3 *db;              /* Database connection associated with this table */
   9361   Module *pMod;             /* Pointer to module implementation */
   9362   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   9363   int nRef;                 /* Number of pointers to this structure */
   9364   VTable *pNext;            /* Next in linked list (see above) */
   9365 };
   9366 
   9367 /*
   9368 ** Each SQL table is represented in memory by an instance of the
   9369 ** following structure.
   9370 **
   9371 ** Table.zName is the name of the table.  The case of the original
   9372 ** CREATE TABLE statement is stored, but case is not significant for
   9373 ** comparisons.
   9374 **
   9375 ** Table.nCol is the number of columns in this table.  Table.aCol is a
   9376 ** pointer to an array of Column structures, one for each column.
   9377 **
   9378 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
   9379 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
   9380 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
   9381 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
   9382 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
   9383 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
   9384 ** the table has any PRIMARY KEY, INTEGER or otherwise.
   9385 **
   9386 ** Table.tnum is the page number for the root BTree page of the table in the
   9387 ** database file.  If Table.iDb is the index of the database table backend
   9388 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
   9389 ** holds temporary tables and indices.  If TF_Ephemeral is set
   9390 ** then the table is stored in a file that is automatically deleted
   9391 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
   9392 ** refers VDBE cursor number that holds the table open, not to the root
   9393 ** page number.  Transient tables are used to hold the results of a
   9394 ** sub-query that appears instead of a real table name in the FROM clause
   9395 ** of a SELECT statement.
   9396 */
   9397 struct Table {
   9398   char *zName;         /* Name of the table or view */
   9399   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
   9400   int nCol;            /* Number of columns in this table */
   9401   Column *aCol;        /* Information about each column */
   9402   Index *pIndex;       /* List of SQL indexes on this table. */
   9403   int tnum;            /* Root BTree node for this table (see note above) */
   9404   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
   9405   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
   9406   u16 nRef;            /* Number of pointers to this Table */
   9407   u8 tabFlags;         /* Mask of TF_* values */
   9408   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
   9409   FKey *pFKey;         /* Linked list of all foreign keys in this table */
   9410   char *zColAff;       /* String defining the affinity of each column */
   9411 #ifndef SQLITE_OMIT_CHECK
   9412   Expr *pCheck;        /* The AND of all CHECK constraints */
   9413 #endif
   9414 #ifndef SQLITE_OMIT_ALTERTABLE
   9415   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
   9416 #endif
   9417 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9418   VTable *pVTable;     /* List of VTable objects. */
   9419   int nModuleArg;      /* Number of arguments to the module */
   9420   char **azModuleArg;  /* Text of all module args. [0] is module name */
   9421 #endif
   9422   Trigger *pTrigger;   /* List of triggers stored in pSchema */
   9423   Schema *pSchema;     /* Schema that contains this table */
   9424   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
   9425 };
   9426 
   9427 /*
   9428 ** Allowed values for Tabe.tabFlags.
   9429 */
   9430 #define TF_Readonly        0x01    /* Read-only system table */
   9431 #define TF_Ephemeral       0x02    /* An ephemeral table */
   9432 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
   9433 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
   9434 #define TF_Virtual         0x10    /* Is a virtual table */
   9435 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
   9436 
   9437 
   9438 
   9439 /*
   9440 ** Test to see whether or not a table is a virtual table.  This is
   9441 ** done as a macro so that it will be optimized out when virtual
   9442 ** table support is omitted from the build.
   9443 */
   9444 #ifndef SQLITE_OMIT_VIRTUALTABLE
   9445 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
   9446 #  define IsHiddenColumn(X) ((X)->isHidden)
   9447 #else
   9448 #  define IsVirtual(X)      0
   9449 #  define IsHiddenColumn(X) 0
   9450 #endif
   9451 
   9452 /*
   9453 ** Each foreign key constraint is an instance of the following structure.
   9454 **
   9455 ** A foreign key is associated with two tables.  The "from" table is
   9456 ** the table that contains the REFERENCES clause that creates the foreign
   9457 ** key.  The "to" table is the table that is named in the REFERENCES clause.
   9458 ** Consider this example:
   9459 **
   9460 **     CREATE TABLE ex1(
   9461 **       a INTEGER PRIMARY KEY,
   9462 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
   9463 **     );
   9464 **
   9465 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
   9466 **
   9467 ** Each REFERENCES clause generates an instance of the following structure
   9468 ** which is attached to the from-table.  The to-table need not exist when
   9469 ** the from-table is created.  The existence of the to-table is not checked.
   9470 */
   9471 struct FKey {
   9472   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
   9473   FKey *pNextFrom;  /* Next foreign key in pFrom */
   9474   char *zTo;        /* Name of table that the key points to (aka: Parent) */
   9475   FKey *pNextTo;    /* Next foreign key on table named zTo */
   9476   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
   9477   int nCol;         /* Number of columns in this key */
   9478   /* EV: R-30323-21917 */
   9479   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
   9480   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
   9481   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
   9482   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
   9483     int iFrom;         /* Index of column in pFrom */
   9484     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
   9485   } aCol[1];        /* One entry for each of nCol column s */
   9486 };
   9487 
   9488 /*
   9489 ** SQLite supports many different ways to resolve a constraint
   9490 ** error.  ROLLBACK processing means that a constraint violation
   9491 ** causes the operation in process to fail and for the current transaction
   9492 ** to be rolled back.  ABORT processing means the operation in process
   9493 ** fails and any prior changes from that one operation are backed out,
   9494 ** but the transaction is not rolled back.  FAIL processing means that
   9495 ** the operation in progress stops and returns an error code.  But prior
   9496 ** changes due to the same operation are not backed out and no rollback
   9497 ** occurs.  IGNORE means that the particular row that caused the constraint
   9498 ** error is not inserted or updated.  Processing continues and no error
   9499 ** is returned.  REPLACE means that preexisting database rows that caused
   9500 ** a UNIQUE constraint violation are removed so that the new insert or
   9501 ** update can proceed.  Processing continues and no error is reported.
   9502 **
   9503 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
   9504 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
   9505 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
   9506 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
   9507 ** referenced table row is propagated into the row that holds the
   9508 ** foreign key.
   9509 **
   9510 ** The following symbolic values are used to record which type
   9511 ** of action to take.
   9512 */
   9513 #define OE_None     0   /* There is no constraint to check */
   9514 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
   9515 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
   9516 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
   9517 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
   9518 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
   9519 
   9520 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
   9521 #define OE_SetNull  7   /* Set the foreign key value to NULL */
   9522 #define OE_SetDflt  8   /* Set the foreign key value to its default */
   9523 #define OE_Cascade  9   /* Cascade the changes */
   9524 
   9525 #define OE_Default  99  /* Do whatever the default action is */
   9526 
   9527 
   9528 /*
   9529 ** An instance of the following structure is passed as the first
   9530 ** argument to sqlite3VdbeKeyCompare and is used to control the
   9531 ** comparison of the two index keys.
   9532 */
   9533 struct KeyInfo {
   9534   sqlite3 *db;        /* The database connection */
   9535   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
   9536   u16 nField;         /* Number of entries in aColl[] */
   9537   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
   9538   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
   9539 };
   9540 
   9541 /*
   9542 ** An instance of the following structure holds information about a
   9543 ** single index record that has already been parsed out into individual
   9544 ** values.
   9545 **
   9546 ** A record is an object that contains one or more fields of data.
   9547 ** Records are used to store the content of a table row and to store
   9548 ** the key of an index.  A blob encoding of a record is created by
   9549 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
   9550 ** OP_Column opcode.
   9551 **
   9552 ** This structure holds a record that has already been disassembled
   9553 ** into its constituent fields.
   9554 */
   9555 struct UnpackedRecord {
   9556   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
   9557   u16 nField;         /* Number of entries in apMem[] */
   9558   u16 flags;          /* Boolean settings.  UNPACKED_... below */
   9559   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
   9560   Mem *aMem;          /* Values */
   9561 };
   9562 
   9563 /*
   9564 ** Allowed values of UnpackedRecord.flags
   9565 */
   9566 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
   9567 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
   9568 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
   9569 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
   9570 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
   9571 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
   9572 
   9573 /*
   9574 ** Each SQL index is represented in memory by an
   9575 ** instance of the following structure.
   9576 **
   9577 ** The columns of the table that are to be indexed are described
   9578 ** by the aiColumn[] field of this structure.  For example, suppose
   9579 ** we have the following table and index:
   9580 **
   9581 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
   9582 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
   9583 **
   9584 ** In the Table structure describing Ex1, nCol==3 because there are
   9585 ** three columns in the table.  In the Index structure describing
   9586 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
   9587 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
   9588 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
   9589 ** The second column to be indexed (c1) has an index of 0 in
   9590 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
   9591 **
   9592 ** The Index.onError field determines whether or not the indexed columns
   9593 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
   9594 ** it means this is not a unique index.  Otherwise it is a unique index
   9595 ** and the value of Index.onError indicate the which conflict resolution
   9596 ** algorithm to employ whenever an attempt is made to insert a non-unique
   9597 ** element.
   9598 */
   9599 struct Index {
   9600   char *zName;     /* Name of this index */
   9601   int nColumn;     /* Number of columns in the table used by this index */
   9602   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
   9603   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
   9604   Table *pTable;   /* The SQL table being indexed */
   9605   int tnum;        /* Page containing root of this index in database file */
   9606   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   9607   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
   9608   char *zColAff;   /* String defining the affinity of each column */
   9609   Index *pNext;    /* The next index associated with the same table */
   9610   Schema *pSchema; /* Schema containing this index */
   9611   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
   9612   char **azColl;   /* Array of collation sequence names for index */
   9613   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
   9614 };
   9615 
   9616 /*
   9617 ** Each sample stored in the sqlite_stat2 table is represented in memory
   9618 ** using a structure of this type.
   9619 */
   9620 struct IndexSample {
   9621   union {
   9622     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
   9623     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
   9624   } u;
   9625   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
   9626   u8 nByte;         /* Size in byte of text or blob. */
   9627 };
   9628 
   9629 /*
   9630 ** Each token coming out of the lexer is an instance of
   9631 ** this structure.  Tokens are also used as part of an expression.
   9632 **
   9633 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
   9634 ** may contain random values.  Do not make any assumptions about Token.dyn
   9635 ** and Token.n when Token.z==0.
   9636 */
   9637 struct Token {
   9638   const char *z;     /* Text of the token.  Not NULL-terminated! */
   9639   unsigned int n;    /* Number of characters in this token */
   9640 };
   9641 
   9642 /*
   9643 ** An instance of this structure contains information needed to generate
   9644 ** code for a SELECT that contains aggregate functions.
   9645 **
   9646 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
   9647 ** pointer to this structure.  The Expr.iColumn field is the index in
   9648 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
   9649 ** code for that node.
   9650 **
   9651 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
   9652 ** original Select structure that describes the SELECT statement.  These
   9653 ** fields do not need to be freed when deallocating the AggInfo structure.
   9654 */
   9655 struct AggInfo {
   9656   u8 directMode;          /* Direct rendering mode means take data directly
   9657                           ** from source tables rather than from accumulators */
   9658   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
   9659                           ** than the source table */
   9660   int sortingIdx;         /* Cursor number of the sorting index */
   9661   ExprList *pGroupBy;     /* The group by clause */
   9662   int nSortingColumn;     /* Number of columns in the sorting index */
   9663   struct AggInfo_col {    /* For each column used in source tables */
   9664     Table *pTab;             /* Source table */
   9665     int iTable;              /* Cursor number of the source table */
   9666     int iColumn;             /* Column number within the source table */
   9667     int iSorterColumn;       /* Column number in the sorting index */
   9668     int iMem;                /* Memory location that acts as accumulator */
   9669     Expr *pExpr;             /* The original expression */
   9670   } *aCol;
   9671   int nColumn;            /* Number of used entries in aCol[] */
   9672   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
   9673   int nAccumulator;       /* Number of columns that show through to the output.
   9674                           ** Additional columns are used only as parameters to
   9675                           ** aggregate functions */
   9676   struct AggInfo_func {   /* For each aggregate function */
   9677     Expr *pExpr;             /* Expression encoding the function */
   9678     FuncDef *pFunc;          /* The aggregate function implementation */
   9679     int iMem;                /* Memory location that acts as accumulator */
   9680     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   9681   } *aFunc;
   9682   int nFunc;              /* Number of entries in aFunc[] */
   9683   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
   9684 };
   9685 
   9686 /*
   9687 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
   9688 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
   9689 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
   9690 ** it uses less memory in the Expr object, which is a big memory user
   9691 ** in systems with lots of prepared statements.  And few applications
   9692 ** need more than about 10 or 20 variables.  But some extreme users want
   9693 ** to have prepared statements with over 32767 variables, and for them
   9694 ** the option is available (at compile-time).
   9695 */
   9696 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
   9697 typedef i16 ynVar;
   9698 #else
   9699 typedef int ynVar;
   9700 #endif
   9701 
   9702 /*
   9703 ** Each node of an expression in the parse tree is an instance
   9704 ** of this structure.
   9705 **
   9706 ** Expr.op is the opcode. The integer parser token codes are reused
   9707 ** as opcodes here. For example, the parser defines TK_GE to be an integer
   9708 ** code representing the ">=" operator. This same integer code is reused
   9709 ** to represent the greater-than-or-equal-to operator in the expression
   9710 ** tree.
   9711 **
   9712 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
   9713 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
   9714 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
   9715 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
   9716 ** then Expr.token contains the name of the function.
   9717 **
   9718 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
   9719 ** binary operator. Either or both may be NULL.
   9720 **
   9721 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
   9722 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
   9723 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
   9724 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
   9725 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
   9726 ** valid.
   9727 **
   9728 ** An expression of the form ID or ID.ID refers to a column in a table.
   9729 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
   9730 ** the integer cursor number of a VDBE cursor pointing to that table and
   9731 ** Expr.iColumn is the column number for the specific column.  If the
   9732 ** expression is used as a result in an aggregate SELECT, then the
   9733 ** value is also stored in the Expr.iAgg column in the aggregate so that
   9734 ** it can be accessed after all aggregates are computed.
   9735 **
   9736 ** If the expression is an unbound variable marker (a question mark
   9737 ** character '?' in the original SQL) then the Expr.iTable holds the index
   9738 ** number for that variable.
   9739 **
   9740 ** If the expression is a subquery then Expr.iColumn holds an integer
   9741 ** register number containing the result of the subquery.  If the
   9742 ** subquery gives a constant result, then iTable is -1.  If the subquery
   9743 ** gives a different answer at different times during statement processing
   9744 ** then iTable is the address of a subroutine that computes the subquery.
   9745 **
   9746 ** If the Expr is of type OP_Column, and the table it is selecting from
   9747 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
   9748 ** corresponding table definition.
   9749 **
   9750 ** ALLOCATION NOTES:
   9751 **
   9752 ** Expr objects can use a lot of memory space in database schema.  To
   9753 ** help reduce memory requirements, sometimes an Expr object will be
   9754 ** truncated.  And to reduce the number of memory allocations, sometimes
   9755 ** two or more Expr objects will be stored in a single memory allocation,
   9756 ** together with Expr.zToken strings.
   9757 **
   9758 ** If the EP_Reduced and EP_TokenOnly flags are set when
   9759 ** an Expr object is truncated.  When EP_Reduced is set, then all
   9760 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
   9761 ** are contained within the same memory allocation.  Note, however, that
   9762 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
   9763 ** allocated, regardless of whether or not EP_Reduced is set.
   9764 */
   9765 struct Expr {
   9766   u8 op;                 /* Operation performed by this node */
   9767   char affinity;         /* The affinity of the column or 0 if not a column */
   9768   u16 flags;             /* Various flags.  EP_* See below */
   9769   union {
   9770     char *zToken;          /* Token value. Zero terminated and dequoted */
   9771     int iValue;            /* Integer value if EP_IntValue */
   9772   } u;
   9773 
   9774   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
   9775   ** space is allocated for the fields below this point. An attempt to
   9776   ** access them will result in a segfault or malfunction.
   9777   *********************************************************************/
   9778 
   9779   Expr *pLeft;           /* Left subnode */
   9780   Expr *pRight;          /* Right subnode */
   9781   union {
   9782     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
   9783     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
   9784   } x;
   9785   CollSeq *pColl;        /* The collation type of the column or 0 */
   9786 
   9787   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
   9788   ** space is allocated for the fields below this point. An attempt to
   9789   ** access them will result in a segfault or malfunction.
   9790   *********************************************************************/
   9791 
   9792   int iTable;            /* TK_COLUMN: cursor number of table holding column
   9793                          ** TK_REGISTER: register number
   9794                          ** TK_TRIGGER: 1 -> new, 0 -> old */
   9795   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
   9796                          ** TK_VARIABLE: variable number (always >= 1). */
   9797   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   9798   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
   9799   u8 flags2;             /* Second set of flags.  EP2_... */
   9800   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
   9801   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   9802   Table *pTab;           /* Table for TK_COLUMN expressions. */
   9803 #if SQLITE_MAX_EXPR_DEPTH>0
   9804   int nHeight;           /* Height of the tree headed by this node */
   9805 #endif
   9806 };
   9807 
   9808 /*
   9809 ** The following are the meanings of bits in the Expr.flags field.
   9810 */
   9811 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
   9812 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
   9813 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
   9814 #define EP_Error      0x0008  /* Expression contains one or more errors */
   9815 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
   9816 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
   9817 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
   9818 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
   9819 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
   9820 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
   9821 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
   9822 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
   9823 
   9824 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
   9825 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
   9826 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
   9827 
   9828 /*
   9829 ** The following are the meanings of bits in the Expr.flags2 field.
   9830 */
   9831 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
   9832 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
   9833 
   9834 /*
   9835 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
   9836 ** flag on an expression structure.  This flag is used for VV&A only.  The
   9837 ** routine is implemented as a macro that only works when in debugging mode,
   9838 ** so as not to burden production code.
   9839 */
   9840 #ifdef SQLITE_DEBUG
   9841 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
   9842 #else
   9843 # define ExprSetIrreducible(X)
   9844 #endif
   9845 
   9846 /*
   9847 ** These macros can be used to test, set, or clear bits in the
   9848 ** Expr.flags field.
   9849 */
   9850 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
   9851 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
   9852 #define ExprSetProperty(E,P)     (E)->flags|=(P)
   9853 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
   9854 
   9855 /*
   9856 ** Macros to determine the number of bytes required by a normal Expr
   9857 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
   9858 ** and an Expr struct with the EP_TokenOnly flag set.
   9859 */
   9860 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
   9861 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
   9862 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
   9863 
   9864 /*
   9865 ** Flags passed to the sqlite3ExprDup() function. See the header comment
   9866 ** above sqlite3ExprDup() for details.
   9867 */
   9868 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
   9869 
   9870 /*
   9871 ** A list of expressions.  Each expression may optionally have a
   9872 ** name.  An expr/name combination can be used in several ways, such
   9873 ** as the list of "expr AS ID" fields following a "SELECT" or in the
   9874 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
   9875 ** also be used as the argument to a function, in which case the a.zName
   9876 ** field is not used.
   9877 */
   9878 struct ExprList {
   9879   int nExpr;             /* Number of expressions on the list */
   9880   int nAlloc;            /* Number of entries allocated below */
   9881   int iECursor;          /* VDBE Cursor associated with this ExprList */
   9882   struct ExprList_item {
   9883     Expr *pExpr;           /* The list of expressions */
   9884     char *zName;           /* Token associated with this expression */
   9885     char *zSpan;           /* Original text of the expression */
   9886     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
   9887     u8 done;               /* A flag to indicate when processing is finished */
   9888     u16 iCol;              /* For ORDER BY, column number in result set */
   9889     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
   9890   } *a;                  /* One entry for each expression */
   9891 };
   9892 
   9893 /*
   9894 ** An instance of this structure is used by the parser to record both
   9895 ** the parse tree for an expression and the span of input text for an
   9896 ** expression.
   9897 */
   9898 struct ExprSpan {
   9899   Expr *pExpr;          /* The expression parse tree */
   9900   const char *zStart;   /* First character of input text */
   9901   const char *zEnd;     /* One character past the end of input text */
   9902 };
   9903 
   9904 /*
   9905 ** An instance of this structure can hold a simple list of identifiers,
   9906 ** such as the list "a,b,c" in the following statements:
   9907 **
   9908 **      INSERT INTO t(a,b,c) VALUES ...;
   9909 **      CREATE INDEX idx ON t(a,b,c);
   9910 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
   9911 **
   9912 ** The IdList.a.idx field is used when the IdList represents the list of
   9913 ** column names after a table name in an INSERT statement.  In the statement
   9914 **
   9915 **     INSERT INTO t(a,b,c) ...
   9916 **
   9917 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
   9918 */
   9919 struct IdList {
   9920   struct IdList_item {
   9921     char *zName;      /* Name of the identifier */
   9922     int idx;          /* Index in some Table.aCol[] of a column named zName */
   9923   } *a;
   9924   int nId;         /* Number of identifiers on the list */
   9925   int nAlloc;      /* Number of entries allocated for a[] below */
   9926 };
   9927 
   9928 /*
   9929 ** The bitmask datatype defined below is used for various optimizations.
   9930 **
   9931 ** Changing this from a 64-bit to a 32-bit type limits the number of
   9932 ** tables in a join to 32 instead of 64.  But it also reduces the size
   9933 ** of the library by 738 bytes on ix86.
   9934 */
   9935 typedef u64 Bitmask;
   9936 
   9937 /*
   9938 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
   9939 */
   9940 #define BMS  ((int)(sizeof(Bitmask)*8))
   9941 
   9942 /*
   9943 ** The following structure describes the FROM clause of a SELECT statement.
   9944 ** Each table or subquery in the FROM clause is a separate element of
   9945 ** the SrcList.a[] array.
   9946 **
   9947 ** With the addition of multiple database support, the following structure
   9948 ** can also be used to describe a particular table such as the table that
   9949 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
   9950 ** such a table must be a simple name: ID.  But in SQLite, the table can
   9951 ** now be identified by a database name, a dot, then the table name: ID.ID.
   9952 **
   9953 ** The jointype starts out showing the join type between the current table
   9954 ** and the next table on the list.  The parser builds the list this way.
   9955 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
   9956 ** jointype expresses the join between the table and the previous table.
   9957 **
   9958 ** In the colUsed field, the high-order bit (bit 63) is set if the table
   9959 ** contains more than 63 columns and the 64-th or later column is used.
   9960 */
   9961 struct SrcList {
   9962   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
   9963   i16 nAlloc;      /* Number of entries allocated in a[] below */
   9964   struct SrcList_item {
   9965     char *zDatabase;  /* Name of database holding this table */
   9966     char *zName;      /* Name of the table */
   9967     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   9968     Table *pTab;      /* An SQL table corresponding to zName */
   9969     Select *pSelect;  /* A SELECT statement used in place of a table name */
   9970     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
   9971     u8 jointype;      /* Type of join between this able and the previous */
   9972     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
   9973 #ifndef SQLITE_OMIT_EXPLAIN
   9974     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
   9975 #endif
   9976     int iCursor;      /* The VDBE cursor number used to access this table */
   9977     Expr *pOn;        /* The ON clause of a join */
   9978     IdList *pUsing;   /* The USING clause of a join */
   9979     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
   9980     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
   9981     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
   9982   } a[1];             /* One entry for each identifier on the list */
   9983 };
   9984 
   9985 /*
   9986 ** Permitted values of the SrcList.a.jointype field
   9987 */
   9988 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
   9989 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
   9990 #define JT_NATURAL   0x0004    /* True for a "natural" join */
   9991 #define JT_LEFT      0x0008    /* Left outer join */
   9992 #define JT_RIGHT     0x0010    /* Right outer join */
   9993 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
   9994 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
   9995 
   9996 
   9997 /*
   9998 ** A WherePlan object holds information that describes a lookup
   9999 ** strategy.
   10000 **
   10001 ** This object is intended to be opaque outside of the where.c module.
   10002 ** It is included here only so that that compiler will know how big it
   10003 ** is.  None of the fields in this object should be used outside of
   10004 ** the where.c module.
   10005 **
   10006 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
   10007 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
   10008 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
   10009 ** case that more than one of these conditions is true.
   10010 */
   10011 struct WherePlan {
   10012   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
   10013   u32 nEq;                       /* Number of == constraints */
   10014   double nRow;                   /* Estimated number of rows (for EQP) */
   10015   union {
   10016     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
   10017     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
   10018     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
   10019   } u;
   10020 };
   10021 
   10022 /*
   10023 ** For each nested loop in a WHERE clause implementation, the WhereInfo
   10024 ** structure contains a single instance of this structure.  This structure
   10025 ** is intended to be private the the where.c module and should not be
   10026 ** access or modified by other modules.
   10027 **
   10028 ** The pIdxInfo field is used to help pick the best index on a
   10029 ** virtual table.  The pIdxInfo pointer contains indexing
   10030 ** information for the i-th table in the FROM clause before reordering.
   10031 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
   10032 ** All other information in the i-th WhereLevel object for the i-th table
   10033 ** after FROM clause ordering.
   10034 */
   10035 struct WhereLevel {
   10036   WherePlan plan;       /* query plan for this element of the FROM clause */
   10037   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
   10038   int iTabCur;          /* The VDBE cursor used to access the table */
   10039   int iIdxCur;          /* The VDBE cursor used to access pIdx */
   10040   int addrBrk;          /* Jump here to break out of the loop */
   10041   int addrNxt;          /* Jump here to start the next IN combination */
   10042   int addrCont;         /* Jump here to continue with the next loop cycle */
   10043   int addrFirst;        /* First instruction of interior of the loop */
   10044   u8 iFrom;             /* Which entry in the FROM clause */
   10045   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
   10046   int p1, p2;           /* Operands of the opcode used to ends the loop */
   10047   union {               /* Information that depends on plan.wsFlags */
   10048     struct {
   10049       int nIn;              /* Number of entries in aInLoop[] */
   10050       struct InLoop {
   10051         int iCur;              /* The VDBE cursor used by this IN operator */
   10052         int addrInTop;         /* Top of the IN loop */
   10053       } *aInLoop;           /* Information about each nested IN operator */
   10054     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
   10055   } u;
   10056 
   10057   /* The following field is really not part of the current level.  But
   10058   ** we need a place to cache virtual table index information for each
   10059   ** virtual table in the FROM clause and the WhereLevel structure is
   10060   ** a convenient place since there is one WhereLevel for each FROM clause
   10061   ** element.
   10062   */
   10063   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
   10064 };
   10065 
   10066 /*
   10067 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
   10068 ** and the WhereInfo.wctrlFlags member.
   10069 */
   10070 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
   10071 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
   10072 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
   10073 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
   10074 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
   10075 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
   10076 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
   10077 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
   10078 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
   10079 
   10080 /*
   10081 ** The WHERE clause processing routine has two halves.  The
   10082 ** first part does the start of the WHERE loop and the second
   10083 ** half does the tail of the WHERE loop.  An instance of
   10084 ** this structure is returned by the first half and passed
   10085 ** into the second half to give some continuity.
   10086 */
   10087 struct WhereInfo {
   10088   Parse *pParse;       /* Parsing and code generating context */
   10089   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
   10090   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
   10091   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
   10092   SrcList *pTabList;             /* List of tables in the join */
   10093   int iTop;                      /* The very beginning of the WHERE loop */
   10094   int iContinue;                 /* Jump here to continue with next record */
   10095   int iBreak;                    /* Jump here to break out of the loop */
   10096   int nLevel;                    /* Number of nested loop */
   10097   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
   10098   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
   10099   double nRowOut;                /* Estimated number of output rows */
   10100   WhereLevel a[1];               /* Information about each nest loop in WHERE */
   10101 };
   10102 
   10103 /*
   10104 ** A NameContext defines a context in which to resolve table and column
   10105 ** names.  The context consists of a list of tables (the pSrcList) field and
   10106 ** a list of named expression (pEList).  The named expression list may
   10107 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
   10108 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
   10109 ** pEList corresponds to the result set of a SELECT and is NULL for
   10110 ** other statements.
   10111 **
   10112 ** NameContexts can be nested.  When resolving names, the inner-most
   10113 ** context is searched first.  If no match is found, the next outer
   10114 ** context is checked.  If there is still no match, the next context
   10115 ** is checked.  This process continues until either a match is found
   10116 ** or all contexts are check.  When a match is found, the nRef member of
   10117 ** the context containing the match is incremented.
   10118 **
   10119 ** Each subquery gets a new NameContext.  The pNext field points to the
   10120 ** NameContext in the parent query.  Thus the process of scanning the
   10121 ** NameContext list corresponds to searching through successively outer
   10122 ** subqueries looking for a match.
   10123 */
   10124 struct NameContext {
   10125   Parse *pParse;       /* The parser */
   10126   SrcList *pSrcList;   /* One or more tables used to resolve names */
   10127   ExprList *pEList;    /* Optional list of named expressions */
   10128   int nRef;            /* Number of names resolved by this context */
   10129   int nErr;            /* Number of errors encountered while resolving names */
   10130   u8 allowAgg;         /* Aggregate functions allowed here */
   10131   u8 hasAgg;           /* True if aggregates are seen */
   10132   u8 isCheck;          /* True if resolving names in a CHECK constraint */
   10133   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
   10134   AggInfo *pAggInfo;   /* Information about aggregates at this level */
   10135   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
   10136 };
   10137 
   10138 /*
   10139 ** An instance of the following structure contains all information
   10140 ** needed to generate code for a single SELECT statement.
   10141 **
   10142 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   10143 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   10144 ** limit and nOffset to the value of the offset (or 0 if there is not
   10145 ** offset).  But later on, nLimit and nOffset become the memory locations
   10146 ** in the VDBE that record the limit and offset counters.
   10147 **
   10148 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
   10149 ** These addresses must be stored so that we can go back and fill in
   10150 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
   10151 ** the number of columns in P2 can be computed at the same time
   10152 ** as the OP_OpenEphm instruction is coded because not
   10153 ** enough information about the compound query is known at that point.
   10154 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
   10155 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
   10156 ** sequences for the ORDER BY clause.
   10157 */
   10158 struct Select {
   10159   ExprList *pEList;      /* The fields of the result */
   10160   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   10161   char affinity;         /* MakeRecord with this affinity for SRT_Set */
   10162   u16 selFlags;          /* Various SF_* values */
   10163   SrcList *pSrc;         /* The FROM clause */
   10164   Expr *pWhere;          /* The WHERE clause */
   10165   ExprList *pGroupBy;    /* The GROUP BY clause */
   10166   Expr *pHaving;         /* The HAVING clause */
   10167   ExprList *pOrderBy;    /* The ORDER BY clause */
   10168   Select *pPrior;        /* Prior select in a compound select statement */
   10169   Select *pNext;         /* Next select to the left in a compound */
   10170   Select *pRightmost;    /* Right-most select in a compound select statement */
   10171   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
   10172   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
   10173   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   10174   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
   10175   double nSelectRow;     /* Estimated number of result rows */
   10176 };
   10177 
   10178 /*
   10179 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
   10180 ** "Select Flag".
   10181 */
   10182 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
   10183 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
   10184 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
   10185 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
   10186 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
   10187 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
   10188 
   10189 
   10190 /*
   10191 ** The results of a select can be distributed in several ways.  The
   10192 ** "SRT" prefix means "SELECT Result Type".
   10193 */
   10194 #define SRT_Union        1  /* Store result as keys in an index */
   10195 #define SRT_Except       2  /* Remove result from a UNION index */
   10196 #define SRT_Exists       3  /* Store 1 if the result is not empty */
   10197 #define SRT_Discard      4  /* Do not save the results anywhere */
   10198 
   10199 /* The ORDER BY clause is ignored for all of the above */
   10200 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
   10201 
   10202 #define SRT_Output       5  /* Output each row of result */
   10203 #define SRT_Mem          6  /* Store result in a memory cell */
   10204 #define SRT_Set          7  /* Store results as keys in an index */
   10205 #define SRT_Table        8  /* Store result as data with an automatic rowid */
   10206 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
   10207 #define SRT_Coroutine   10  /* Generate a single row of result */
   10208 
   10209 /*
   10210 ** A structure used to customize the behavior of sqlite3Select(). See
   10211 ** comments above sqlite3Select() for details.
   10212 */
   10213 typedef struct SelectDest SelectDest;
   10214 struct SelectDest {
   10215   u8 eDest;         /* How to dispose of the results */
   10216   u8 affinity;      /* Affinity used when eDest==SRT_Set */
   10217   int iParm;        /* A parameter used by the eDest disposal method */
   10218   int iMem;         /* Base register where results are written */
   10219   int nMem;         /* Number of registers allocated */
   10220 };
   10221 
   10222 /*
   10223 ** During code generation of statements that do inserts into AUTOINCREMENT
   10224 ** tables, the following information is attached to the Table.u.autoInc.p
   10225 ** pointer of each autoincrement table to record some side information that
   10226 ** the code generator needs.  We have to keep per-table autoincrement
   10227 ** information in case inserts are down within triggers.  Triggers do not
   10228 ** normally coordinate their activities, but we do need to coordinate the
   10229 ** loading and saving of autoincrement information.
   10230 */
   10231 struct AutoincInfo {
   10232   AutoincInfo *pNext;   /* Next info block in a list of them all */
   10233   Table *pTab;          /* Table this info block refers to */
   10234   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
   10235   int regCtr;           /* Memory register holding the rowid counter */
   10236 };
   10237 
   10238 /*
   10239 ** Size of the column cache
   10240 */
   10241 #ifndef SQLITE_N_COLCACHE
   10242 # define SQLITE_N_COLCACHE 10
   10243 #endif
   10244 
   10245 /*
   10246 ** At least one instance of the following structure is created for each
   10247 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
   10248 ** statement. All such objects are stored in the linked list headed at
   10249 ** Parse.pTriggerPrg and deleted once statement compilation has been
   10250 ** completed.
   10251 **
   10252 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
   10253 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
   10254 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
   10255 ** The Parse.pTriggerPrg list never contains two entries with the same
   10256 ** values for both pTrigger and orconf.
   10257 **
   10258 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
   10259 ** accessed (or set to 0 for triggers fired as a result of INSERT
   10260 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
   10261 ** a mask of new.* columns used by the program.
   10262 */
   10263 struct TriggerPrg {
   10264   Trigger *pTrigger;      /* Trigger this program was coded from */
   10265   int orconf;             /* Default ON CONFLICT policy */
   10266   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
   10267   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
   10268   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
   10269 };
   10270 
   10271 /*
   10272 ** An SQL parser context.  A copy of this structure is passed through
   10273 ** the parser and down into all the parser action routine in order to
   10274 ** carry around information that is global to the entire parse.
   10275 **
   10276 ** The structure is divided into two parts.  When the parser and code
   10277 ** generate call themselves recursively, the first part of the structure
   10278 ** is constant but the second part is reset at the beginning and end of
   10279 ** each recursion.
   10280 **
   10281 ** The nTableLock and aTableLock variables are only used if the shared-cache
   10282 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
   10283 ** used to store the set of table-locks required by the statement being
   10284 ** compiled. Function sqlite3TableLock() is used to add entries to the
   10285 ** list.
   10286 */
   10287 struct Parse {
   10288   sqlite3 *db;         /* The main database structure */
   10289   int rc;              /* Return code from execution */
   10290   char *zErrMsg;       /* An error message */
   10291   Vdbe *pVdbe;         /* An engine for executing database bytecode */
   10292   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
   10293   u8 nameClash;        /* A permanent table name clashes with temp table name */
   10294   u8 checkSchema;      /* Causes schema cookie check after an error */
   10295   u8 nested;           /* Number of nested calls to the parser/code generator */
   10296   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
   10297   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
   10298   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
   10299   int aTempReg[8];     /* Holding area for temporary registers */
   10300   int nRangeReg;       /* Size of the temporary register block */
   10301   int iRangeReg;       /* First register in temporary register block */
   10302   int nErr;            /* Number of errors seen */
   10303   int nTab;            /* Number of previously allocated VDBE cursors */
   10304   int nMem;            /* Number of memory cells used so far */
   10305   int nSet;            /* Number of sets used so far */
   10306   int ckBase;          /* Base register of data during check constraints */
   10307   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
   10308   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
   10309   u8 nColCache;        /* Number of entries in the column cache */
   10310   u8 iColCache;        /* Next entry of the cache to replace */
   10311   struct yColCache {
   10312     int iTable;           /* Table cursor number */
   10313     int iColumn;          /* Table column number */
   10314     u8 tempReg;           /* iReg is a temp register that needs to be freed */
   10315     int iLevel;           /* Nesting level */
   10316     int iReg;             /* Reg with value of this column. 0 means none. */
   10317     int lru;              /* Least recently used entry has the smallest value */
   10318   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
   10319   u32 writeMask;       /* Start a write transaction on these databases */
   10320   u32 cookieMask;      /* Bitmask of schema verified databases */
   10321   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
   10322   u8 mayAbort;         /* True if statement may throw an ABORT exception */
   10323   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
   10324   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
   10325 #ifndef SQLITE_OMIT_SHARED_CACHE
   10326   int nTableLock;        /* Number of locks in aTableLock */
   10327   TableLock *aTableLock; /* Required table locks for shared-cache mode */
   10328 #endif
   10329   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
   10330   int regRoot;         /* Register holding root page number for new objects */
   10331   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
   10332   int nMaxArg;         /* Max args passed to user function by sub-program */
   10333 
   10334   /* Information used while coding trigger programs. */
   10335   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   10336   Table *pTriggerTab;  /* Table triggers are being coded for */
   10337   u32 oldmask;         /* Mask of old.* columns referenced */
   10338   u32 newmask;         /* Mask of new.* columns referenced */
   10339   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
   10340   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
   10341   u8 disableTriggers;  /* True to disable triggers */
   10342   double nQueryLoop;   /* Estimated number of iterations of a query */
   10343 
   10344   /* Above is constant between recursions.  Below is reset before and after
   10345   ** each recursion */
   10346 
   10347   int nVar;            /* Number of '?' variables seen in the SQL so far */
   10348   int nVarExpr;        /* Number of used slots in apVarExpr[] */
   10349   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
   10350   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
   10351   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
   10352   int nAlias;          /* Number of aliased result set columns */
   10353   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
   10354   int *aAlias;         /* Register used to hold aliased result */
   10355   u8 explain;          /* True if the EXPLAIN flag is found on the query */
   10356   Token sNameToken;    /* Token with unqualified schema object name */
   10357   Token sLastToken;    /* The last token parsed */
   10358   const char *zTail;   /* All SQL text past the last semicolon parsed */
   10359   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
   10360   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
   10361   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
   10362 #ifndef SQLITE_OMIT_VIRTUALTABLE
   10363   Token sArg;                /* Complete text of a module argument */
   10364   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
   10365   int nVtabLock;             /* Number of virtual tables to lock */
   10366   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
   10367 #endif
   10368   int nHeight;            /* Expression tree height of current sub-select */
   10369   Table *pZombieTab;      /* List of Table objects to delete after code gen */
   10370   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
   10371 
   10372 #ifndef SQLITE_OMIT_EXPLAIN
   10373   int iSelectId;
   10374   int iNextSelectId;
   10375 #endif
   10376 };
   10377 
   10378 #ifdef SQLITE_OMIT_VIRTUALTABLE
   10379   #define IN_DECLARE_VTAB 0
   10380 #else
   10381   #define IN_DECLARE_VTAB (pParse->declareVtab)
   10382 #endif
   10383 
   10384 /*
   10385 ** An instance of the following structure can be declared on a stack and used
   10386 ** to save the Parse.zAuthContext value so that it can be restored later.
   10387 */
   10388 struct AuthContext {
   10389   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
   10390   Parse *pParse;              /* The Parse structure */
   10391 };
   10392 
   10393 /*
   10394 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
   10395 */
   10396 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
   10397 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
   10398 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
   10399 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
   10400 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
   10401 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
   10402 
   10403 /*
   10404  * Each trigger present in the database schema is stored as an instance of
   10405  * struct Trigger.
   10406  *
   10407  * Pointers to instances of struct Trigger are stored in two ways.
   10408  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
   10409  *    database). This allows Trigger structures to be retrieved by name.
   10410  * 2. All triggers associated with a single table form a linked list, using the
   10411  *    pNext member of struct Trigger. A pointer to the first element of the
   10412  *    linked list is stored as the "pTrigger" member of the associated
   10413  *    struct Table.
   10414  *
   10415  * The "step_list" member points to the first element of a linked list
   10416  * containing the SQL statements specified as the trigger program.
   10417  */
   10418 struct Trigger {
   10419   char *zName;            /* The name of the trigger                        */
   10420   char *table;            /* The table or view to which the trigger applies */
   10421   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
   10422   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   10423   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
   10424   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
   10425                              the <column-list> is stored here */
   10426   Schema *pSchema;        /* Schema containing the trigger */
   10427   Schema *pTabSchema;     /* Schema containing the table */
   10428   TriggerStep *step_list; /* Link list of trigger program steps             */
   10429   Trigger *pNext;         /* Next trigger associated with the table */
   10430 };
   10431 
   10432 /*
   10433 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
   10434 ** determine which.
   10435 **
   10436 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
   10437 ** In that cases, the constants below can be ORed together.
   10438 */
   10439 #define TRIGGER_BEFORE  1
   10440 #define TRIGGER_AFTER   2
   10441 
   10442 /*
   10443  * An instance of struct TriggerStep is used to store a single SQL statement
   10444  * that is a part of a trigger-program.
   10445  *
   10446  * Instances of struct TriggerStep are stored in a singly linked list (linked
   10447  * using the "pNext" member) referenced by the "step_list" member of the
   10448  * associated struct Trigger instance. The first element of the linked list is
   10449  * the first step of the trigger-program.
   10450  *
   10451  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
   10452  * "SELECT" statement. The meanings of the other members is determined by the
   10453  * value of "op" as follows:
   10454  *
   10455  * (op == TK_INSERT)
   10456  * orconf    -> stores the ON CONFLICT algorithm
   10457  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
   10458  *              this stores a pointer to the SELECT statement. Otherwise NULL.
   10459  * target    -> A token holding the quoted name of the table to insert into.
   10460  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
   10461  *              this stores values to be inserted. Otherwise NULL.
   10462  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
   10463  *              statement, then this stores the column-names to be
   10464  *              inserted into.
   10465  *
   10466  * (op == TK_DELETE)
   10467  * target    -> A token holding the quoted name of the table to delete from.
   10468  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
   10469  *              Otherwise NULL.
   10470  *
   10471  * (op == TK_UPDATE)
   10472  * target    -> A token holding the quoted name of the table to update rows of.
   10473  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
   10474  *              Otherwise NULL.
   10475  * pExprList -> A list of the columns to update and the expressions to update
   10476  *              them to. See sqlite3Update() documentation of "pChanges"
   10477  *              argument.
   10478  *
   10479  */
   10480 struct TriggerStep {
   10481   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
   10482   u8 orconf;           /* OE_Rollback etc. */
   10483   Trigger *pTrig;      /* The trigger that this step is a part of */
   10484   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
   10485   Token target;        /* Target table for DELETE, UPDATE, INSERT */
   10486   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   10487   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
   10488   IdList *pIdList;     /* Column names for INSERT */
   10489   TriggerStep *pNext;  /* Next in the link-list */
   10490   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
   10491 };
   10492 
   10493 /*
   10494 ** The following structure contains information used by the sqliteFix...
   10495 ** routines as they walk the parse tree to make database references
   10496 ** explicit.
   10497 */
   10498 typedef struct DbFixer DbFixer;
   10499 struct DbFixer {
   10500   Parse *pParse;      /* The parsing context.  Error messages written here */
   10501   const char *zDb;    /* Make sure all objects are contained in this database */
   10502   const char *zType;  /* Type of the container - used for error messages */
   10503   const Token *pName; /* Name of the container - used for error messages */
   10504 };
   10505 
   10506 /*
   10507 ** An objected used to accumulate the text of a string where we
   10508 ** do not necessarily know how big the string will be in the end.
   10509 */
   10510 struct StrAccum {
   10511   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
   10512   char *zBase;         /* A base allocation.  Not from malloc. */
   10513   char *zText;         /* The string collected so far */
   10514   int  nChar;          /* Length of the string so far */
   10515   int  nAlloc;         /* Amount of space allocated in zText */
   10516   int  mxAlloc;        /* Maximum allowed string length */
   10517   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
   10518   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
   10519   u8   tooBig;         /* Becomes true if string size exceeds limits */
   10520 };
   10521 
   10522 /*
   10523 ** A pointer to this structure is used to communicate information
   10524 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
   10525 */
   10526 typedef struct {
   10527   sqlite3 *db;        /* The database being initialized */
   10528   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
   10529   char **pzErrMsg;    /* Error message stored here */
   10530   int rc;             /* Result code stored here */
   10531 } InitData;
   10532 
   10533 /*
   10534 ** Structure containing global configuration data for the SQLite library.
   10535 **
   10536 ** This structure also contains some state information.
   10537 */
   10538 struct Sqlite3Config {
   10539   int bMemstat;                     /* True to enable memory status */
   10540   int bCoreMutex;                   /* True to enable core mutexing */
   10541   int bFullMutex;                   /* True to enable full mutexing */
   10542   int mxStrlen;                     /* Maximum string length */
   10543   int szLookaside;                  /* Default lookaside buffer size */
   10544   int nLookaside;                   /* Default lookaside buffer count */
   10545   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
   10546   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
   10547   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
   10548   void *pHeap;                      /* Heap storage space */
   10549   int nHeap;                        /* Size of pHeap[] */
   10550   int mnReq, mxReq;                 /* Min and max heap requests sizes */
   10551   void *pScratch;                   /* Scratch memory */
   10552   int szScratch;                    /* Size of each scratch buffer */
   10553   int nScratch;                     /* Number of scratch buffers */
   10554   void *pPage;                      /* Page cache memory */
   10555   int szPage;                       /* Size of each page in pPage[] */
   10556   int nPage;                        /* Number of pages in pPage[] */
   10557   int mxParserStack;                /* maximum depth of the parser stack */
   10558   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
   10559   /* The above might be initialized to non-zero.  The following need to always
   10560   ** initially be zero, however. */
   10561   int isInit;                       /* True after initialization has finished */
   10562   int inProgress;                   /* True while initialization in progress */
   10563   int isMutexInit;                  /* True after mutexes are initialized */
   10564   int isMallocInit;                 /* True after malloc is initialized */
   10565   int isPCacheInit;                 /* True after malloc is initialized */
   10566   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
   10567   int nRefInitMutex;                /* Number of users of pInitMutex */
   10568   void (*xLog)(void*,int,const char*); /* Function for logging */
   10569   void *pLogArg;                       /* First argument to xLog() */
   10570 };
   10571 
   10572 /*
   10573 ** Context pointer passed down through the tree-walk.
   10574 */
   10575 struct Walker {
   10576   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
   10577   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   10578   Parse *pParse;                            /* Parser context.  */
   10579   union {                                   /* Extra data for callback */
   10580     NameContext *pNC;                          /* Naming context */
   10581     int i;                                     /* Integer value */
   10582   } u;
   10583 };
   10584 
   10585 /* Forward declarations */
   10586 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
   10587 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
   10588 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
   10589 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
   10590 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
   10591 
   10592 /*
   10593 ** Return code from the parse-tree walking primitives and their
   10594 ** callbacks.
   10595 */
   10596 #define WRC_Continue    0   /* Continue down into children */
   10597 #define WRC_Prune       1   /* Omit children but continue walking siblings */
   10598 #define WRC_Abort       2   /* Abandon the tree walk */
   10599 
   10600 /*
   10601 ** Assuming zIn points to the first byte of a UTF-8 character,
   10602 ** advance zIn to point to the first byte of the next UTF-8 character.
   10603 */
   10604 #define SQLITE_SKIP_UTF8(zIn) {                        \
   10605   if( (*(zIn++))>=0xc0 ){                              \
   10606     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
   10607   }                                                    \
   10608 }
   10609 
   10610 /*
   10611 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
   10612 ** the same name but without the _BKPT suffix.  These macros invoke
   10613 ** routines that report the line-number on which the error originated
   10614 ** using sqlite3_log().  The routines also provide a convenient place
   10615 ** to set a debugger breakpoint.
   10616 */
   10617 SQLITE_PRIVATE int sqlite3CorruptError(int);
   10618 SQLITE_PRIVATE int sqlite3MisuseError(int);
   10619 SQLITE_PRIVATE int sqlite3CantopenError(int);
   10620 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
   10621 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
   10622 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
   10623 
   10624 
   10625 /*
   10626 ** FTS4 is really an extension for FTS3.  It is enabled using the
   10627 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
   10628 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
   10629 */
   10630 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
   10631 # define SQLITE_ENABLE_FTS3
   10632 #endif
   10633 
   10634 /*
   10635 ** The ctype.h header is needed for non-ASCII systems.  It is also
   10636 ** needed by FTS3 when FTS3 is included in the amalgamation.
   10637 */
   10638 #if !defined(SQLITE_ASCII) || \
   10639     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
   10640 # include <ctype.h>
   10641 #endif
   10642 
   10643 /*
   10644 ** The following macros mimic the standard library functions toupper(),
   10645 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
   10646 ** sqlite versions only work for ASCII characters, regardless of locale.
   10647 */
   10648 #ifdef SQLITE_ASCII
   10649 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
   10650 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
   10651 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
   10652 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
   10653 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
   10654 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
   10655 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
   10656 #else
   10657 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
   10658 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
   10659 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
   10660 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
   10661 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
   10662 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
   10663 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
   10664 #endif
   10665 
   10666 /*
   10667 ** Internal function prototypes
   10668 */
   10669 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
   10670 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
   10671 #define sqlite3StrNICmp sqlite3_strnicmp
   10672 
   10673 SQLITE_PRIVATE int sqlite3MallocInit(void);
   10674 SQLITE_PRIVATE void sqlite3MallocEnd(void);
   10675 SQLITE_PRIVATE void *sqlite3Malloc(int);
   10676 SQLITE_PRIVATE void *sqlite3MallocZero(int);
   10677 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
   10678 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
   10679 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
   10680 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
   10681 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
   10682 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
   10683 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
   10684 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
   10685 SQLITE_PRIVATE int sqlite3MallocSize(void*);
   10686 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
   10687 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
   10688 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
   10689 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
   10690 SQLITE_PRIVATE void sqlite3PageFree(void*);
   10691 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
   10692 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
   10693 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
   10694 
   10695 /*
   10696 ** On systems with ample stack space and that support alloca(), make
   10697 ** use of alloca() to obtain space for large automatic objects.  By default,
   10698 ** obtain space from malloc().
   10699 **
   10700 ** The alloca() routine never returns NULL.  This will cause code paths
   10701 ** that deal with sqlite3StackAlloc() failures to be unreachable.
   10702 */
   10703 #ifdef SQLITE_USE_ALLOCA
   10704 # define sqlite3StackAllocRaw(D,N)   alloca(N)
   10705 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
   10706 # define sqlite3StackFree(D,P)
   10707 #else
   10708 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
   10709 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
   10710 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
   10711 #endif
   10712 
   10713 #ifdef SQLITE_ENABLE_MEMSYS3
   10714 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
   10715 #endif
   10716 #ifdef SQLITE_ENABLE_MEMSYS5
   10717 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
   10718 #endif
   10719 
   10720 
   10721 #ifndef SQLITE_MUTEX_OMIT
   10722 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
   10723 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
   10724 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
   10725 SQLITE_PRIVATE   int sqlite3MutexInit(void);
   10726 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
   10727 #endif
   10728 
   10729 SQLITE_PRIVATE int sqlite3StatusValue(int);
   10730 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
   10731 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
   10732 
   10733 #ifndef SQLITE_OMIT_FLOATING_POINT
   10734 SQLITE_PRIVATE   int sqlite3IsNaN(double);
   10735 #else
   10736 # define sqlite3IsNaN(X)  0
   10737 #endif
   10738 
   10739 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
   10740 #ifndef SQLITE_OMIT_TRACE
   10741 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
   10742 #endif
   10743 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
   10744 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
   10745 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
   10746 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   10747 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
   10748 #endif
   10749 #if defined(SQLITE_TEST)
   10750 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
   10751 #endif
   10752 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
   10753 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
   10754 SQLITE_PRIVATE int sqlite3Dequote(char*);
   10755 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
   10756 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
   10757 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
   10758 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
   10759 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
   10760 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
   10761 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
   10762 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
   10763 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
   10764 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
   10765 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
   10766 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
   10767 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
   10768 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
   10769 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
   10770 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
   10771 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
   10772 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
   10773 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
   10774 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
   10775 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
   10776 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
   10777 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
   10778 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
   10779 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
   10780 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
   10781 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
   10782 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
   10783 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
   10784 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
   10785 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
   10786 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
   10787 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
   10788 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
   10789 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
   10790 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
   10791 
   10792 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
   10793 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
   10794 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
   10795 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
   10796 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
   10797 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
   10798 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
   10799 
   10800 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
   10801 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
   10802 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
   10803 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
   10804 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
   10805 
   10806 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
   10807 
   10808 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   10809 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
   10810 #else
   10811 # define sqlite3ViewGetColumnNames(A,B) 0
   10812 #endif
   10813 
   10814 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
   10815 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
   10816 #ifndef SQLITE_OMIT_AUTOINCREMENT
   10817 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
   10818 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
   10819 #else
   10820 # define sqlite3AutoincrementBegin(X)
   10821 # define sqlite3AutoincrementEnd(X)
   10822 #endif
   10823 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
   10824 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
   10825 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
   10826 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
   10827 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
   10828 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
   10829 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
   10830                                       Token*, Select*, Expr*, IdList*);
   10831 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
   10832 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
   10833 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
   10834 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
   10835 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
   10836 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
   10837 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
   10838                         Token*, int, int);
   10839 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
   10840 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
   10841 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
   10842                          Expr*,ExprList*,int,Expr*,Expr*);
   10843 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
   10844 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
   10845 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
   10846 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
   10847 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   10848 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
   10849 #endif
   10850 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
   10851 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
   10852 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
   10853 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
   10854 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
   10855 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
   10856 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
   10857 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
   10858 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
   10859 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
   10860 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
   10861 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
   10862 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
   10863 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
   10864 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
   10865 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
   10866 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
   10867 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
   10868 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
   10869 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
   10870 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
   10871 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
   10872 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
   10873 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
   10874 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
   10875 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
   10876 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
   10877 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
   10878 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
   10879 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
   10880 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
   10881 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
   10882 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
   10883 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
   10884 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
   10885 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
   10886 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
   10887 SQLITE_PRIVATE void sqlite3PrngResetState(void);
   10888 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
   10889 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
   10890 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
   10891 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
   10892 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
   10893 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
   10894 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
   10895 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
   10896 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
   10897 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
   10898 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
   10899 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
   10900 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
   10901 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
   10902 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
   10903 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
   10904 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
   10905 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
   10906 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
   10907                                      int*,int,int,int,int,int*);
   10908 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
   10909 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
   10910 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
   10911 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
   10912 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
   10913 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
   10914 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
   10915 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
   10916 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
   10917 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
   10918 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
   10919 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
   10920 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
   10921 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
   10922 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
   10923 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
   10924 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
   10925 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
   10926 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
   10927 
   10928 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   10929 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
   10930 #endif
   10931 
   10932 #ifndef SQLITE_OMIT_TRIGGER
   10933 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
   10934                            Expr*,int, int);
   10935 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
   10936 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
   10937 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
   10938 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
   10939 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
   10940 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
   10941                             int, int, int);
   10942 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
   10943   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
   10944 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
   10945 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
   10946 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
   10947                                         ExprList*,Select*,u8);
   10948 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
   10949 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
   10950 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
   10951 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
   10952 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
   10953 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
   10954 #else
   10955 # define sqlite3TriggersExist(B,C,D,E,F) 0
   10956 # define sqlite3DeleteTrigger(A,B)
   10957 # define sqlite3DropTriggerPtr(A,B)
   10958 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
   10959 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
   10960 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
   10961 # define sqlite3TriggerList(X, Y) 0
   10962 # define sqlite3ParseToplevel(p) p
   10963 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
   10964 #endif
   10965 
   10966 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
   10967 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
   10968 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
   10969 #ifndef SQLITE_OMIT_AUTHORIZATION
   10970 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
   10971 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
   10972 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
   10973 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
   10974 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
   10975 #else
   10976 # define sqlite3AuthRead(a,b,c,d)
   10977 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
   10978 # define sqlite3AuthContextPush(a,b,c)
   10979 # define sqlite3AuthContextPop(a)  ((void)(a))
   10980 #endif
   10981 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
   10982 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
   10983 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
   10984 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
   10985 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
   10986 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
   10987 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
   10988 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
   10989 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
   10990 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
   10991 SQLITE_PRIVATE int sqlite3Atoi(const char*);
   10992 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
   10993 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
   10994 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
   10995 
   10996 /*
   10997 ** Routines to read and write variable-length integers.  These used to
   10998 ** be defined locally, but now we use the varint routines in the util.c
   10999 ** file.  Code should use the MACRO forms below, as the Varint32 versions
   11000 ** are coded to assume the single byte case is already handled (which
   11001 ** the MACRO form does).
   11002 */
   11003 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
   11004 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
   11005 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
   11006 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
   11007 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
   11008 
   11009 /*
   11010 ** The header of a record consists of a sequence variable-length integers.
   11011 ** These integers are almost always small and are encoded as a single byte.
   11012 ** The following macros take advantage this fact to provide a fast encode
   11013 ** and decode of the integers in a record header.  It is faster for the common
   11014 ** case where the integer is a single byte.  It is a little slower when the
   11015 ** integer is two or more bytes.  But overall it is faster.
   11016 **
   11017 ** The following expressions are equivalent:
   11018 **
   11019 **     x = sqlite3GetVarint32( A, &B );
   11020 **     x = sqlite3PutVarint32( A, B );
   11021 **
   11022 **     x = getVarint32( A, B );
   11023 **     x = putVarint32( A, B );
   11024 **
   11025 */
   11026 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
   11027 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
   11028 #define getVarint    sqlite3GetVarint
   11029 #define putVarint    sqlite3PutVarint
   11030 
   11031 
   11032 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
   11033 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
   11034 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
   11035 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
   11036 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
   11037 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
   11038 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
   11039 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
   11040 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
   11041 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
   11042 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
   11043 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
   11044 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
   11045 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
   11046 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
   11047 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
   11048 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
   11049 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
   11050 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
   11051 
   11052 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
   11053 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
   11054 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
   11055                         void(*)(void*));
   11056 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
   11057 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
   11058 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
   11059 #ifdef SQLITE_ENABLE_STAT2
   11060 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
   11061 #endif
   11062 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
   11063 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
   11064 #ifndef SQLITE_AMALGAMATION
   11065 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
   11066 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
   11067 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
   11068 SQLITE_PRIVATE const Token sqlite3IntTokens[];
   11069 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
   11070 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   11071 #ifndef SQLITE_OMIT_WSD
   11072 SQLITE_PRIVATE int sqlite3PendingByte;
   11073 #endif
   11074 #endif
   11075 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
   11076 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
   11077 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
   11078 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
   11079 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
   11080 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
   11081 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
   11082 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
   11083 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
   11084 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
   11085 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
   11086 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
   11087 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
   11088 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
   11089 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
   11090 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
   11091 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
   11092 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
   11093 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
   11094 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
   11095 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
   11096 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
   11097 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
   11098 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
   11099 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
   11100 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
   11101 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
   11102 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
   11103 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
   11104 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
   11105 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
   11106 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   11107   void (*)(sqlite3_context*,int,sqlite3_value **),
   11108   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
   11109   FuncDestructor *pDestructor
   11110 );
   11111 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
   11112 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
   11113 
   11114 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
   11115 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
   11116 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
   11117 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
   11118 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
   11119 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
   11120 
   11121 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
   11122 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
   11123 
   11124 /*
   11125 ** The interface to the LEMON-generated parser
   11126 */
   11127 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
   11128 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
   11129 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
   11130 #ifdef YYTRACKMAXSTACKDEPTH
   11131 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
   11132 #endif
   11133 
   11134 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
   11135 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   11136 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
   11137 #else
   11138 # define sqlite3CloseExtensions(X)
   11139 #endif
   11140 
   11141 #ifndef SQLITE_OMIT_SHARED_CACHE
   11142 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
   11143 #else
   11144   #define sqlite3TableLock(v,w,x,y,z)
   11145 #endif
   11146 
   11147 #ifdef SQLITE_TEST
   11148 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
   11149 #endif
   11150 
   11151 #ifdef SQLITE_OMIT_VIRTUALTABLE
   11152 #  define sqlite3VtabClear(Y)
   11153 #  define sqlite3VtabSync(X,Y) SQLITE_OK
   11154 #  define sqlite3VtabRollback(X)
   11155 #  define sqlite3VtabCommit(X)
   11156 #  define sqlite3VtabInSync(db) 0
   11157 #  define sqlite3VtabLock(X)
   11158 #  define sqlite3VtabUnlock(X)
   11159 #  define sqlite3VtabUnlockList(X)
   11160 #else
   11161 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
   11162 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
   11163 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
   11164 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
   11165 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
   11166 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
   11167 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
   11168 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
   11169 #endif
   11170 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
   11171 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
   11172 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
   11173 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
   11174 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
   11175 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
   11176 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
   11177 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
   11178 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
   11179 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
   11180 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
   11181 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
   11182 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
   11183 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
   11184 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
   11185 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
   11186 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
   11187 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
   11188 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
   11189 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
   11190 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
   11191 
   11192 /* Declarations for functions in fkey.c. All of these are replaced by
   11193 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
   11194 ** key functionality is available. If OMIT_TRIGGER is defined but
   11195 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
   11196 ** this case foreign keys are parsed, but no other functionality is
   11197 ** provided (enforcement of FK constraints requires the triggers sub-system).
   11198 */
   11199 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   11200 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
   11201 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
   11202 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
   11203 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
   11204 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
   11205 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
   11206 #else
   11207   #define sqlite3FkActions(a,b,c,d)
   11208   #define sqlite3FkCheck(a,b,c,d)
   11209   #define sqlite3FkDropTable(a,b,c)
   11210   #define sqlite3FkOldmask(a,b)      0
   11211   #define sqlite3FkRequired(a,b,c,d) 0
   11212 #endif
   11213 #ifndef SQLITE_OMIT_FOREIGN_KEY
   11214 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
   11215 #else
   11216   #define sqlite3FkDelete(a,b)
   11217 #endif
   11218 
   11219 
   11220 /*
   11221 ** Available fault injectors.  Should be numbered beginning with 0.
   11222 */
   11223 #define SQLITE_FAULTINJECTOR_MALLOC     0
   11224 #define SQLITE_FAULTINJECTOR_COUNT      1
   11225 
   11226 /*
   11227 ** The interface to the code in fault.c used for identifying "benign"
   11228 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
   11229 ** is not defined.
   11230 */
   11231 #ifndef SQLITE_OMIT_BUILTIN_TEST
   11232 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
   11233 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
   11234 #else
   11235   #define sqlite3BeginBenignMalloc()
   11236   #define sqlite3EndBenignMalloc()
   11237 #endif
   11238 
   11239 #define IN_INDEX_ROWID           1
   11240 #define IN_INDEX_EPH             2
   11241 #define IN_INDEX_INDEX           3
   11242 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
   11243 
   11244 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   11245 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
   11246 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
   11247 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
   11248 #else
   11249   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
   11250 #endif
   11251 
   11252 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
   11253 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
   11254 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
   11255 
   11256 #if SQLITE_MAX_EXPR_DEPTH>0
   11257 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
   11258 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
   11259 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
   11260 #else
   11261   #define sqlite3ExprSetHeight(x,y)
   11262   #define sqlite3SelectExprHeight(x) 0
   11263   #define sqlite3ExprCheckHeight(x,y)
   11264 #endif
   11265 
   11266 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
   11267 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
   11268 
   11269 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   11270 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
   11271 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
   11272 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
   11273 #else
   11274   #define sqlite3ConnectionBlocked(x,y)
   11275   #define sqlite3ConnectionUnlocked(x)
   11276   #define sqlite3ConnectionClosed(x)
   11277 #endif
   11278 
   11279 #ifdef SQLITE_DEBUG
   11280 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
   11281 #endif
   11282 
   11283 /*
   11284 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
   11285 ** sqlite3IoTrace is a pointer to a printf-like routine used to
   11286 ** print I/O tracing messages.
   11287 */
   11288 #ifdef SQLITE_ENABLE_IOTRACE
   11289 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
   11290 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
   11291 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
   11292 #else
   11293 # define IOTRACE(A)
   11294 # define sqlite3VdbeIOTraceSql(X)
   11295 #endif
   11296 
   11297 /*
   11298 ** These routines are available for the mem2.c debugging memory allocator
   11299 ** only.  They are used to verify that different "types" of memory
   11300 ** allocations are properly tracked by the system.
   11301 **
   11302 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
   11303 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
   11304 ** a single bit set.
   11305 **
   11306 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
   11307 ** argument match the type set by the previous sqlite3MemdebugSetType().
   11308 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
   11309 **
   11310 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
   11311 ** argument match the type set by the previous sqlite3MemdebugSetType().
   11312 **
   11313 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
   11314 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
   11315 ** it might have been allocated by lookaside, except the allocation was
   11316 ** too large or lookaside was already full.  It is important to verify
   11317 ** that allocations that might have been satisfied by lookaside are not
   11318 ** passed back to non-lookaside free() routines.  Asserts such as the
   11319 ** example above are placed on the non-lookaside free() routines to verify
   11320 ** this constraint.
   11321 **
   11322 ** All of this is no-op for a production build.  It only comes into
   11323 ** play when the SQLITE_MEMDEBUG compile-time option is used.
   11324 */
   11325 #ifdef SQLITE_MEMDEBUG
   11326 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
   11327 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
   11328 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
   11329 #else
   11330 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
   11331 # define sqlite3MemdebugHasType(X,Y)  1
   11332 # define sqlite3MemdebugNoType(X,Y)   1
   11333 #endif
   11334 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
   11335 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
   11336 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
   11337 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
   11338 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
   11339 
   11340 #endif /* _SQLITEINT_H_ */
   11341 
   11342 /************** End of sqliteInt.h *******************************************/
   11343 /************** Begin file global.c ******************************************/
   11344 /*
   11345 ** 2008 June 13
   11346 **
   11347 ** The author disclaims copyright to this source code.  In place of
   11348 ** a legal notice, here is a blessing:
   11349 **
   11350 **    May you do good and not evil.
   11351 **    May you find forgiveness for yourself and forgive others.
   11352 **    May you share freely, never taking more than you give.
   11353 **
   11354 *************************************************************************
   11355 **
   11356 ** This file contains definitions of global variables and contants.
   11357 */
   11358 
   11359 /* An array to map all upper-case characters into their corresponding
   11360 ** lower-case character.
   11361 **
   11362 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
   11363 ** handle case conversions for the UTF character set since the tables
   11364 ** involved are nearly as big or bigger than SQLite itself.
   11365 */
   11366 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
   11367 #ifdef SQLITE_ASCII
   11368       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
   11369      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
   11370      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
   11371      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
   11372     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
   11373     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
   11374     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
   11375     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
   11376     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
   11377     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
   11378     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
   11379     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
   11380     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
   11381     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
   11382     252,253,254,255
   11383 #endif
   11384 #ifdef SQLITE_EBCDIC
   11385       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
   11386      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
   11387      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
   11388      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
   11389      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
   11390      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
   11391      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
   11392     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
   11393     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
   11394     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
   11395     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
   11396     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
   11397     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
   11398     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
   11399     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
   11400     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
   11401 #endif
   11402 };
   11403 
   11404 /*
   11405 ** The following 256 byte lookup table is used to support SQLites built-in
   11406 ** equivalents to the following standard library functions:
   11407 **
   11408 **   isspace()                        0x01
   11409 **   isalpha()                        0x02
   11410 **   isdigit()                        0x04
   11411 **   isalnum()                        0x06
   11412 **   isxdigit()                       0x08
   11413 **   toupper()                        0x20
   11414 **   SQLite identifier character      0x40
   11415 **
   11416 ** Bit 0x20 is set if the mapped character requires translation to upper
   11417 ** case. i.e. if the character is a lower-case ASCII character.
   11418 ** If x is a lower-case ASCII character, then its upper-case equivalent
   11419 ** is (x - 0x20). Therefore toupper() can be implemented as:
   11420 **
   11421 **   (x & ~(map[x]&0x20))
   11422 **
   11423 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
   11424 ** array. tolower() is used more often than toupper() by SQLite.
   11425 **
   11426 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
   11427 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
   11428 ** non-ASCII UTF character. Hence the test for whether or not a character is
   11429 ** part of an identifier is 0x46.
   11430 **
   11431 ** SQLite's versions are identical to the standard versions assuming a
   11432 ** locale of "C". They are implemented as macros in sqliteInt.h.
   11433 */
   11434 #ifdef SQLITE_ASCII
   11435 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   11436   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   11437   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
   11438   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
   11439   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
   11440   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
   11441   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
   11442   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
   11443   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
   11444 
   11445   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
   11446   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
   11447   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
   11448   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
   11449   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
   11450   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
   11451   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
   11452   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
   11453 
   11454   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
   11455   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
   11456   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
   11457   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
   11458   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
   11459   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
   11460   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
   11461   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
   11462 
   11463   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
   11464   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
   11465   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
   11466   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
   11467   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
   11468   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
   11469   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   11470   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
   11471 };
   11472 #endif
   11473 
   11474 
   11475 
   11476 /*
   11477 ** The following singleton contains the global configuration for
   11478 ** the SQLite library.
   11479 */
   11480 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   11481    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   11482    1,                         /* bCoreMutex */
   11483    SQLITE_THREADSAFE==1,      /* bFullMutex */
   11484    0x7ffffffe,                /* mxStrlen */
   11485    100,                       /* szLookaside */
   11486    500,                       /* nLookaside */
   11487    {0,0,0,0,0,0,0,0},         /* m */
   11488    {0,0,0,0,0,0,0,0,0},       /* mutex */
   11489    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
   11490    (void*)0,                  /* pHeap */
   11491    0,                         /* nHeap */
   11492    0, 0,                      /* mnHeap, mxHeap */
   11493    (void*)0,                  /* pScratch */
   11494    0,                         /* szScratch */
   11495    0,                         /* nScratch */
   11496    (void*)0,                  /* pPage */
   11497    0,                         /* szPage */
   11498    0,                         /* nPage */
   11499    0,                         /* mxParserStack */
   11500    0,                         /* sharedCacheEnabled */
   11501    /* All the rest should always be initialized to zero */
   11502    0,                         /* isInit */
   11503    0,                         /* inProgress */
   11504    0,                         /* isMutexInit */
   11505    0,                         /* isMallocInit */
   11506    0,                         /* isPCacheInit */
   11507    0,                         /* pInitMutex */
   11508    0,                         /* nRefInitMutex */
   11509    0,                         /* xLog */
   11510    0,                         /* pLogArg */
   11511 };
   11512 
   11513 
   11514 /*
   11515 ** Hash table for global functions - functions common to all
   11516 ** database connections.  After initialization, this table is
   11517 ** read-only.
   11518 */
   11519 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
   11520 
   11521 /*
   11522 ** Constant tokens for values 0 and 1.
   11523 */
   11524 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
   11525    { "0", 1 },
   11526    { "1", 1 }
   11527 };
   11528 
   11529 
   11530 /*
   11531 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
   11532 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
   11533 ** the database page that contains the pending byte.  It never attempts
   11534 ** to read or write that page.  The pending byte page is set assign
   11535 ** for use by the VFS layers as space for managing file locks.
   11536 **
   11537 ** During testing, it is often desirable to move the pending byte to
   11538 ** a different position in the file.  This allows code that has to
   11539 ** deal with the pending byte to run on files that are much smaller
   11540 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
   11541 ** move the pending byte.
   11542 **
   11543 ** IMPORTANT:  Changing the pending byte to any value other than
   11544 ** 0x40000000 results in an incompatible database file format!
   11545 ** Changing the pending byte during operating results in undefined
   11546 ** and dileterious behavior.
   11547 */
   11548 #ifndef SQLITE_OMIT_WSD
   11549 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
   11550 #endif
   11551 
   11552 /*
   11553 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
   11554 ** created by mkopcodeh.awk during compilation.  Data is obtained
   11555 ** from the comments following the "case OP_xxxx:" statements in
   11556 ** the vdbe.c file.
   11557 */
   11558 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
   11559 
   11560 /************** End of global.c **********************************************/
   11561 /************** Begin file ctime.c *******************************************/
   11562 /*
   11563 ** 2010 February 23
   11564 **
   11565 ** The author disclaims copyright to this source code.  In place of
   11566 ** a legal notice, here is a blessing:
   11567 **
   11568 **    May you do good and not evil.
   11569 **    May you find forgiveness for yourself and forgive others.
   11570 **    May you share freely, never taking more than you give.
   11571 **
   11572 *************************************************************************
   11573 **
   11574 ** This file implements routines used to report what compile-time options
   11575 ** SQLite was built with.
   11576 */
   11577 
   11578 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   11579 
   11580 
   11581 /*
   11582 ** An array of names of all compile-time options.  This array should
   11583 ** be sorted A-Z.
   11584 **
   11585 ** This array looks large, but in a typical installation actually uses
   11586 ** only a handful of compile-time options, so most times this array is usually
   11587 ** rather short and uses little memory space.
   11588 */
   11589 static const char * const azCompileOpt[] = {
   11590 
   11591 /* These macros are provided to "stringify" the value of the define
   11592 ** for those options in which the value is meaningful. */
   11593 #define CTIMEOPT_VAL_(opt) #opt
   11594 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
   11595 
   11596 #ifdef SQLITE_32BIT_ROWID
   11597   "32BIT_ROWID",
   11598 #endif
   11599 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
   11600   "4_BYTE_ALIGNED_MALLOC",
   11601 #endif
   11602 #ifdef SQLITE_CASE_SENSITIVE_LIKE
   11603   "CASE_SENSITIVE_LIKE",
   11604 #endif
   11605 #ifdef SQLITE_CHECK_PAGES
   11606   "CHECK_PAGES",
   11607 #endif
   11608 #ifdef SQLITE_COVERAGE_TEST
   11609   "COVERAGE_TEST",
   11610 #endif
   11611 #ifdef SQLITE_DEBUG
   11612   "DEBUG",
   11613 #endif
   11614 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   11615   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
   11616 #endif
   11617 #ifdef SQLITE_DISABLE_DIRSYNC
   11618   "DISABLE_DIRSYNC",
   11619 #endif
   11620 #ifdef SQLITE_DISABLE_LFS
   11621   "DISABLE_LFS",
   11622 #endif
   11623 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   11624   "ENABLE_ATOMIC_WRITE",
   11625 #endif
   11626 #ifdef SQLITE_ENABLE_CEROD
   11627   "ENABLE_CEROD",
   11628 #endif
   11629 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   11630   "ENABLE_COLUMN_METADATA",
   11631 #endif
   11632 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   11633   "ENABLE_EXPENSIVE_ASSERT",
   11634 #endif
   11635 #ifdef SQLITE_ENABLE_FTS1
   11636   "ENABLE_FTS1",
   11637 #endif
   11638 #ifdef SQLITE_ENABLE_FTS2
   11639   "ENABLE_FTS2",
   11640 #endif
   11641 #ifdef SQLITE_ENABLE_FTS3
   11642   "ENABLE_FTS3",
   11643 #endif
   11644 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   11645   "ENABLE_FTS3_PARENTHESIS",
   11646 #endif
   11647 #ifdef SQLITE_ENABLE_FTS4
   11648   "ENABLE_FTS4",
   11649 #endif
   11650 #ifdef SQLITE_ENABLE_ICU
   11651   "ENABLE_ICU",
   11652 #endif
   11653 #ifdef SQLITE_ENABLE_IOTRACE
   11654   "ENABLE_IOTRACE",
   11655 #endif
   11656 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   11657   "ENABLE_LOAD_EXTENSION",
   11658 #endif
   11659 #ifdef SQLITE_ENABLE_LOCKING_STYLE
   11660   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
   11661 #endif
   11662 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   11663   "ENABLE_MEMORY_MANAGEMENT",
   11664 #endif
   11665 #ifdef SQLITE_ENABLE_MEMSYS3
   11666   "ENABLE_MEMSYS3",
   11667 #endif
   11668 #ifdef SQLITE_ENABLE_MEMSYS5
   11669   "ENABLE_MEMSYS5",
   11670 #endif
   11671 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
   11672   "ENABLE_OVERSIZE_CELL_CHECK",
   11673 #endif
   11674 #ifdef SQLITE_ENABLE_RTREE
   11675   "ENABLE_RTREE",
   11676 #endif
   11677 #ifdef SQLITE_ENABLE_STAT2
   11678   "ENABLE_STAT2",
   11679 #endif
   11680 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   11681   "ENABLE_UNLOCK_NOTIFY",
   11682 #endif
   11683 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
   11684   "ENABLE_UPDATE_DELETE_LIMIT",
   11685 #endif
   11686 #ifdef SQLITE_HAS_CODEC
   11687   "HAS_CODEC",
   11688 #endif
   11689 #ifdef SQLITE_HAVE_ISNAN
   11690   "HAVE_ISNAN",
   11691 #endif
   11692 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   11693   "HOMEGROWN_RECURSIVE_MUTEX",
   11694 #endif
   11695 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   11696   "IGNORE_AFP_LOCK_ERRORS",
   11697 #endif
   11698 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   11699   "IGNORE_FLOCK_LOCK_ERRORS",
   11700 #endif
   11701 #ifdef SQLITE_INT64_TYPE
   11702   "INT64_TYPE",
   11703 #endif
   11704 #ifdef SQLITE_LOCK_TRACE
   11705   "LOCK_TRACE",
   11706 #endif
   11707 #ifdef SQLITE_MEMDEBUG
   11708   "MEMDEBUG",
   11709 #endif
   11710 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   11711   "MIXED_ENDIAN_64BIT_FLOAT",
   11712 #endif
   11713 #ifdef SQLITE_NO_SYNC
   11714   "NO_SYNC",
   11715 #endif
   11716 #ifdef SQLITE_OMIT_ALTERTABLE
   11717   "OMIT_ALTERTABLE",
   11718 #endif
   11719 #ifdef SQLITE_OMIT_ANALYZE
   11720   "OMIT_ANALYZE",
   11721 #endif
   11722 #ifdef SQLITE_OMIT_ATTACH
   11723   "OMIT_ATTACH",
   11724 #endif
   11725 #ifdef SQLITE_OMIT_AUTHORIZATION
   11726   "OMIT_AUTHORIZATION",
   11727 #endif
   11728 #ifdef SQLITE_OMIT_AUTOINCREMENT
   11729   "OMIT_AUTOINCREMENT",
   11730 #endif
   11731 #ifdef SQLITE_OMIT_AUTOINIT
   11732   "OMIT_AUTOINIT",
   11733 #endif
   11734 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
   11735   "OMIT_AUTOMATIC_INDEX",
   11736 #endif
   11737 #ifdef SQLITE_OMIT_AUTOVACUUM
   11738   "OMIT_AUTOVACUUM",
   11739 #endif
   11740 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   11741   "OMIT_BETWEEN_OPTIMIZATION",
   11742 #endif
   11743 #ifdef SQLITE_OMIT_BLOB_LITERAL
   11744   "OMIT_BLOB_LITERAL",
   11745 #endif
   11746 #ifdef SQLITE_OMIT_BTREECOUNT
   11747   "OMIT_BTREECOUNT",
   11748 #endif
   11749 #ifdef SQLITE_OMIT_BUILTIN_TEST
   11750   "OMIT_BUILTIN_TEST",
   11751 #endif
   11752 #ifdef SQLITE_OMIT_CAST
   11753   "OMIT_CAST",
   11754 #endif
   11755 #ifdef SQLITE_OMIT_CHECK
   11756   "OMIT_CHECK",
   11757 #endif
   11758 /* // redundant
   11759 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
   11760 **   "OMIT_COMPILEOPTION_DIAGS",
   11761 ** #endif
   11762 */
   11763 #ifdef SQLITE_OMIT_COMPLETE
   11764   "OMIT_COMPLETE",
   11765 #endif
   11766 #ifdef SQLITE_OMIT_COMPOUND_SELECT
   11767   "OMIT_COMPOUND_SELECT",
   11768 #endif
   11769 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   11770   "OMIT_DATETIME_FUNCS",
   11771 #endif
   11772 #ifdef SQLITE_OMIT_DECLTYPE
   11773   "OMIT_DECLTYPE",
   11774 #endif
   11775 #ifdef SQLITE_OMIT_DEPRECATED
   11776   "OMIT_DEPRECATED",
   11777 #endif
   11778 #ifdef SQLITE_OMIT_DISKIO
   11779   "OMIT_DISKIO",
   11780 #endif
   11781 #ifdef SQLITE_OMIT_EXPLAIN
   11782   "OMIT_EXPLAIN",
   11783 #endif
   11784 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
   11785   "OMIT_FLAG_PRAGMAS",
   11786 #endif
   11787 #ifdef SQLITE_OMIT_FLOATING_POINT
   11788   "OMIT_FLOATING_POINT",
   11789 #endif
   11790 #ifdef SQLITE_OMIT_FOREIGN_KEY
   11791   "OMIT_FOREIGN_KEY",
   11792 #endif
   11793 #ifdef SQLITE_OMIT_GET_TABLE
   11794   "OMIT_GET_TABLE",
   11795 #endif
   11796 #ifdef SQLITE_OMIT_INCRBLOB
   11797   "OMIT_INCRBLOB",
   11798 #endif
   11799 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
   11800   "OMIT_INTEGRITY_CHECK",
   11801 #endif
   11802 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
   11803   "OMIT_LIKE_OPTIMIZATION",
   11804 #endif
   11805 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   11806   "OMIT_LOAD_EXTENSION",
   11807 #endif
   11808 #ifdef SQLITE_OMIT_LOCALTIME
   11809   "OMIT_LOCALTIME",
   11810 #endif
   11811 #ifdef SQLITE_OMIT_LOOKASIDE
   11812   "OMIT_LOOKASIDE",
   11813 #endif
   11814 #ifdef SQLITE_OMIT_MEMORYDB
   11815   "OMIT_MEMORYDB",
   11816 #endif
   11817 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
   11818   "OMIT_OR_OPTIMIZATION",
   11819 #endif
   11820 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
   11821   "OMIT_PAGER_PRAGMAS",
   11822 #endif
   11823 #ifdef SQLITE_OMIT_PRAGMA
   11824   "OMIT_PRAGMA",
   11825 #endif
   11826 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   11827   "OMIT_PROGRESS_CALLBACK",
   11828 #endif
   11829 #ifdef SQLITE_OMIT_QUICKBALANCE
   11830   "OMIT_QUICKBALANCE",
   11831 #endif
   11832 #ifdef SQLITE_OMIT_REINDEX
   11833   "OMIT_REINDEX",
   11834 #endif
   11835 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
   11836   "OMIT_SCHEMA_PRAGMAS",
   11837 #endif
   11838 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   11839   "OMIT_SCHEMA_VERSION_PRAGMAS",
   11840 #endif
   11841 #ifdef SQLITE_OMIT_SHARED_CACHE
   11842   "OMIT_SHARED_CACHE",
   11843 #endif
   11844 #ifdef SQLITE_OMIT_SUBQUERY
   11845   "OMIT_SUBQUERY",
   11846 #endif
   11847 #ifdef SQLITE_OMIT_TCL_VARIABLE
   11848   "OMIT_TCL_VARIABLE",
   11849 #endif
   11850 #ifdef SQLITE_OMIT_TEMPDB
   11851   "OMIT_TEMPDB",
   11852 #endif
   11853 #ifdef SQLITE_OMIT_TRACE
   11854   "OMIT_TRACE",
   11855 #endif
   11856 #ifdef SQLITE_OMIT_TRIGGER
   11857   "OMIT_TRIGGER",
   11858 #endif
   11859 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   11860   "OMIT_TRUNCATE_OPTIMIZATION",
   11861 #endif
   11862 #ifdef SQLITE_OMIT_UTF16
   11863   "OMIT_UTF16",
   11864 #endif
   11865 #ifdef SQLITE_OMIT_VACUUM
   11866   "OMIT_VACUUM",
   11867 #endif
   11868 #ifdef SQLITE_OMIT_VIEW
   11869   "OMIT_VIEW",
   11870 #endif
   11871 #ifdef SQLITE_OMIT_VIRTUALTABLE
   11872   "OMIT_VIRTUALTABLE",
   11873 #endif
   11874 #ifdef SQLITE_OMIT_WAL
   11875   "OMIT_WAL",
   11876 #endif
   11877 #ifdef SQLITE_OMIT_WSD
   11878   "OMIT_WSD",
   11879 #endif
   11880 #ifdef SQLITE_OMIT_XFER_OPT
   11881   "OMIT_XFER_OPT",
   11882 #endif
   11883 #ifdef SQLITE_PERFORMANCE_TRACE
   11884   "PERFORMANCE_TRACE",
   11885 #endif
   11886 #ifdef SQLITE_PROXY_DEBUG
   11887   "PROXY_DEBUG",
   11888 #endif
   11889 #ifdef SQLITE_SECURE_DELETE
   11890   "SECURE_DELETE",
   11891 #endif
   11892 #ifdef SQLITE_SMALL_STACK
   11893   "SMALL_STACK",
   11894 #endif
   11895 #ifdef SQLITE_SOUNDEX
   11896   "SOUNDEX",
   11897 #endif
   11898 #ifdef SQLITE_TCL
   11899   "TCL",
   11900 #endif
   11901 #ifdef SQLITE_TEMP_STORE
   11902   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
   11903 #endif
   11904 #ifdef SQLITE_TEST
   11905   "TEST",
   11906 #endif
   11907 #ifdef SQLITE_THREADSAFE
   11908   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
   11909 #endif
   11910 #ifdef SQLITE_USE_ALLOCA
   11911   "USE_ALLOCA",
   11912 #endif
   11913 #ifdef SQLITE_ZERO_MALLOC
   11914   "ZERO_MALLOC"
   11915 #endif
   11916 };
   11917 
   11918 /*
   11919 ** Given the name of a compile-time option, return true if that option
   11920 ** was used and false if not.
   11921 **
   11922 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
   11923 ** is not required for a match.
   11924 */
   11925 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   11926   int i, n;
   11927   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   11928   n = sqlite3Strlen30(zOptName);
   11929 
   11930   /* Since ArraySize(azCompileOpt) is normally in single digits, a
   11931   ** linear search is adequate.  No need for a binary search. */
   11932   for(i=0; i<ArraySize(azCompileOpt); i++){
   11933     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
   11934        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
   11935   }
   11936   return 0;
   11937 }
   11938 
   11939 /*
   11940 ** Return the N-th compile-time option string.  If N is out of range,
   11941 ** return a NULL pointer.
   11942 */
   11943 SQLITE_API const char *sqlite3_compileoption_get(int N){
   11944   if( N>=0 && N<ArraySize(azCompileOpt) ){
   11945     return azCompileOpt[N];
   11946   }
   11947   return 0;
   11948 }
   11949 
   11950 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   11951 
   11952 /************** End of ctime.c ***********************************************/
   11953 /************** Begin file status.c ******************************************/
   11954 /*
   11955 ** 2008 June 18
   11956 **
   11957 ** The author disclaims copyright to this source code.  In place of
   11958 ** a legal notice, here is a blessing:
   11959 **
   11960 **    May you do good and not evil.
   11961 **    May you find forgiveness for yourself and forgive others.
   11962 **    May you share freely, never taking more than you give.
   11963 **
   11964 *************************************************************************
   11965 **
   11966 ** This module implements the sqlite3_status() interface and related
   11967 ** functionality.
   11968 */
   11969 /************** Include vdbeInt.h in the middle of status.c ******************/
   11970 /************** Begin file vdbeInt.h *****************************************/
   11971 /*
   11972 ** 2003 September 6
   11973 **
   11974 ** The author disclaims copyright to this source code.  In place of
   11975 ** a legal notice, here is a blessing:
   11976 **
   11977 **    May you do good and not evil.
   11978 **    May you find forgiveness for yourself and forgive others.
   11979 **    May you share freely, never taking more than you give.
   11980 **
   11981 *************************************************************************
   11982 ** This is the header file for information that is private to the
   11983 ** VDBE.  This information used to all be at the top of the single
   11984 ** source code file "vdbe.c".  When that file became too big (over
   11985 ** 6000 lines long) it was split up into several smaller files and
   11986 ** this header information was factored out.
   11987 */
   11988 #ifndef _VDBEINT_H_
   11989 #define _VDBEINT_H_
   11990 
   11991 /*
   11992 ** SQL is translated into a sequence of instructions to be
   11993 ** executed by a virtual machine.  Each instruction is an instance
   11994 ** of the following structure.
   11995 */
   11996 typedef struct VdbeOp Op;
   11997 
   11998 /*
   11999 ** Boolean values
   12000 */
   12001 typedef unsigned char Bool;
   12002 
   12003 /*
   12004 ** A cursor is a pointer into a single BTree within a database file.
   12005 ** The cursor can seek to a BTree entry with a particular key, or
   12006 ** loop over all entries of the Btree.  You can also insert new BTree
   12007 ** entries or retrieve the key or data from the entry that the cursor
   12008 ** is currently pointing to.
   12009 **
   12010 ** Every cursor that the virtual machine has open is represented by an
   12011 ** instance of the following structure.
   12012 **
   12013 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
   12014 ** really a single row that represents the NEW or OLD pseudo-table of
   12015 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
   12016 ** the rowid is in VdbeCursor.iKey.
   12017 */
   12018 struct VdbeCursor {
   12019   BtCursor *pCursor;    /* The cursor structure of the backend */
   12020   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
   12021   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
   12022   Bool zeroed;          /* True if zeroed out and ready for reuse */
   12023   Bool rowidIsValid;    /* True if lastRowid is valid */
   12024   Bool atFirst;         /* True if pointing to first entry */
   12025   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
   12026   Bool nullRow;         /* True if pointing to a row with no data */
   12027   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
   12028   Bool isTable;         /* True if a table requiring integer keys */
   12029   Bool isIndex;         /* True if an index containing keys only - no data */
   12030   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
   12031   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
   12032   Btree *pBt;           /* Separate file holding temporary table */
   12033   int pseudoTableReg;   /* Register holding pseudotable content. */
   12034   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
   12035   int nField;           /* Number of fields in the header */
   12036   i64 seqCount;         /* Sequence counter */
   12037   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
   12038   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
   12039 
   12040   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
   12041   ** OP_IsUnique opcode on this cursor. */
   12042   int seekResult;
   12043 
   12044   /* Cached information about the header for the data record that the
   12045   ** cursor is currently pointing to.  Only valid if cacheStatus matches
   12046   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
   12047   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
   12048   ** the cache is out of date.
   12049   **
   12050   ** aRow might point to (ephemeral) data for the current row, or it might
   12051   ** be NULL.
   12052   */
   12053   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
   12054   int payloadSize;      /* Total number of bytes in the record */
   12055   u32 *aType;           /* Type values for all entries in the record */
   12056   u32 *aOffset;         /* Cached offsets to the start of each columns data */
   12057   u8 *aRow;             /* Data for the current row, if all on one page */
   12058 };
   12059 typedef struct VdbeCursor VdbeCursor;
   12060 
   12061 /*
   12062 ** When a sub-program is executed (OP_Program), a structure of this type
   12063 ** is allocated to store the current value of the program counter, as
   12064 ** well as the current memory cell array and various other frame specific
   12065 ** values stored in the Vdbe struct. When the sub-program is finished,
   12066 ** these values are copied back to the Vdbe from the VdbeFrame structure,
   12067 ** restoring the state of the VM to as it was before the sub-program
   12068 ** began executing.
   12069 **
   12070 ** The memory for a VdbeFrame object is allocated and managed by a memory
   12071 ** cell in the parent (calling) frame. When the memory cell is deleted or
   12072 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
   12073 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
   12074 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
   12075 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
   12076 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
   12077 ** child frame are released.
   12078 **
   12079 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
   12080 ** set to NULL if the currently executing frame is the main program.
   12081 */
   12082 typedef struct VdbeFrame VdbeFrame;
   12083 struct VdbeFrame {
   12084   Vdbe *v;                /* VM this frame belongs to */
   12085   int pc;                 /* Program Counter in parent (calling) frame */
   12086   Op *aOp;                /* Program instructions for parent frame */
   12087   int nOp;                /* Size of aOp array */
   12088   Mem *aMem;              /* Array of memory cells for parent frame */
   12089   int nMem;               /* Number of entries in aMem */
   12090   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
   12091   u16 nCursor;            /* Number of entries in apCsr */
   12092   void *token;            /* Copy of SubProgram.token */
   12093   int nChildMem;          /* Number of memory cells for child frame */
   12094   int nChildCsr;          /* Number of cursors for child frame */
   12095   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
   12096   int nChange;            /* Statement changes (Vdbe.nChanges)     */
   12097   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
   12098 };
   12099 
   12100 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
   12101 
   12102 /*
   12103 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
   12104 */
   12105 #define CACHE_STALE 0
   12106 
   12107 /*
   12108 ** Internally, the vdbe manipulates nearly all SQL values as Mem
   12109 ** structures. Each Mem struct may cache multiple representations (string,
   12110 ** integer etc.) of the same value.  A value (and therefore Mem structure)
   12111 ** has the following properties:
   12112 **
   12113 ** Each value has a manifest type. The manifest type of the value stored
   12114 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
   12115 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
   12116 ** SQLITE_BLOB.
   12117 */
   12118 struct Mem {
   12119   union {
   12120     i64 i;              /* Integer value. */
   12121     int nZero;          /* Used when bit MEM_Zero is set in flags */
   12122     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
   12123     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
   12124     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
   12125   } u;
   12126   double r;           /* Real value */
   12127   sqlite3 *db;        /* The associated database connection */
   12128   char *z;            /* String or BLOB value */
   12129   int n;              /* Number of characters in string value, excluding '\0' */
   12130   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
   12131   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
   12132   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
   12133 #ifdef SQLITE_DEBUG
   12134   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
   12135   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
   12136 #endif
   12137   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
   12138   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
   12139 };
   12140 
   12141 /* One or more of the following flags are set to indicate the validOK
   12142 ** representations of the value stored in the Mem struct.
   12143 **
   12144 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
   12145 ** No other flags may be set in this case.
   12146 **
   12147 ** If the MEM_Str flag is set then Mem.z points at a string representation.
   12148 ** Usually this is encoded in the same unicode encoding as the main
   12149 ** database (see below for exceptions). If the MEM_Term flag is also
   12150 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
   12151 ** flags may coexist with the MEM_Str flag.
   12152 **
   12153 ** Multiple of these values can appear in Mem.flags.  But only one
   12154 ** at a time can appear in Mem.type.
   12155 */
   12156 #define MEM_Null      0x0001   /* Value is NULL */
   12157 #define MEM_Str       0x0002   /* Value is a string */
   12158 #define MEM_Int       0x0004   /* Value is an integer */
   12159 #define MEM_Real      0x0008   /* Value is a real number */
   12160 #define MEM_Blob      0x0010   /* Value is a BLOB */
   12161 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
   12162 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
   12163 #define MEM_Invalid   0x0080   /* Value is undefined */
   12164 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
   12165 
   12166 /* Whenever Mem contains a valid string or blob representation, one of
   12167 ** the following flags must be set to determine the memory management
   12168 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   12169 ** string is \000 or \u0000 terminated
   12170 */
   12171 #define MEM_Term      0x0200   /* String rep is nul terminated */
   12172 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
   12173 #define MEM_Static    0x0800   /* Mem.z points to a static string */
   12174 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   12175 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   12176 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   12177 #ifdef SQLITE_OMIT_INCRBLOB
   12178   #undef MEM_Zero
   12179   #define MEM_Zero 0x0000
   12180 #endif
   12181 
   12182 /*
   12183 ** Clear any existing type flags from a Mem and replace them with f
   12184 */
   12185 #define MemSetTypeFlag(p, f) \
   12186    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
   12187 
   12188 /*
   12189 ** Return true if a memory cell is not marked as invalid.  This macro
   12190 ** is for use inside assert() statements only.
   12191 */
   12192 #ifdef SQLITE_DEBUG
   12193 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
   12194 #endif
   12195 
   12196 
   12197 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
   12198 ** additional information about auxiliary information bound to arguments
   12199 ** of the function.  This is used to implement the sqlite3_get_auxdata()
   12200 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
   12201 ** that can be associated with a constant argument to a function.  This
   12202 ** allows functions such as "regexp" to compile their constant regular
   12203 ** expression argument once and reused the compiled code for multiple
   12204 ** invocations.
   12205 */
   12206 struct VdbeFunc {
   12207   FuncDef *pFunc;               /* The definition of the function */
   12208   int nAux;                     /* Number of entries allocated for apAux[] */
   12209   struct AuxData {
   12210     void *pAux;                   /* Aux data for the i-th argument */
   12211     void (*xDelete)(void *);      /* Destructor for the aux data */
   12212   } apAux[1];                   /* One slot for each function argument */
   12213 };
   12214 
   12215 /*
   12216 ** The "context" argument for a installable function.  A pointer to an
   12217 ** instance of this structure is the first argument to the routines used
   12218 ** implement the SQL functions.
   12219 **
   12220 ** There is a typedef for this structure in sqlite.h.  So all routines,
   12221 ** even the public interface to SQLite, can use a pointer to this structure.
   12222 ** But this file is the only place where the internal details of this
   12223 ** structure are known.
   12224 **
   12225 ** This structure is defined inside of vdbeInt.h because it uses substructures
   12226 ** (Mem) which are only defined there.
   12227 */
   12228 struct sqlite3_context {
   12229   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
   12230   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
   12231   Mem s;                /* The return value is stored here */
   12232   Mem *pMem;            /* Memory cell used to store aggregate context */
   12233   int isError;          /* Error code returned by the function. */
   12234   CollSeq *pColl;       /* Collating sequence */
   12235 };
   12236 
   12237 /*
   12238 ** A Set structure is used for quick testing to see if a value
   12239 ** is part of a small set.  Sets are used to implement code like
   12240 ** this:
   12241 **            x.y IN ('hi','hoo','hum')
   12242 */
   12243 typedef struct Set Set;
   12244 struct Set {
   12245   Hash hash;             /* A set is just a hash table */
   12246   HashElem *prev;        /* Previously accessed hash elemen */
   12247 };
   12248 
   12249 /*
   12250 ** An instance of the virtual machine.  This structure contains the complete
   12251 ** state of the virtual machine.
   12252 **
   12253 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
   12254 ** is really a pointer to an instance of this structure.
   12255 **
   12256 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
   12257 ** any virtual table method invocations made by the vdbe program. It is
   12258 ** set to 2 for xDestroy method calls and 1 for all other methods. This
   12259 ** variable is used for two purposes: to allow xDestroy methods to execute
   12260 ** "DROP TABLE" statements and to prevent some nasty side effects of
   12261 ** malloc failure when SQLite is invoked recursively by a virtual table
   12262 ** method function.
   12263 */
   12264 struct Vdbe {
   12265   sqlite3 *db;            /* The database connection that owns this statement */
   12266   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
   12267   int nOp;                /* Number of instructions in the program */
   12268   int nOpAlloc;           /* Number of slots allocated for aOp[] */
   12269   Op *aOp;                /* Space to hold the virtual machine's program */
   12270   int nLabel;             /* Number of labels used */
   12271   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
   12272   int *aLabel;            /* Space to hold the labels */
   12273   Mem **apArg;            /* Arguments to currently executing user function */
   12274   Mem *aColName;          /* Column names to return */
   12275   Mem *pResultSet;        /* Pointer to an array of results */
   12276   u16 nResColumn;         /* Number of columns in one row of the result set */
   12277   u16 nCursor;            /* Number of slots in apCsr[] */
   12278   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
   12279   u8 errorAction;         /* Recovery action to do in case of an error */
   12280   u8 okVar;               /* True if azVar[] has been initialized */
   12281   ynVar nVar;             /* Number of entries in aVar[] */
   12282   Mem *aVar;              /* Values for the OP_Variable opcode. */
   12283   char **azVar;           /* Name of variables */
   12284   u32 magic;              /* Magic number for sanity checking */
   12285   int nMem;               /* Number of memory locations currently allocated */
   12286   Mem *aMem;              /* The memory locations */
   12287   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
   12288   int pc;                 /* The program counter */
   12289   int rc;                 /* Value to return */
   12290   char *zErrMsg;          /* Error message written here */
   12291   u8 explain;             /* True if EXPLAIN present on SQL command */
   12292   u8 changeCntOn;         /* True to update the change-counter */
   12293   u8 expired;             /* True if the VM needs to be recompiled */
   12294   u8 runOnlyOnce;         /* Automatically expire on reset */
   12295   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   12296   u8 inVtabMethod;        /* See comments above */
   12297   u8 usesStmtJournal;     /* True if uses a statement journal */
   12298   u8 readOnly;            /* True for read-only statements */
   12299   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
   12300   int nChange;            /* Number of db changes made since last reset */
   12301   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
   12302   i64 startTime;          /* Time when query started - used for profiling */
   12303   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
   12304   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
   12305   char *zSql;             /* Text of the SQL statement that generated this */
   12306   void *pFree;            /* Free this when deleting the vdbe */
   12307   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
   12308   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
   12309   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
   12310 #ifdef SQLITE_DEBUG
   12311   FILE *trace;            /* Write an execution trace here, if not NULL */
   12312 #endif
   12313   VdbeFrame *pFrame;      /* Parent frame */
   12314   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
   12315   int nFrame;             /* Number of frames in pFrame list */
   12316   u32 expmask;            /* Binding to these vars invalidates VM */
   12317   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
   12318 };
   12319 
   12320 /*
   12321 ** The following are allowed values for Vdbe.magic
   12322 */
   12323 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
   12324 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
   12325 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
   12326 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
   12327 
   12328 /*
   12329 ** Function prototypes
   12330 */
   12331 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
   12332 void sqliteVdbePopStack(Vdbe*,int);
   12333 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
   12334 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
   12335 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
   12336 #endif
   12337 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
   12338 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
   12339 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
   12340 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   12341 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
   12342 
   12343 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   12344 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
   12345 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
   12346 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   12347 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
   12348 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
   12349 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
   12350 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
   12351 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
   12352 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
   12353 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
   12354 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
   12355 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
   12356 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
   12357 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
   12358 #ifdef SQLITE_OMIT_FLOATING_POINT
   12359 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
   12360 #else
   12361 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
   12362 #endif
   12363 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
   12364 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
   12365 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
   12366 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
   12367 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
   12368 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
   12369 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
   12370 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
   12371 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
   12372 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
   12373 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
   12374 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
   12375 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
   12376 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
   12377 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
   12378 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
   12379 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
   12380 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
   12381 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
   12382 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
   12383 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
   12384 
   12385 #ifdef SQLITE_DEBUG
   12386 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
   12387 #endif
   12388 
   12389 #ifndef SQLITE_OMIT_FOREIGN_KEY
   12390 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
   12391 #else
   12392 # define sqlite3VdbeCheckFk(p,i) 0
   12393 #endif
   12394 
   12395 #ifndef SQLITE_OMIT_SHARED_CACHE
   12396 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
   12397 #else
   12398 # define sqlite3VdbeMutexArrayEnter(p)
   12399 #endif
   12400 
   12401 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
   12402 #ifdef SQLITE_DEBUG
   12403 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
   12404 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
   12405 #endif
   12406 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
   12407 
   12408 #ifndef SQLITE_OMIT_INCRBLOB
   12409 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
   12410 #else
   12411   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
   12412 #endif
   12413 
   12414 #endif /* !defined(_VDBEINT_H_) */
   12415 
   12416 /************** End of vdbeInt.h *********************************************/
   12417 /************** Continuing where we left off in status.c *********************/
   12418 
   12419 /*
   12420 ** Variables in which to record status information.
   12421 */
   12422 typedef struct sqlite3StatType sqlite3StatType;
   12423 static SQLITE_WSD struct sqlite3StatType {
   12424   int nowValue[10];         /* Current value */
   12425   int mxValue[10];          /* Maximum value */
   12426 } sqlite3Stat = { {0,}, {0,} };
   12427 
   12428 
   12429 /* The "wsdStat" macro will resolve to the status information
   12430 ** state vector.  If writable static data is unsupported on the target,
   12431 ** we have to locate the state vector at run-time.  In the more common
   12432 ** case where writable static data is supported, wsdStat can refer directly
   12433 ** to the "sqlite3Stat" state vector declared above.
   12434 */
   12435 #ifdef SQLITE_OMIT_WSD
   12436 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
   12437 # define wsdStat x[0]
   12438 #else
   12439 # define wsdStatInit
   12440 # define wsdStat sqlite3Stat
   12441 #endif
   12442 
   12443 /*
   12444 ** Return the current value of a status parameter.
   12445 */
   12446 SQLITE_PRIVATE int sqlite3StatusValue(int op){
   12447   wsdStatInit;
   12448   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   12449   return wsdStat.nowValue[op];
   12450 }
   12451 
   12452 /*
   12453 ** Add N to the value of a status record.  It is assumed that the
   12454 ** caller holds appropriate locks.
   12455 */
   12456 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
   12457   wsdStatInit;
   12458   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   12459   wsdStat.nowValue[op] += N;
   12460   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   12461     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   12462   }
   12463 }
   12464 
   12465 /*
   12466 ** Set the value of a status to X.
   12467 */
   12468 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
   12469   wsdStatInit;
   12470   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
   12471   wsdStat.nowValue[op] = X;
   12472   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
   12473     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   12474   }
   12475 }
   12476 
   12477 /*
   12478 ** Query status information.
   12479 **
   12480 ** This implementation assumes that reading or writing an aligned
   12481 ** 32-bit integer is an atomic operation.  If that assumption is not true,
   12482 ** then this routine is not threadsafe.
   12483 */
   12484 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
   12485   wsdStatInit;
   12486   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
   12487     return SQLITE_MISUSE_BKPT;
   12488   }
   12489   *pCurrent = wsdStat.nowValue[op];
   12490   *pHighwater = wsdStat.mxValue[op];
   12491   if( resetFlag ){
   12492     wsdStat.mxValue[op] = wsdStat.nowValue[op];
   12493   }
   12494   return SQLITE_OK;
   12495 }
   12496 
   12497 /*
   12498 ** Query status information for a single database connection
   12499 */
   12500 SQLITE_API int sqlite3_db_status(
   12501   sqlite3 *db,          /* The database connection whose status is desired */
   12502   int op,               /* Status verb */
   12503   int *pCurrent,        /* Write current value here */
   12504   int *pHighwater,      /* Write high-water mark here */
   12505   int resetFlag         /* Reset high-water mark if true */
   12506 ){
   12507   int rc = SQLITE_OK;   /* Return code */
   12508   sqlite3_mutex_enter(db->mutex);
   12509   switch( op ){
   12510     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
   12511       *pCurrent = db->lookaside.nOut;
   12512       *pHighwater = db->lookaside.mxOut;
   12513       if( resetFlag ){
   12514         db->lookaside.mxOut = db->lookaside.nOut;
   12515       }
   12516       break;
   12517     }
   12518 
   12519     /*
   12520     ** Return an approximation for the amount of memory currently used
   12521     ** by all pagers associated with the given database connection.  The
   12522     ** highwater mark is meaningless and is returned as zero.
   12523     */
   12524     case SQLITE_DBSTATUS_CACHE_USED: {
   12525       int totalUsed = 0;
   12526       int i;
   12527       sqlite3BtreeEnterAll(db);
   12528       for(i=0; i<db->nDb; i++){
   12529         Btree *pBt = db->aDb[i].pBt;
   12530         if( pBt ){
   12531           Pager *pPager = sqlite3BtreePager(pBt);
   12532           totalUsed += sqlite3PagerMemUsed(pPager);
   12533         }
   12534       }
   12535       sqlite3BtreeLeaveAll(db);
   12536       *pCurrent = totalUsed;
   12537       *pHighwater = 0;
   12538       break;
   12539     }
   12540 
   12541     /*
   12542     ** *pCurrent gets an accurate estimate of the amount of memory used
   12543     ** to store the schema for all databases (main, temp, and any ATTACHed
   12544     ** databases.  *pHighwater is set to zero.
   12545     */
   12546     case SQLITE_DBSTATUS_SCHEMA_USED: {
   12547       int i;                      /* Used to iterate through schemas */
   12548       int nByte = 0;              /* Used to accumulate return value */
   12549 
   12550       db->pnBytesFreed = &nByte;
   12551       for(i=0; i<db->nDb; i++){
   12552         Schema *pSchema = db->aDb[i].pSchema;
   12553         if( ALWAYS(pSchema!=0) ){
   12554           HashElem *p;
   12555 
   12556           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
   12557               pSchema->tblHash.count
   12558             + pSchema->trigHash.count
   12559             + pSchema->idxHash.count
   12560             + pSchema->fkeyHash.count
   12561           );
   12562           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
   12563           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
   12564           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
   12565           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
   12566 
   12567           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
   12568             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
   12569           }
   12570           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
   12571             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
   12572           }
   12573         }
   12574       }
   12575       db->pnBytesFreed = 0;
   12576 
   12577       *pHighwater = 0;
   12578       *pCurrent = nByte;
   12579       break;
   12580     }
   12581 
   12582     /*
   12583     ** *pCurrent gets an accurate estimate of the amount of memory used
   12584     ** to store all prepared statements.
   12585     ** *pHighwater is set to zero.
   12586     */
   12587     case SQLITE_DBSTATUS_STMT_USED: {
   12588       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
   12589       int nByte = 0;              /* Used to accumulate return value */
   12590 
   12591       db->pnBytesFreed = &nByte;
   12592       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
   12593         sqlite3VdbeDeleteObject(db, pVdbe);
   12594       }
   12595       db->pnBytesFreed = 0;
   12596 
   12597       *pHighwater = 0;
   12598       *pCurrent = nByte;
   12599 
   12600       break;
   12601     }
   12602 
   12603     default: {
   12604       rc = SQLITE_ERROR;
   12605     }
   12606   }
   12607   sqlite3_mutex_leave(db->mutex);
   12608   return rc;
   12609 }
   12610 
   12611 /************** End of status.c **********************************************/
   12612 /************** Begin file date.c ********************************************/
   12613 /*
   12614 ** 2003 October 31
   12615 **
   12616 ** The author disclaims copyright to this source code.  In place of
   12617 ** a legal notice, here is a blessing:
   12618 **
   12619 **    May you do good and not evil.
   12620 **    May you find forgiveness for yourself and forgive others.
   12621 **    May you share freely, never taking more than you give.
   12622 **
   12623 *************************************************************************
   12624 ** This file contains the C functions that implement date and time
   12625 ** functions for SQLite.
   12626 **
   12627 ** There is only one exported symbol in this file - the function
   12628 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
   12629 ** All other code has file scope.
   12630 **
   12631 ** SQLite processes all times and dates as Julian Day numbers.  The
   12632 ** dates and times are stored as the number of days since noon
   12633 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
   12634 ** calendar system.
   12635 **
   12636 ** 1970-01-01 00:00:00 is JD 2440587.5
   12637 ** 2000-01-01 00:00:00 is JD 2451544.5
   12638 **
   12639 ** This implemention requires years to be expressed as a 4-digit number
   12640 ** which means that only dates between 0000-01-01 and 9999-12-31 can
   12641 ** be represented, even though julian day numbers allow a much wider
   12642 ** range of dates.
   12643 **
   12644 ** The Gregorian calendar system is used for all dates and times,
   12645 ** even those that predate the Gregorian calendar.  Historians usually
   12646 ** use the Julian calendar for dates prior to 1582-10-15 and for some
   12647 ** dates afterwards, depending on locale.  Beware of this difference.
   12648 **
   12649 ** The conversion algorithms are implemented based on descriptions
   12650 ** in the following text:
   12651 **
   12652 **      Jean Meeus
   12653 **      Astronomical Algorithms, 2nd Edition, 1998
   12654 **      ISBM 0-943396-61-1
   12655 **      Willmann-Bell, Inc
   12656 **      Richmond, Virginia (USA)
   12657 */
   12658 #include <time.h>
   12659 
   12660 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   12661 
   12662 /*
   12663 ** On recent Windows platforms, the localtime_s() function is available
   12664 ** as part of the "Secure CRT". It is essentially equivalent to
   12665 ** localtime_r() available under most POSIX platforms, except that the
   12666 ** order of the parameters is reversed.
   12667 **
   12668 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
   12669 **
   12670 ** If the user has not indicated to use localtime_r() or localtime_s()
   12671 ** already, check for an MSVC build environment that provides
   12672 ** localtime_s().
   12673 */
   12674 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
   12675      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
   12676 #define HAVE_LOCALTIME_S 1
   12677 #endif
   12678 
   12679 /*
   12680 ** A structure for holding a single date and time.
   12681 */
   12682 typedef struct DateTime DateTime;
   12683 struct DateTime {
   12684   sqlite3_int64 iJD; /* The julian day number times 86400000 */
   12685   int Y, M, D;       /* Year, month, and day */
   12686   int h, m;          /* Hour and minutes */
   12687   int tz;            /* Timezone offset in minutes */
   12688   double s;          /* Seconds */
   12689   char validYMD;     /* True (1) if Y,M,D are valid */
   12690   char validHMS;     /* True (1) if h,m,s are valid */
   12691   char validJD;      /* True (1) if iJD is valid */
   12692   char validTZ;      /* True (1) if tz is valid */
   12693 };
   12694 
   12695 
   12696 /*
   12697 ** Convert zDate into one or more integers.  Additional arguments
   12698 ** come in groups of 5 as follows:
   12699 **
   12700 **       N       number of digits in the integer
   12701 **       min     minimum allowed value of the integer
   12702 **       max     maximum allowed value of the integer
   12703 **       nextC   first character after the integer
   12704 **       pVal    where to write the integers value.
   12705 **
   12706 ** Conversions continue until one with nextC==0 is encountered.
   12707 ** The function returns the number of successful conversions.
   12708 */
   12709 static int getDigits(const char *zDate, ...){
   12710   va_list ap;
   12711   int val;
   12712   int N;
   12713   int min;
   12714   int max;
   12715   int nextC;
   12716   int *pVal;
   12717   int cnt = 0;
   12718   va_start(ap, zDate);
   12719   do{
   12720     N = va_arg(ap, int);
   12721     min = va_arg(ap, int);
   12722     max = va_arg(ap, int);
   12723     nextC = va_arg(ap, int);
   12724     pVal = va_arg(ap, int*);
   12725     val = 0;
   12726     while( N-- ){
   12727       if( !sqlite3Isdigit(*zDate) ){
   12728         goto end_getDigits;
   12729       }
   12730       val = val*10 + *zDate - '0';
   12731       zDate++;
   12732     }
   12733     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
   12734       goto end_getDigits;
   12735     }
   12736     *pVal = val;
   12737     zDate++;
   12738     cnt++;
   12739   }while( nextC );
   12740 end_getDigits:
   12741   va_end(ap);
   12742   return cnt;
   12743 }
   12744 
   12745 /*
   12746 ** Parse a timezone extension on the end of a date-time.
   12747 ** The extension is of the form:
   12748 **
   12749 **        (+/-)HH:MM
   12750 **
   12751 ** Or the "zulu" notation:
   12752 **
   12753 **        Z
   12754 **
   12755 ** If the parse is successful, write the number of minutes
   12756 ** of change in p->tz and return 0.  If a parser error occurs,
   12757 ** return non-zero.
   12758 **
   12759 ** A missing specifier is not considered an error.
   12760 */
   12761 static int parseTimezone(const char *zDate, DateTime *p){
   12762   int sgn = 0;
   12763   int nHr, nMn;
   12764   int c;
   12765   while( sqlite3Isspace(*zDate) ){ zDate++; }
   12766   p->tz = 0;
   12767   c = *zDate;
   12768   if( c=='-' ){
   12769     sgn = -1;
   12770   }else if( c=='+' ){
   12771     sgn = +1;
   12772   }else if( c=='Z' || c=='z' ){
   12773     zDate++;
   12774     goto zulu_time;
   12775   }else{
   12776     return c!=0;
   12777   }
   12778   zDate++;
   12779   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
   12780     return 1;
   12781   }
   12782   zDate += 5;
   12783   p->tz = sgn*(nMn + nHr*60);
   12784 zulu_time:
   12785   while( sqlite3Isspace(*zDate) ){ zDate++; }
   12786   return *zDate!=0;
   12787 }
   12788 
   12789 /*
   12790 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
   12791 ** The HH, MM, and SS must each be exactly 2 digits.  The
   12792 ** fractional seconds FFFF can be one or more digits.
   12793 **
   12794 ** Return 1 if there is a parsing error and 0 on success.
   12795 */
   12796 static int parseHhMmSs(const char *zDate, DateTime *p){
   12797   int h, m, s;
   12798   double ms = 0.0;
   12799   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
   12800     return 1;
   12801   }
   12802   zDate += 5;
   12803   if( *zDate==':' ){
   12804     zDate++;
   12805     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
   12806       return 1;
   12807     }
   12808     zDate += 2;
   12809     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
   12810       double rScale = 1.0;
   12811       zDate++;
   12812       while( sqlite3Isdigit(*zDate) ){
   12813         ms = ms*10.0 + *zDate - '0';
   12814         rScale *= 10.0;
   12815         zDate++;
   12816       }
   12817       ms /= rScale;
   12818     }
   12819   }else{
   12820     s = 0;
   12821   }
   12822   p->validJD = 0;
   12823   p->validHMS = 1;
   12824   p->h = h;
   12825   p->m = m;
   12826   p->s = s + ms;
   12827   if( parseTimezone(zDate, p) ) return 1;
   12828   p->validTZ = (p->tz!=0)?1:0;
   12829   return 0;
   12830 }
   12831 
   12832 /*
   12833 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
   12834 ** that the YYYY-MM-DD is according to the Gregorian calendar.
   12835 **
   12836 ** Reference:  Meeus page 61
   12837 */
   12838 static void computeJD(DateTime *p){
   12839   int Y, M, D, A, B, X1, X2;
   12840 
   12841   if( p->validJD ) return;
   12842   if( p->validYMD ){
   12843     Y = p->Y;
   12844     M = p->M;
   12845     D = p->D;
   12846   }else{
   12847     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
   12848     M = 1;
   12849     D = 1;
   12850   }
   12851   if( M<=2 ){
   12852     Y--;
   12853     M += 12;
   12854   }
   12855   A = Y/100;
   12856   B = 2 - A + (A/4);
   12857   X1 = 36525*(Y+4716)/100;
   12858   X2 = 306001*(M+1)/10000;
   12859   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
   12860   p->validJD = 1;
   12861   if( p->validHMS ){
   12862     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
   12863     if( p->validTZ ){
   12864       p->iJD -= p->tz*60000;
   12865       p->validYMD = 0;
   12866       p->validHMS = 0;
   12867       p->validTZ = 0;
   12868     }
   12869   }
   12870 }
   12871 
   12872 /*
   12873 ** Parse dates of the form
   12874 **
   12875 **     YYYY-MM-DD HH:MM:SS.FFF
   12876 **     YYYY-MM-DD HH:MM:SS
   12877 **     YYYY-MM-DD HH:MM
   12878 **     YYYY-MM-DD
   12879 **
   12880 ** Write the result into the DateTime structure and return 0
   12881 ** on success and 1 if the input string is not a well-formed
   12882 ** date.
   12883 */
   12884 static int parseYyyyMmDd(const char *zDate, DateTime *p){
   12885   int Y, M, D, neg;
   12886 
   12887   if( zDate[0]=='-' ){
   12888     zDate++;
   12889     neg = 1;
   12890   }else{
   12891     neg = 0;
   12892   }
   12893   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
   12894     return 1;
   12895   }
   12896   zDate += 10;
   12897   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
   12898   if( parseHhMmSs(zDate, p)==0 ){
   12899     /* We got the time */
   12900   }else if( *zDate==0 ){
   12901     p->validHMS = 0;
   12902   }else{
   12903     return 1;
   12904   }
   12905   p->validJD = 0;
   12906   p->validYMD = 1;
   12907   p->Y = neg ? -Y : Y;
   12908   p->M = M;
   12909   p->D = D;
   12910   if( p->validTZ ){
   12911     computeJD(p);
   12912   }
   12913   return 0;
   12914 }
   12915 
   12916 /*
   12917 ** Set the time to the current time reported by the VFS
   12918 */
   12919 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
   12920   sqlite3 *db = sqlite3_context_db_handle(context);
   12921   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
   12922   p->validJD = 1;
   12923 }
   12924 
   12925 /*
   12926 ** Attempt to parse the given string into a Julian Day Number.  Return
   12927 ** the number of errors.
   12928 **
   12929 ** The following are acceptable forms for the input string:
   12930 **
   12931 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
   12932 **      DDDD.DD
   12933 **      now
   12934 **
   12935 ** In the first form, the +/-HH:MM is always optional.  The fractional
   12936 ** seconds extension (the ".FFF") is optional.  The seconds portion
   12937 ** (":SS.FFF") is option.  The year and date can be omitted as long
   12938 ** as there is a time string.  The time string can be omitted as long
   12939 ** as there is a year and date.
   12940 */
   12941 static int parseDateOrTime(
   12942   sqlite3_context *context,
   12943   const char *zDate,
   12944   DateTime *p
   12945 ){
   12946   double r;
   12947   if( parseYyyyMmDd(zDate,p)==0 ){
   12948     return 0;
   12949   }else if( parseHhMmSs(zDate, p)==0 ){
   12950     return 0;
   12951   }else if( sqlite3StrICmp(zDate,"now")==0){
   12952     setDateTimeToCurrent(context, p);
   12953     return 0;
   12954   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
   12955     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
   12956     p->validJD = 1;
   12957     return 0;
   12958   }
   12959   return 1;
   12960 }
   12961 
   12962 /*
   12963 ** Compute the Year, Month, and Day from the julian day number.
   12964 */
   12965 static void computeYMD(DateTime *p){
   12966   int Z, A, B, C, D, E, X1;
   12967   if( p->validYMD ) return;
   12968   if( !p->validJD ){
   12969     p->Y = 2000;
   12970     p->M = 1;
   12971     p->D = 1;
   12972   }else{
   12973     Z = (int)((p->iJD + 43200000)/86400000);
   12974     A = (int)((Z - 1867216.25)/36524.25);
   12975     A = Z + 1 + A - (A/4);
   12976     B = A + 1524;
   12977     C = (int)((B - 122.1)/365.25);
   12978     D = (36525*C)/100;
   12979     E = (int)((B-D)/30.6001);
   12980     X1 = (int)(30.6001*E);
   12981     p->D = B - D - X1;
   12982     p->M = E<14 ? E-1 : E-13;
   12983     p->Y = p->M>2 ? C - 4716 : C - 4715;
   12984   }
   12985   p->validYMD = 1;
   12986 }
   12987 
   12988 /*
   12989 ** Compute the Hour, Minute, and Seconds from the julian day number.
   12990 */
   12991 static void computeHMS(DateTime *p){
   12992   int s;
   12993   if( p->validHMS ) return;
   12994   computeJD(p);
   12995   s = (int)((p->iJD + 43200000) % 86400000);
   12996   p->s = s/1000.0;
   12997   s = (int)p->s;
   12998   p->s -= s;
   12999   p->h = s/3600;
   13000   s -= p->h*3600;
   13001   p->m = s/60;
   13002   p->s += s - p->m*60;
   13003   p->validHMS = 1;
   13004 }
   13005 
   13006 /*
   13007 ** Compute both YMD and HMS
   13008 */
   13009 static void computeYMD_HMS(DateTime *p){
   13010   computeYMD(p);
   13011   computeHMS(p);
   13012 }
   13013 
   13014 /*
   13015 ** Clear the YMD and HMS and the TZ
   13016 */
   13017 static void clearYMD_HMS_TZ(DateTime *p){
   13018   p->validYMD = 0;
   13019   p->validHMS = 0;
   13020   p->validTZ = 0;
   13021 }
   13022 
   13023 #ifndef SQLITE_OMIT_LOCALTIME
   13024 /*
   13025 ** Compute the difference (in milliseconds)
   13026 ** between localtime and UTC (a.k.a. GMT)
   13027 ** for the time value p where p is in UTC.
   13028 */
   13029 static sqlite3_int64 localtimeOffset(DateTime *p){
   13030   DateTime x, y;
   13031   time_t t;
   13032   x = *p;
   13033   computeYMD_HMS(&x);
   13034   if( x.Y<1971 || x.Y>=2038 ){
   13035     x.Y = 2000;
   13036     x.M = 1;
   13037     x.D = 1;
   13038     x.h = 0;
   13039     x.m = 0;
   13040     x.s = 0.0;
   13041   } else {
   13042     int s = (int)(x.s + 0.5);
   13043     x.s = s;
   13044   }
   13045   x.tz = 0;
   13046   x.validJD = 0;
   13047   computeJD(&x);
   13048   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
   13049 #ifdef HAVE_LOCALTIME_R
   13050   {
   13051     struct tm sLocal;
   13052     localtime_r(&t, &sLocal);
   13053     y.Y = sLocal.tm_year + 1900;
   13054     y.M = sLocal.tm_mon + 1;
   13055     y.D = sLocal.tm_mday;
   13056     y.h = sLocal.tm_hour;
   13057     y.m = sLocal.tm_min;
   13058     y.s = sLocal.tm_sec;
   13059   }
   13060 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
   13061   {
   13062     struct tm sLocal;
   13063     localtime_s(&sLocal, &t);
   13064     y.Y = sLocal.tm_year + 1900;
   13065     y.M = sLocal.tm_mon + 1;
   13066     y.D = sLocal.tm_mday;
   13067     y.h = sLocal.tm_hour;
   13068     y.m = sLocal.tm_min;
   13069     y.s = sLocal.tm_sec;
   13070   }
   13071 #else
   13072   {
   13073     struct tm *pTm;
   13074     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   13075     pTm = localtime(&t);
   13076     y.Y = pTm->tm_year + 1900;
   13077     y.M = pTm->tm_mon + 1;
   13078     y.D = pTm->tm_mday;
   13079     y.h = pTm->tm_hour;
   13080     y.m = pTm->tm_min;
   13081     y.s = pTm->tm_sec;
   13082     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   13083   }
   13084 #endif
   13085   y.validYMD = 1;
   13086   y.validHMS = 1;
   13087   y.validJD = 0;
   13088   y.validTZ = 0;
   13089   computeJD(&y);
   13090   return y.iJD - x.iJD;
   13091 }
   13092 #endif /* SQLITE_OMIT_LOCALTIME */
   13093 
   13094 /*
   13095 ** Process a modifier to a date-time stamp.  The modifiers are
   13096 ** as follows:
   13097 **
   13098 **     NNN days
   13099 **     NNN hours
   13100 **     NNN minutes
   13101 **     NNN.NNNN seconds
   13102 **     NNN months
   13103 **     NNN years
   13104 **     start of month
   13105 **     start of year
   13106 **     start of week
   13107 **     start of day
   13108 **     weekday N
   13109 **     unixepoch
   13110 **     localtime
   13111 **     utc
   13112 **
   13113 ** Return 0 on success and 1 if there is any kind of error.
   13114 */
   13115 static int parseModifier(const char *zMod, DateTime *p){
   13116   int rc = 1;
   13117   int n;
   13118   double r;
   13119   char *z, zBuf[30];
   13120   z = zBuf;
   13121   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
   13122     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
   13123   }
   13124   z[n] = 0;
   13125   switch( z[0] ){
   13126 #ifndef SQLITE_OMIT_LOCALTIME
   13127     case 'l': {
   13128       /*    localtime
   13129       **
   13130       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
   13131       ** show local time.
   13132       */
   13133       if( strcmp(z, "localtime")==0 ){
   13134         computeJD(p);
   13135         p->iJD += localtimeOffset(p);
   13136         clearYMD_HMS_TZ(p);
   13137         rc = 0;
   13138       }
   13139       break;
   13140     }
   13141 #endif
   13142     case 'u': {
   13143       /*
   13144       **    unixepoch
   13145       **
   13146       ** Treat the current value of p->iJD as the number of
   13147       ** seconds since 1970.  Convert to a real julian day number.
   13148       */
   13149       if( strcmp(z, "unixepoch")==0 && p->validJD ){
   13150         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
   13151         clearYMD_HMS_TZ(p);
   13152         rc = 0;
   13153       }
   13154 #ifndef SQLITE_OMIT_LOCALTIME
   13155       else if( strcmp(z, "utc")==0 ){
   13156         sqlite3_int64 c1;
   13157         computeJD(p);
   13158         c1 = localtimeOffset(p);
   13159         p->iJD -= c1;
   13160         clearYMD_HMS_TZ(p);
   13161         p->iJD += c1 - localtimeOffset(p);
   13162         rc = 0;
   13163       }
   13164 #endif
   13165       break;
   13166     }
   13167     case 'w': {
   13168       /*
   13169       **    weekday N
   13170       **
   13171       ** Move the date to the same time on the next occurrence of
   13172       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
   13173       ** date is already on the appropriate weekday, this is a no-op.
   13174       */
   13175       if( strncmp(z, "weekday ", 8)==0
   13176                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
   13177                && (n=(int)r)==r && n>=0 && r<7 ){
   13178         sqlite3_int64 Z;
   13179         computeYMD_HMS(p);
   13180         p->validTZ = 0;
   13181         p->validJD = 0;
   13182         computeJD(p);
   13183         Z = ((p->iJD + 129600000)/86400000) % 7;
   13184         if( Z>n ) Z -= 7;
   13185         p->iJD += (n - Z)*86400000;
   13186         clearYMD_HMS_TZ(p);
   13187         rc = 0;
   13188       }
   13189       break;
   13190     }
   13191     case 's': {
   13192       /*
   13193       **    start of TTTTT
   13194       **
   13195       ** Move the date backwards to the beginning of the current day,
   13196       ** or month or year.
   13197       */
   13198       if( strncmp(z, "start of ", 9)!=0 ) break;
   13199       z += 9;
   13200       computeYMD(p);
   13201       p->validHMS = 1;
   13202       p->h = p->m = 0;
   13203       p->s = 0.0;
   13204       p->validTZ = 0;
   13205       p->validJD = 0;
   13206       if( strcmp(z,"month")==0 ){
   13207         p->D = 1;
   13208         rc = 0;
   13209       }else if( strcmp(z,"year")==0 ){
   13210         computeYMD(p);
   13211         p->M = 1;
   13212         p->D = 1;
   13213         rc = 0;
   13214       }else if( strcmp(z,"day")==0 ){
   13215         rc = 0;
   13216       }
   13217       break;
   13218     }
   13219     case '+':
   13220     case '-':
   13221     case '0':
   13222     case '1':
   13223     case '2':
   13224     case '3':
   13225     case '4':
   13226     case '5':
   13227     case '6':
   13228     case '7':
   13229     case '8':
   13230     case '9': {
   13231       double rRounder;
   13232       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
   13233       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
   13234         rc = 1;
   13235         break;
   13236       }
   13237       if( z[n]==':' ){
   13238         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
   13239         ** specified number of hours, minutes, seconds, and fractional seconds
   13240         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
   13241         ** omitted.
   13242         */
   13243         const char *z2 = z;
   13244         DateTime tx;
   13245         sqlite3_int64 day;
   13246         if( !sqlite3Isdigit(*z2) ) z2++;
   13247         memset(&tx, 0, sizeof(tx));
   13248         if( parseHhMmSs(z2, &tx) ) break;
   13249         computeJD(&tx);
   13250         tx.iJD -= 43200000;
   13251         day = tx.iJD/86400000;
   13252         tx.iJD -= day*86400000;
   13253         if( z[0]=='-' ) tx.iJD = -tx.iJD;
   13254         computeJD(p);
   13255         clearYMD_HMS_TZ(p);
   13256         p->iJD += tx.iJD;
   13257         rc = 0;
   13258         break;
   13259       }
   13260       z += n;
   13261       while( sqlite3Isspace(*z) ) z++;
   13262       n = sqlite3Strlen30(z);
   13263       if( n>10 || n<3 ) break;
   13264       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
   13265       computeJD(p);
   13266       rc = 0;
   13267       rRounder = r<0 ? -0.5 : +0.5;
   13268       if( n==3 && strcmp(z,"day")==0 ){
   13269         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
   13270       }else if( n==4 && strcmp(z,"hour")==0 ){
   13271         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
   13272       }else if( n==6 && strcmp(z,"minute")==0 ){
   13273         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
   13274       }else if( n==6 && strcmp(z,"second")==0 ){
   13275         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
   13276       }else if( n==5 && strcmp(z,"month")==0 ){
   13277         int x, y;
   13278         computeYMD_HMS(p);
   13279         p->M += (int)r;
   13280         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
   13281         p->Y += x;
   13282         p->M -= x*12;
   13283         p->validJD = 0;
   13284         computeJD(p);
   13285         y = (int)r;
   13286         if( y!=r ){
   13287           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
   13288         }
   13289       }else if( n==4 && strcmp(z,"year")==0 ){
   13290         int y = (int)r;
   13291         computeYMD_HMS(p);
   13292         p->Y += y;
   13293         p->validJD = 0;
   13294         computeJD(p);
   13295         if( y!=r ){
   13296           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
   13297         }
   13298       }else{
   13299         rc = 1;
   13300       }
   13301       clearYMD_HMS_TZ(p);
   13302       break;
   13303     }
   13304     default: {
   13305       break;
   13306     }
   13307   }
   13308   return rc;
   13309 }
   13310 
   13311 /*
   13312 ** Process time function arguments.  argv[0] is a date-time stamp.
   13313 ** argv[1] and following are modifiers.  Parse them all and write
   13314 ** the resulting time into the DateTime structure p.  Return 0
   13315 ** on success and 1 if there are any errors.
   13316 **
   13317 ** If there are zero parameters (if even argv[0] is undefined)
   13318 ** then assume a default value of "now" for argv[0].
   13319 */
   13320 static int isDate(
   13321   sqlite3_context *context,
   13322   int argc,
   13323   sqlite3_value **argv,
   13324   DateTime *p
   13325 ){
   13326   int i;
   13327   const unsigned char *z;
   13328   int eType;
   13329   memset(p, 0, sizeof(*p));
   13330   if( argc==0 ){
   13331     setDateTimeToCurrent(context, p);
   13332   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
   13333                    || eType==SQLITE_INTEGER ){
   13334     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
   13335     p->validJD = 1;
   13336   }else{
   13337     z = sqlite3_value_text(argv[0]);
   13338     if( !z || parseDateOrTime(context, (char*)z, p) ){
   13339       return 1;
   13340     }
   13341   }
   13342   for(i=1; i<argc; i++){
   13343     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
   13344       return 1;
   13345     }
   13346   }
   13347   return 0;
   13348 }
   13349 
   13350 
   13351 /*
   13352 ** The following routines implement the various date and time functions
   13353 ** of SQLite.
   13354 */
   13355 
   13356 /*
   13357 **    julianday( TIMESTRING, MOD, MOD, ...)
   13358 **
   13359 ** Return the julian day number of the date specified in the arguments
   13360 */
   13361 static void juliandayFunc(
   13362   sqlite3_context *context,
   13363   int argc,
   13364   sqlite3_value **argv
   13365 ){
   13366   DateTime x;
   13367   if( isDate(context, argc, argv, &x)==0 ){
   13368     computeJD(&x);
   13369     sqlite3_result_double(context, x.iJD/86400000.0);
   13370   }
   13371 }
   13372 
   13373 /*
   13374 **    datetime( TIMESTRING, MOD, MOD, ...)
   13375 **
   13376 ** Return YYYY-MM-DD HH:MM:SS
   13377 */
   13378 static void datetimeFunc(
   13379   sqlite3_context *context,
   13380   int argc,
   13381   sqlite3_value **argv
   13382 ){
   13383   DateTime x;
   13384   if( isDate(context, argc, argv, &x)==0 ){
   13385     char zBuf[100];
   13386     computeYMD_HMS(&x);
   13387     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
   13388                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
   13389     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   13390   }
   13391 }
   13392 
   13393 /*
   13394 **    time( TIMESTRING, MOD, MOD, ...)
   13395 **
   13396 ** Return HH:MM:SS
   13397 */
   13398 static void timeFunc(
   13399   sqlite3_context *context,
   13400   int argc,
   13401   sqlite3_value **argv
   13402 ){
   13403   DateTime x;
   13404   if( isDate(context, argc, argv, &x)==0 ){
   13405     char zBuf[100];
   13406     computeHMS(&x);
   13407     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
   13408     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   13409   }
   13410 }
   13411 
   13412 /*
   13413 **    date( TIMESTRING, MOD, MOD, ...)
   13414 **
   13415 ** Return YYYY-MM-DD
   13416 */
   13417 static void dateFunc(
   13418   sqlite3_context *context,
   13419   int argc,
   13420   sqlite3_value **argv
   13421 ){
   13422   DateTime x;
   13423   if( isDate(context, argc, argv, &x)==0 ){
   13424     char zBuf[100];
   13425     computeYMD(&x);
   13426     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
   13427     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   13428   }
   13429 }
   13430 
   13431 /*
   13432 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
   13433 **
   13434 ** Return a string described by FORMAT.  Conversions as follows:
   13435 **
   13436 **   %d  day of month
   13437 **   %f  ** fractional seconds  SS.SSS
   13438 **   %H  hour 00-24
   13439 **   %j  day of year 000-366
   13440 **   %J  ** Julian day number
   13441 **   %m  month 01-12
   13442 **   %M  minute 00-59
   13443 **   %s  seconds since 1970-01-01
   13444 **   %S  seconds 00-59
   13445 **   %w  day of week 0-6  sunday==0
   13446 **   %W  week of year 00-53
   13447 **   %Y  year 0000-9999
   13448 **   %%  %
   13449 */
   13450 static void strftimeFunc(
   13451   sqlite3_context *context,
   13452   int argc,
   13453   sqlite3_value **argv
   13454 ){
   13455   DateTime x;
   13456   u64 n;
   13457   size_t i,j;
   13458   char *z;
   13459   sqlite3 *db;
   13460   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
   13461   char zBuf[100];
   13462   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
   13463   db = sqlite3_context_db_handle(context);
   13464   for(i=0, n=1; zFmt[i]; i++, n++){
   13465     if( zFmt[i]=='%' ){
   13466       switch( zFmt[i+1] ){
   13467         case 'd':
   13468         case 'H':
   13469         case 'm':
   13470         case 'M':
   13471         case 'S':
   13472         case 'W':
   13473           n++;
   13474           /* fall thru */
   13475         case 'w':
   13476         case '%':
   13477           break;
   13478         case 'f':
   13479           n += 8;
   13480           break;
   13481         case 'j':
   13482           n += 3;
   13483           break;
   13484         case 'Y':
   13485           n += 8;
   13486           break;
   13487         case 's':
   13488         case 'J':
   13489           n += 50;
   13490           break;
   13491         default:
   13492           return;  /* ERROR.  return a NULL */
   13493       }
   13494       i++;
   13495     }
   13496   }
   13497   testcase( n==sizeof(zBuf)-1 );
   13498   testcase( n==sizeof(zBuf) );
   13499   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   13500   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   13501   if( n<sizeof(zBuf) ){
   13502     z = zBuf;
   13503   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   13504     sqlite3_result_error_toobig(context);
   13505     return;
   13506   }else{
   13507     z = sqlite3DbMallocRaw(db, (int)n);
   13508     if( z==0 ){
   13509       sqlite3_result_error_nomem(context);
   13510       return;
   13511     }
   13512   }
   13513   computeJD(&x);
   13514   computeYMD_HMS(&x);
   13515   for(i=j=0; zFmt[i]; i++){
   13516     if( zFmt[i]!='%' ){
   13517       z[j++] = zFmt[i];
   13518     }else{
   13519       i++;
   13520       switch( zFmt[i] ){
   13521         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
   13522         case 'f': {
   13523           double s = x.s;
   13524           if( s>59.999 ) s = 59.999;
   13525           sqlite3_snprintf(7, &z[j],"%06.3f", s);
   13526           j += sqlite3Strlen30(&z[j]);
   13527           break;
   13528         }
   13529         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
   13530         case 'W': /* Fall thru */
   13531         case 'j': {
   13532           int nDay;             /* Number of days since 1st day of year */
   13533           DateTime y = x;
   13534           y.validJD = 0;
   13535           y.M = 1;
   13536           y.D = 1;
   13537           computeJD(&y);
   13538           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
   13539           if( zFmt[i]=='W' ){
   13540             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
   13541             wd = (int)(((x.iJD+43200000)/86400000)%7);
   13542             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
   13543             j += 2;
   13544           }else{
   13545             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
   13546             j += 3;
   13547           }
   13548           break;
   13549         }
   13550         case 'J': {
   13551           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
   13552           j+=sqlite3Strlen30(&z[j]);
   13553           break;
   13554         }
   13555         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
   13556         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
   13557         case 's': {
   13558           sqlite3_snprintf(30,&z[j],"%lld",
   13559                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
   13560           j += sqlite3Strlen30(&z[j]);
   13561           break;
   13562         }
   13563         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
   13564         case 'w': {
   13565           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
   13566           break;
   13567         }
   13568         case 'Y': {
   13569           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
   13570           break;
   13571         }
   13572         default:   z[j++] = '%'; break;
   13573       }
   13574     }
   13575   }
   13576   z[j] = 0;
   13577   sqlite3_result_text(context, z, -1,
   13578                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
   13579 }
   13580 
   13581 /*
   13582 ** current_time()
   13583 **
   13584 ** This function returns the same value as time('now').
   13585 */
   13586 static void ctimeFunc(
   13587   sqlite3_context *context,
   13588   int NotUsed,
   13589   sqlite3_value **NotUsed2
   13590 ){
   13591   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   13592   timeFunc(context, 0, 0);
   13593 }
   13594 
   13595 /*
   13596 ** current_date()
   13597 **
   13598 ** This function returns the same value as date('now').
   13599 */
   13600 static void cdateFunc(
   13601   sqlite3_context *context,
   13602   int NotUsed,
   13603   sqlite3_value **NotUsed2
   13604 ){
   13605   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   13606   dateFunc(context, 0, 0);
   13607 }
   13608 
   13609 /*
   13610 ** current_timestamp()
   13611 **
   13612 ** This function returns the same value as datetime('now').
   13613 */
   13614 static void ctimestampFunc(
   13615   sqlite3_context *context,
   13616   int NotUsed,
   13617   sqlite3_value **NotUsed2
   13618 ){
   13619   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   13620   datetimeFunc(context, 0, 0);
   13621 }
   13622 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
   13623 
   13624 #ifdef SQLITE_OMIT_DATETIME_FUNCS
   13625 /*
   13626 ** If the library is compiled to omit the full-scale date and time
   13627 ** handling (to get a smaller binary), the following minimal version
   13628 ** of the functions current_time(), current_date() and current_timestamp()
   13629 ** are included instead. This is to support column declarations that
   13630 ** include "DEFAULT CURRENT_TIME" etc.
   13631 **
   13632 ** This function uses the C-library functions time(), gmtime()
   13633 ** and strftime(). The format string to pass to strftime() is supplied
   13634 ** as the user-data for the function.
   13635 */
   13636 static void currentTimeFunc(
   13637   sqlite3_context *context,
   13638   int argc,
   13639   sqlite3_value **argv
   13640 ){
   13641   time_t t;
   13642   char *zFormat = (char *)sqlite3_user_data(context);
   13643   sqlite3 *db;
   13644   sqlite3_int64 iT;
   13645   char zBuf[20];
   13646 
   13647   UNUSED_PARAMETER(argc);
   13648   UNUSED_PARAMETER(argv);
   13649 
   13650   db = sqlite3_context_db_handle(context);
   13651   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
   13652   t = iT/1000 - 10000*(sqlite3_int64)21086676;
   13653 #ifdef HAVE_GMTIME_R
   13654   {
   13655     struct tm sNow;
   13656     gmtime_r(&t, &sNow);
   13657     strftime(zBuf, 20, zFormat, &sNow);
   13658   }
   13659 #else
   13660   {
   13661     struct tm *pTm;
   13662     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   13663     pTm = gmtime(&t);
   13664     strftime(zBuf, 20, zFormat, pTm);
   13665     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   13666   }
   13667 #endif
   13668 
   13669   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   13670 }
   13671 #endif
   13672 
   13673 /*
   13674 ** This function registered all of the above C functions as SQL
   13675 ** functions.  This should be the only routine in this file with
   13676 ** external linkage.
   13677 */
   13678 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
   13679   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
   13680 #ifndef SQLITE_OMIT_DATETIME_FUNCS
   13681     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
   13682     FUNCTION(date,             -1, 0, 0, dateFunc      ),
   13683     FUNCTION(time,             -1, 0, 0, timeFunc      ),
   13684     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
   13685     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
   13686     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
   13687     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
   13688     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
   13689 #else
   13690     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
   13691     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
   13692     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
   13693 #endif
   13694   };
   13695   int i;
   13696   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   13697   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
   13698 
   13699   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
   13700     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   13701   }
   13702 }
   13703 
   13704 /************** End of date.c ************************************************/
   13705 /************** Begin file os.c **********************************************/
   13706 /*
   13707 ** 2005 November 29
   13708 **
   13709 ** The author disclaims copyright to this source code.  In place of
   13710 ** a legal notice, here is a blessing:
   13711 **
   13712 **    May you do good and not evil.
   13713 **    May you find forgiveness for yourself and forgive others.
   13714 **    May you share freely, never taking more than you give.
   13715 **
   13716 ******************************************************************************
   13717 **
   13718 ** This file contains OS interface code that is common to all
   13719 ** architectures.
   13720 */
   13721 #define _SQLITE_OS_C_ 1
   13722 #undef _SQLITE_OS_C_
   13723 
   13724 /*
   13725 ** The default SQLite sqlite3_vfs implementations do not allocate
   13726 ** memory (actually, os_unix.c allocates a small amount of memory
   13727 ** from within OsOpen()), but some third-party implementations may.
   13728 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
   13729 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
   13730 **
   13731 ** The following functions are instrumented for malloc() failure
   13732 ** testing:
   13733 **
   13734 **     sqlite3OsOpen()
   13735 **     sqlite3OsRead()
   13736 **     sqlite3OsWrite()
   13737 **     sqlite3OsSync()
   13738 **     sqlite3OsLock()
   13739 **
   13740 */
   13741 #if defined(SQLITE_TEST)
   13742 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
   13743   #define DO_OS_MALLOC_TEST(x)                                       \
   13744   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
   13745     void *pTstAlloc = sqlite3Malloc(10);                             \
   13746     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
   13747     sqlite3_free(pTstAlloc);                                         \
   13748   }
   13749 #else
   13750   #define DO_OS_MALLOC_TEST(x)
   13751 #endif
   13752 
   13753 /*
   13754 ** The following routines are convenience wrappers around methods
   13755 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
   13756 ** of this would be completely automatic if SQLite were coded using
   13757 ** C++ instead of plain old C.
   13758 */
   13759 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
   13760   int rc = SQLITE_OK;
   13761   if( pId->pMethods ){
   13762     rc = pId->pMethods->xClose(pId);
   13763     pId->pMethods = 0;
   13764   }
   13765   return rc;
   13766 }
   13767 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
   13768   DO_OS_MALLOC_TEST(id);
   13769   return id->pMethods->xRead(id, pBuf, amt, offset);
   13770 }
   13771 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
   13772   DO_OS_MALLOC_TEST(id);
   13773   return id->pMethods->xWrite(id, pBuf, amt, offset);
   13774 }
   13775 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
   13776   return id->pMethods->xTruncate(id, size);
   13777 }
   13778 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
   13779   DO_OS_MALLOC_TEST(id);
   13780   return id->pMethods->xSync(id, flags);
   13781 }
   13782 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
   13783   DO_OS_MALLOC_TEST(id);
   13784   return id->pMethods->xFileSize(id, pSize);
   13785 }
   13786 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
   13787   DO_OS_MALLOC_TEST(id);
   13788   return id->pMethods->xLock(id, lockType);
   13789 }
   13790 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
   13791   return id->pMethods->xUnlock(id, lockType);
   13792 }
   13793 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
   13794   DO_OS_MALLOC_TEST(id);
   13795   return id->pMethods->xCheckReservedLock(id, pResOut);
   13796 }
   13797 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
   13798   return id->pMethods->xFileControl(id, op, pArg);
   13799 }
   13800 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
   13801   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
   13802   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
   13803 }
   13804 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
   13805   return id->pMethods->xDeviceCharacteristics(id);
   13806 }
   13807 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
   13808   return id->pMethods->xShmLock(id, offset, n, flags);
   13809 }
   13810 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
   13811   id->pMethods->xShmBarrier(id);
   13812 }
   13813 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
   13814   return id->pMethods->xShmUnmap(id, deleteFlag);
   13815 }
   13816 SQLITE_PRIVATE int sqlite3OsShmMap(
   13817   sqlite3_file *id,               /* Database file handle */
   13818   int iPage,
   13819   int pgsz,
   13820   int bExtend,                    /* True to extend file if necessary */
   13821   void volatile **pp              /* OUT: Pointer to mapping */
   13822 ){
   13823   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
   13824 }
   13825 
   13826 /*
   13827 ** The next group of routines are convenience wrappers around the
   13828 ** VFS methods.
   13829 */
   13830 SQLITE_PRIVATE int sqlite3OsOpen(
   13831   sqlite3_vfs *pVfs,
   13832   const char *zPath,
   13833   sqlite3_file *pFile,
   13834   int flags,
   13835   int *pFlagsOut
   13836 ){
   13837   int rc;
   13838   DO_OS_MALLOC_TEST(0);
   13839   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   13840   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   13841   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   13842   ** reaching the VFS. */
   13843   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
   13844   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   13845   return rc;
   13846 }
   13847 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
   13848   return pVfs->xDelete(pVfs, zPath, dirSync);
   13849 }
   13850 SQLITE_PRIVATE int sqlite3OsAccess(
   13851   sqlite3_vfs *pVfs,
   13852   const char *zPath,
   13853   int flags,
   13854   int *pResOut
   13855 ){
   13856   DO_OS_MALLOC_TEST(0);
   13857   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
   13858 }
   13859 SQLITE_PRIVATE int sqlite3OsFullPathname(
   13860   sqlite3_vfs *pVfs,
   13861   const char *zPath,
   13862   int nPathOut,
   13863   char *zPathOut
   13864 ){
   13865   zPathOut[0] = 0;
   13866   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   13867 }
   13868 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   13869 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   13870   return pVfs->xDlOpen(pVfs, zPath);
   13871 }
   13872 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   13873   pVfs->xDlError(pVfs, nByte, zBufOut);
   13874 }
   13875 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
   13876   return pVfs->xDlSym(pVfs, pHdle, zSym);
   13877 }
   13878 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
   13879   pVfs->xDlClose(pVfs, pHandle);
   13880 }
   13881 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   13882 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
   13883   return pVfs->xRandomness(pVfs, nByte, zBufOut);
   13884 }
   13885 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   13886   return pVfs->xSleep(pVfs, nMicro);
   13887 }
   13888 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
   13889   int rc;
   13890   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
   13891   ** method to get the current date and time if that method is available
   13892   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
   13893   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
   13894   ** unavailable.
   13895   */
   13896   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
   13897     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
   13898   }else{
   13899     double r;
   13900     rc = pVfs->xCurrentTime(pVfs, &r);
   13901     *pTimeOut = (sqlite3_int64)(r*86400000.0);
   13902   }
   13903   return rc;
   13904 }
   13905 
   13906 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
   13907   sqlite3_vfs *pVfs,
   13908   const char *zFile,
   13909   sqlite3_file **ppFile,
   13910   int flags,
   13911   int *pOutFlags
   13912 ){
   13913   int rc = SQLITE_NOMEM;
   13914   sqlite3_file *pFile;
   13915   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
   13916   if( pFile ){
   13917     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
   13918     if( rc!=SQLITE_OK ){
   13919       sqlite3_free(pFile);
   13920     }else{
   13921       *ppFile = pFile;
   13922     }
   13923   }
   13924   return rc;
   13925 }
   13926 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
   13927   int rc = SQLITE_OK;
   13928   assert( pFile );
   13929   rc = sqlite3OsClose(pFile);
   13930   sqlite3_free(pFile);
   13931   return rc;
   13932 }
   13933 
   13934 /*
   13935 ** This function is a wrapper around the OS specific implementation of
   13936 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
   13937 ** ability to simulate a malloc failure, so that the handling of an
   13938 ** error in sqlite3_os_init() by the upper layers can be tested.
   13939 */
   13940 SQLITE_PRIVATE int sqlite3OsInit(void){
   13941   void *p = sqlite3_malloc(10);
   13942   if( p==0 ) return SQLITE_NOMEM;
   13943   sqlite3_free(p);
   13944   return sqlite3_os_init();
   13945 }
   13946 
   13947 /*
   13948 ** The list of all registered VFS implementations.
   13949 */
   13950 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
   13951 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
   13952 
   13953 /*
   13954 ** Locate a VFS by name.  If no name is given, simply return the
   13955 ** first VFS on the list.
   13956 */
   13957 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   13958   sqlite3_vfs *pVfs = 0;
   13959 #if SQLITE_THREADSAFE
   13960   sqlite3_mutex *mutex;
   13961 #endif
   13962 #ifndef SQLITE_OMIT_AUTOINIT
   13963   int rc = sqlite3_initialize();
   13964   if( rc ) return 0;
   13965 #endif
   13966 #if SQLITE_THREADSAFE
   13967   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   13968 #endif
   13969   sqlite3_mutex_enter(mutex);
   13970   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
   13971     if( zVfs==0 ) break;
   13972     if( strcmp(zVfs, pVfs->zName)==0 ) break;
   13973   }
   13974   sqlite3_mutex_leave(mutex);
   13975   return pVfs;
   13976 }
   13977 
   13978 /*
   13979 ** Unlink a VFS from the linked list
   13980 */
   13981 static void vfsUnlink(sqlite3_vfs *pVfs){
   13982   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
   13983   if( pVfs==0 ){
   13984     /* No-op */
   13985   }else if( vfsList==pVfs ){
   13986     vfsList = pVfs->pNext;
   13987   }else if( vfsList ){
   13988     sqlite3_vfs *p = vfsList;
   13989     while( p->pNext && p->pNext!=pVfs ){
   13990       p = p->pNext;
   13991     }
   13992     if( p->pNext==pVfs ){
   13993       p->pNext = pVfs->pNext;
   13994     }
   13995   }
   13996 }
   13997 
   13998 /*
   13999 ** Register a VFS with the system.  It is harmless to register the same
   14000 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
   14001 ** true.
   14002 */
   14003 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   14004   sqlite3_mutex *mutex = 0;
   14005 #ifndef SQLITE_OMIT_AUTOINIT
   14006   int rc = sqlite3_initialize();
   14007   if( rc ) return rc;
   14008 #endif
   14009   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   14010   sqlite3_mutex_enter(mutex);
   14011   vfsUnlink(pVfs);
   14012   if( makeDflt || vfsList==0 ){
   14013     pVfs->pNext = vfsList;
   14014     vfsList = pVfs;
   14015   }else{
   14016     pVfs->pNext = vfsList->pNext;
   14017     vfsList->pNext = pVfs;
   14018   }
   14019   assert(vfsList);
   14020   sqlite3_mutex_leave(mutex);
   14021   return SQLITE_OK;
   14022 }
   14023 
   14024 /*
   14025 ** Unregister a VFS so that it is no longer accessible.
   14026 */
   14027 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   14028 #if SQLITE_THREADSAFE
   14029   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   14030 #endif
   14031   sqlite3_mutex_enter(mutex);
   14032   vfsUnlink(pVfs);
   14033   sqlite3_mutex_leave(mutex);
   14034   return SQLITE_OK;
   14035 }
   14036 
   14037 /************** End of os.c **************************************************/
   14038 /************** Begin file fault.c *******************************************/
   14039 /*
   14040 ** 2008 Jan 22
   14041 **
   14042 ** The author disclaims copyright to this source code.  In place of
   14043 ** a legal notice, here is a blessing:
   14044 **
   14045 **    May you do good and not evil.
   14046 **    May you find forgiveness for yourself and forgive others.
   14047 **    May you share freely, never taking more than you give.
   14048 **
   14049 *************************************************************************
   14050 **
   14051 ** This file contains code to support the concept of "benign"
   14052 ** malloc failures (when the xMalloc() or xRealloc() method of the
   14053 ** sqlite3_mem_methods structure fails to allocate a block of memory
   14054 ** and returns 0).
   14055 **
   14056 ** Most malloc failures are non-benign. After they occur, SQLite
   14057 ** abandons the current operation and returns an error code (usually
   14058 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
   14059 ** fatal. For example, if a malloc fails while resizing a hash table, this
   14060 ** is completely recoverable simply by not carrying out the resize. The
   14061 ** hash table will continue to function normally.  So a malloc failure
   14062 ** during a hash table resize is a benign fault.
   14063 */
   14064 
   14065 
   14066 #ifndef SQLITE_OMIT_BUILTIN_TEST
   14067 
   14068 /*
   14069 ** Global variables.
   14070 */
   14071 typedef struct BenignMallocHooks BenignMallocHooks;
   14072 static SQLITE_WSD struct BenignMallocHooks {
   14073   void (*xBenignBegin)(void);
   14074   void (*xBenignEnd)(void);
   14075 } sqlite3Hooks = { 0, 0 };
   14076 
   14077 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
   14078 ** structure.  If writable static data is unsupported on the target,
   14079 ** we have to locate the state vector at run-time.  In the more common
   14080 ** case where writable static data is supported, wsdHooks can refer directly
   14081 ** to the "sqlite3Hooks" state vector declared above.
   14082 */
   14083 #ifdef SQLITE_OMIT_WSD
   14084 # define wsdHooksInit \
   14085   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
   14086 # define wsdHooks x[0]
   14087 #else
   14088 # define wsdHooksInit
   14089 # define wsdHooks sqlite3Hooks
   14090 #endif
   14091 
   14092 
   14093 /*
   14094 ** Register hooks to call when sqlite3BeginBenignMalloc() and
   14095 ** sqlite3EndBenignMalloc() are called, respectively.
   14096 */
   14097 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
   14098   void (*xBenignBegin)(void),
   14099   void (*xBenignEnd)(void)
   14100 ){
   14101   wsdHooksInit;
   14102   wsdHooks.xBenignBegin = xBenignBegin;
   14103   wsdHooks.xBenignEnd = xBenignEnd;
   14104 }
   14105 
   14106 /*
   14107 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
   14108 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
   14109 ** indicates that subsequent malloc failures are non-benign.
   14110 */
   14111 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
   14112   wsdHooksInit;
   14113   if( wsdHooks.xBenignBegin ){
   14114     wsdHooks.xBenignBegin();
   14115   }
   14116 }
   14117 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
   14118   wsdHooksInit;
   14119   if( wsdHooks.xBenignEnd ){
   14120     wsdHooks.xBenignEnd();
   14121   }
   14122 }
   14123 
   14124 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
   14125 
   14126 /************** End of fault.c ***********************************************/
   14127 /************** Begin file mem0.c ********************************************/
   14128 /*
   14129 ** 2008 October 28
   14130 **
   14131 ** The author disclaims copyright to this source code.  In place of
   14132 ** a legal notice, here is a blessing:
   14133 **
   14134 **    May you do good and not evil.
   14135 **    May you find forgiveness for yourself and forgive others.
   14136 **    May you share freely, never taking more than you give.
   14137 **
   14138 *************************************************************************
   14139 **
   14140 ** This file contains a no-op memory allocation drivers for use when
   14141 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
   14142 ** here always fail.  SQLite will not operate with these drivers.  These
   14143 ** are merely placeholders.  Real drivers must be substituted using
   14144 ** sqlite3_config() before SQLite will operate.
   14145 */
   14146 
   14147 /*
   14148 ** This version of the memory allocator is the default.  It is
   14149 ** used when no other memory allocator is specified using compile-time
   14150 ** macros.
   14151 */
   14152 #ifdef SQLITE_ZERO_MALLOC
   14153 
   14154 /*
   14155 ** No-op versions of all memory allocation routines
   14156 */
   14157 static void *sqlite3MemMalloc(int nByte){ return 0; }
   14158 static void sqlite3MemFree(void *pPrior){ return; }
   14159 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
   14160 static int sqlite3MemSize(void *pPrior){ return 0; }
   14161 static int sqlite3MemRoundup(int n){ return n; }
   14162 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
   14163 static void sqlite3MemShutdown(void *NotUsed){ return; }
   14164 
   14165 /*
   14166 ** This routine is the only routine in this file with external linkage.
   14167 **
   14168 ** Populate the low-level memory allocation function pointers in
   14169 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   14170 */
   14171 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   14172   static const sqlite3_mem_methods defaultMethods = {
   14173      sqlite3MemMalloc,
   14174      sqlite3MemFree,
   14175      sqlite3MemRealloc,
   14176      sqlite3MemSize,
   14177      sqlite3MemRoundup,
   14178      sqlite3MemInit,
   14179      sqlite3MemShutdown,
   14180      0
   14181   };
   14182   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   14183 }
   14184 
   14185 #endif /* SQLITE_ZERO_MALLOC */
   14186 
   14187 /************** End of mem0.c ************************************************/
   14188 /************** Begin file mem1.c ********************************************/
   14189 /*
   14190 ** 2007 August 14
   14191 **
   14192 ** The author disclaims copyright to this source code.  In place of
   14193 ** a legal notice, here is a blessing:
   14194 **
   14195 **    May you do good and not evil.
   14196 **    May you find forgiveness for yourself and forgive others.
   14197 **    May you share freely, never taking more than you give.
   14198 **
   14199 *************************************************************************
   14200 **
   14201 ** This file contains low-level memory allocation drivers for when
   14202 ** SQLite will use the standard C-library malloc/realloc/free interface
   14203 ** to obtain the memory it needs.
   14204 **
   14205 ** This file contains implementations of the low-level memory allocation
   14206 ** routines specified in the sqlite3_mem_methods object.
   14207 */
   14208 
   14209 /*
   14210 ** This version of the memory allocator is the default.  It is
   14211 ** used when no other memory allocator is specified using compile-time
   14212 ** macros.
   14213 */
   14214 #ifdef SQLITE_SYSTEM_MALLOC
   14215 
   14216 /*
   14217 ** Like malloc(), but remember the size of the allocation
   14218 ** so that we can find it later using sqlite3MemSize().
   14219 **
   14220 ** For this low-level routine, we are guaranteed that nByte>0 because
   14221 ** cases of nByte<=0 will be intercepted and dealt with by higher level
   14222 ** routines.
   14223 */
   14224 static void *sqlite3MemMalloc(int nByte){
   14225   sqlite3_int64 *p;
   14226   assert( nByte>0 );
   14227   nByte = ROUND8(nByte);
   14228   p = malloc( nByte+8 );
   14229   if( p ){
   14230     p[0] = nByte;
   14231     p++;
   14232   }else{
   14233     testcase( sqlite3GlobalConfig.xLog!=0 );
   14234     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
   14235   }
   14236   return (void *)p;
   14237 }
   14238 
   14239 /*
   14240 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
   14241 ** or sqlite3MemRealloc().
   14242 **
   14243 ** For this low-level routine, we already know that pPrior!=0 since
   14244 ** cases where pPrior==0 will have been intecepted and dealt with
   14245 ** by higher-level routines.
   14246 */
   14247 static void sqlite3MemFree(void *pPrior){
   14248   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   14249   assert( pPrior!=0 );
   14250   p--;
   14251   free(p);
   14252 }
   14253 
   14254 /*
   14255 ** Report the allocated size of a prior return from xMalloc()
   14256 ** or xRealloc().
   14257 */
   14258 static int sqlite3MemSize(void *pPrior){
   14259   sqlite3_int64 *p;
   14260   if( pPrior==0 ) return 0;
   14261   p = (sqlite3_int64*)pPrior;
   14262   p--;
   14263   return (int)p[0];
   14264 }
   14265 
   14266 /*
   14267 ** Like realloc().  Resize an allocation previously obtained from
   14268 ** sqlite3MemMalloc().
   14269 **
   14270 ** For this low-level interface, we know that pPrior!=0.  Cases where
   14271 ** pPrior==0 while have been intercepted by higher-level routine and
   14272 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
   14273 ** cases where nByte<=0 will have been intercepted by higher-level
   14274 ** routines and redirected to xFree.
   14275 */
   14276 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   14277   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
   14278   assert( pPrior!=0 && nByte>0 );
   14279   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
   14280   p--;
   14281   p = realloc(p, nByte+8 );
   14282   if( p ){
   14283     p[0] = nByte;
   14284     p++;
   14285   }else{
   14286     testcase( sqlite3GlobalConfig.xLog!=0 );
   14287     sqlite3_log(SQLITE_NOMEM,
   14288       "failed memory resize %u to %u bytes",
   14289       sqlite3MemSize(pPrior), nByte);
   14290   }
   14291   return (void*)p;
   14292 }
   14293 
   14294 /*
   14295 ** Round up a request size to the next valid allocation size.
   14296 */
   14297 static int sqlite3MemRoundup(int n){
   14298   return ROUND8(n);
   14299 }
   14300 
   14301 /*
   14302 ** Initialize this module.
   14303 */
   14304 static int sqlite3MemInit(void *NotUsed){
   14305   UNUSED_PARAMETER(NotUsed);
   14306   return SQLITE_OK;
   14307 }
   14308 
   14309 /*
   14310 ** Deinitialize this module.
   14311 */
   14312 static void sqlite3MemShutdown(void *NotUsed){
   14313   UNUSED_PARAMETER(NotUsed);
   14314   return;
   14315 }
   14316 
   14317 /*
   14318 ** This routine is the only routine in this file with external linkage.
   14319 **
   14320 ** Populate the low-level memory allocation function pointers in
   14321 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   14322 */
   14323 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   14324   static const sqlite3_mem_methods defaultMethods = {
   14325      sqlite3MemMalloc,
   14326      sqlite3MemFree,
   14327      sqlite3MemRealloc,
   14328      sqlite3MemSize,
   14329      sqlite3MemRoundup,
   14330      sqlite3MemInit,
   14331      sqlite3MemShutdown,
   14332      0
   14333   };
   14334   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   14335 }
   14336 
   14337 #endif /* SQLITE_SYSTEM_MALLOC */
   14338 
   14339 /************** End of mem1.c ************************************************/
   14340 /************** Begin file mem2.c ********************************************/
   14341 /*
   14342 ** 2007 August 15
   14343 **
   14344 ** The author disclaims copyright to this source code.  In place of
   14345 ** a legal notice, here is a blessing:
   14346 **
   14347 **    May you do good and not evil.
   14348 **    May you find forgiveness for yourself and forgive others.
   14349 **    May you share freely, never taking more than you give.
   14350 **
   14351 *************************************************************************
   14352 **
   14353 ** This file contains low-level memory allocation drivers for when
   14354 ** SQLite will use the standard C-library malloc/realloc/free interface
   14355 ** to obtain the memory it needs while adding lots of additional debugging
   14356 ** information to each allocation in order to help detect and fix memory
   14357 ** leaks and memory usage errors.
   14358 **
   14359 ** This file contains implementations of the low-level memory allocation
   14360 ** routines specified in the sqlite3_mem_methods object.
   14361 */
   14362 
   14363 /*
   14364 ** This version of the memory allocator is used only if the
   14365 ** SQLITE_MEMDEBUG macro is defined
   14366 */
   14367 #ifdef SQLITE_MEMDEBUG
   14368 
   14369 /*
   14370 ** The backtrace functionality is only available with GLIBC
   14371 */
   14372 #ifdef __GLIBC__
   14373   extern int backtrace(void**,int);
   14374   extern void backtrace_symbols_fd(void*const*,int,int);
   14375 #else
   14376 # define backtrace(A,B) 1
   14377 # define backtrace_symbols_fd(A,B,C)
   14378 #endif
   14379 
   14380 /*
   14381 ** Each memory allocation looks like this:
   14382 **
   14383 **  ------------------------------------------------------------------------
   14384 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
   14385 **  ------------------------------------------------------------------------
   14386 **
   14387 ** The application code sees only a pointer to the allocation.  We have
   14388 ** to back up from the allocation pointer to find the MemBlockHdr.  The
   14389 ** MemBlockHdr tells us the size of the allocation and the number of
   14390 ** backtrace pointers.  There is also a guard word at the end of the
   14391 ** MemBlockHdr.
   14392 */
   14393 struct MemBlockHdr {
   14394   i64 iSize;                          /* Size of this allocation */
   14395   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
   14396   char nBacktrace;                    /* Number of backtraces on this alloc */
   14397   char nBacktraceSlots;               /* Available backtrace slots */
   14398   u8 nTitle;                          /* Bytes of title; includes '\0' */
   14399   u8 eType;                           /* Allocation type code */
   14400   int iForeGuard;                     /* Guard word for sanity */
   14401 };
   14402 
   14403 /*
   14404 ** Guard words
   14405 */
   14406 #define FOREGUARD 0x80F5E153
   14407 #define REARGUARD 0xE4676B53
   14408 
   14409 /*
   14410 ** Number of malloc size increments to track.
   14411 */
   14412 #define NCSIZE  1000
   14413 
   14414 /*
   14415 ** All of the static variables used by this module are collected
   14416 ** into a single structure named "mem".  This is to keep the
   14417 ** static variables organized and to reduce namespace pollution
   14418 ** when this module is combined with other in the amalgamation.
   14419 */
   14420 static struct {
   14421 
   14422   /*
   14423   ** Mutex to control access to the memory allocation subsystem.
   14424   */
   14425   sqlite3_mutex *mutex;
   14426 
   14427   /*
   14428   ** Head and tail of a linked list of all outstanding allocations
   14429   */
   14430   struct MemBlockHdr *pFirst;
   14431   struct MemBlockHdr *pLast;
   14432 
   14433   /*
   14434   ** The number of levels of backtrace to save in new allocations.
   14435   */
   14436   int nBacktrace;
   14437   void (*xBacktrace)(int, int, void **);
   14438 
   14439   /*
   14440   ** Title text to insert in front of each block
   14441   */
   14442   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   14443   char zTitle[100];  /* The title text */
   14444 
   14445   /*
   14446   ** sqlite3MallocDisallow() increments the following counter.
   14447   ** sqlite3MallocAllow() decrements it.
   14448   */
   14449   int disallow; /* Do not allow memory allocation */
   14450 
   14451   /*
   14452   ** Gather statistics on the sizes of memory allocations.
   14453   ** nAlloc[i] is the number of allocation attempts of i*8
   14454   ** bytes.  i==NCSIZE is the number of allocation attempts for
   14455   ** sizes more than NCSIZE*8 bytes.
   14456   */
   14457   int nAlloc[NCSIZE];      /* Total number of allocations */
   14458   int nCurrent[NCSIZE];    /* Current number of allocations */
   14459   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
   14460 
   14461 } mem;
   14462 
   14463 
   14464 /*
   14465 ** Adjust memory usage statistics
   14466 */
   14467 static void adjustStats(int iSize, int increment){
   14468   int i = ROUND8(iSize)/8;
   14469   if( i>NCSIZE-1 ){
   14470     i = NCSIZE - 1;
   14471   }
   14472   if( increment>0 ){
   14473     mem.nAlloc[i]++;
   14474     mem.nCurrent[i]++;
   14475     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
   14476       mem.mxCurrent[i] = mem.nCurrent[i];
   14477     }
   14478   }else{
   14479     mem.nCurrent[i]--;
   14480     assert( mem.nCurrent[i]>=0 );
   14481   }
   14482 }
   14483 
   14484 /*
   14485 ** Given an allocation, find the MemBlockHdr for that allocation.
   14486 **
   14487 ** This routine checks the guards at either end of the allocation and
   14488 ** if they are incorrect it asserts.
   14489 */
   14490 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   14491   struct MemBlockHdr *p;
   14492   int *pInt;
   14493   u8 *pU8;
   14494   int nReserve;
   14495 
   14496   p = (struct MemBlockHdr*)pAllocation;
   14497   p--;
   14498   assert( p->iForeGuard==(int)FOREGUARD );
   14499   nReserve = ROUND8(p->iSize);
   14500   pInt = (int*)pAllocation;
   14501   pU8 = (u8*)pAllocation;
   14502   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   14503   /* This checks any of the "extra" bytes allocated due
   14504   ** to rounding up to an 8 byte boundary to ensure
   14505   ** they haven't been overwritten.
   14506   */
   14507   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
   14508   return p;
   14509 }
   14510 
   14511 /*
   14512 ** Return the number of bytes currently allocated at address p.
   14513 */
   14514 static int sqlite3MemSize(void *p){
   14515   struct MemBlockHdr *pHdr;
   14516   if( !p ){
   14517     return 0;
   14518   }
   14519   pHdr = sqlite3MemsysGetHeader(p);
   14520   return pHdr->iSize;
   14521 }
   14522 
   14523 /*
   14524 ** Initialize the memory allocation subsystem.
   14525 */
   14526 static int sqlite3MemInit(void *NotUsed){
   14527   UNUSED_PARAMETER(NotUsed);
   14528   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
   14529   if( !sqlite3GlobalConfig.bMemstat ){
   14530     /* If memory status is enabled, then the malloc.c wrapper will already
   14531     ** hold the STATIC_MEM mutex when the routines here are invoked. */
   14532     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   14533   }
   14534   return SQLITE_OK;
   14535 }
   14536 
   14537 /*
   14538 ** Deinitialize the memory allocation subsystem.
   14539 */
   14540 static void sqlite3MemShutdown(void *NotUsed){
   14541   UNUSED_PARAMETER(NotUsed);
   14542   mem.mutex = 0;
   14543 }
   14544 
   14545 /*
   14546 ** Round up a request size to the next valid allocation size.
   14547 */
   14548 static int sqlite3MemRoundup(int n){
   14549   return ROUND8(n);
   14550 }
   14551 
   14552 /*
   14553 ** Fill a buffer with pseudo-random bytes.  This is used to preset
   14554 ** the content of a new memory allocation to unpredictable values and
   14555 ** to clear the content of a freed allocation to unpredictable values.
   14556 */
   14557 static void randomFill(char *pBuf, int nByte){
   14558   unsigned int x, y, r;
   14559   x = SQLITE_PTR_TO_INT(pBuf);
   14560   y = nByte | 1;
   14561   while( nByte >= 4 ){
   14562     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   14563     y = y*1103515245 + 12345;
   14564     r = x ^ y;
   14565     *(int*)pBuf = r;
   14566     pBuf += 4;
   14567     nByte -= 4;
   14568   }
   14569   while( nByte-- > 0 ){
   14570     x = (x>>1) ^ (-(x&1) & 0xd0000001);
   14571     y = y*1103515245 + 12345;
   14572     r = x ^ y;
   14573     *(pBuf++) = r & 0xff;
   14574   }
   14575 }
   14576 
   14577 /*
   14578 ** Allocate nByte bytes of memory.
   14579 */
   14580 static void *sqlite3MemMalloc(int nByte){
   14581   struct MemBlockHdr *pHdr;
   14582   void **pBt;
   14583   char *z;
   14584   int *pInt;
   14585   void *p = 0;
   14586   int totalSize;
   14587   int nReserve;
   14588   sqlite3_mutex_enter(mem.mutex);
   14589   assert( mem.disallow==0 );
   14590   nReserve = ROUND8(nByte);
   14591   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
   14592                mem.nBacktrace*sizeof(void*) + mem.nTitle;
   14593   p = malloc(totalSize);
   14594   if( p ){
   14595     z = p;
   14596     pBt = (void**)&z[mem.nTitle];
   14597     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
   14598     pHdr->pNext = 0;
   14599     pHdr->pPrev = mem.pLast;
   14600     if( mem.pLast ){
   14601       mem.pLast->pNext = pHdr;
   14602     }else{
   14603       mem.pFirst = pHdr;
   14604     }
   14605     mem.pLast = pHdr;
   14606     pHdr->iForeGuard = FOREGUARD;
   14607     pHdr->eType = MEMTYPE_HEAP;
   14608     pHdr->nBacktraceSlots = mem.nBacktrace;
   14609     pHdr->nTitle = mem.nTitle;
   14610     if( mem.nBacktrace ){
   14611       void *aAddr[40];
   14612       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
   14613       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
   14614       assert(pBt[0]);
   14615       if( mem.xBacktrace ){
   14616         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
   14617       }
   14618     }else{
   14619       pHdr->nBacktrace = 0;
   14620     }
   14621     if( mem.nTitle ){
   14622       memcpy(z, mem.zTitle, mem.nTitle);
   14623     }
   14624     pHdr->iSize = nByte;
   14625     adjustStats(nByte, +1);
   14626     pInt = (int*)&pHdr[1];
   14627     pInt[nReserve/sizeof(int)] = REARGUARD;
   14628     randomFill((char*)pInt, nByte);
   14629     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
   14630     p = (void*)pInt;
   14631   }
   14632   sqlite3_mutex_leave(mem.mutex);
   14633   return p;
   14634 }
   14635 
   14636 /*
   14637 ** Free memory.
   14638 */
   14639 static void sqlite3MemFree(void *pPrior){
   14640   struct MemBlockHdr *pHdr;
   14641   void **pBt;
   14642   char *z;
   14643   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
   14644        || mem.mutex!=0 );
   14645   pHdr = sqlite3MemsysGetHeader(pPrior);
   14646   pBt = (void**)pHdr;
   14647   pBt -= pHdr->nBacktraceSlots;
   14648   sqlite3_mutex_enter(mem.mutex);
   14649   if( pHdr->pPrev ){
   14650     assert( pHdr->pPrev->pNext==pHdr );
   14651     pHdr->pPrev->pNext = pHdr->pNext;
   14652   }else{
   14653     assert( mem.pFirst==pHdr );
   14654     mem.pFirst = pHdr->pNext;
   14655   }
   14656   if( pHdr->pNext ){
   14657     assert( pHdr->pNext->pPrev==pHdr );
   14658     pHdr->pNext->pPrev = pHdr->pPrev;
   14659   }else{
   14660     assert( mem.pLast==pHdr );
   14661     mem.pLast = pHdr->pPrev;
   14662   }
   14663   z = (char*)pBt;
   14664   z -= pHdr->nTitle;
   14665   adjustStats(pHdr->iSize, -1);
   14666   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
   14667                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
   14668   free(z);
   14669   sqlite3_mutex_leave(mem.mutex);
   14670 }
   14671 
   14672 /*
   14673 ** Change the size of an existing memory allocation.
   14674 **
   14675 ** For this debugging implementation, we *always* make a copy of the
   14676 ** allocation into a new place in memory.  In this way, if the
   14677 ** higher level code is using pointer to the old allocation, it is
   14678 ** much more likely to break and we are much more liking to find
   14679 ** the error.
   14680 */
   14681 static void *sqlite3MemRealloc(void *pPrior, int nByte){
   14682   struct MemBlockHdr *pOldHdr;
   14683   void *pNew;
   14684   assert( mem.disallow==0 );
   14685   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
   14686   pOldHdr = sqlite3MemsysGetHeader(pPrior);
   14687   pNew = sqlite3MemMalloc(nByte);
   14688   if( pNew ){
   14689     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
   14690     if( nByte>pOldHdr->iSize ){
   14691       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
   14692     }
   14693     sqlite3MemFree(pPrior);
   14694   }
   14695   return pNew;
   14696 }
   14697 
   14698 /*
   14699 ** Populate the low-level memory allocation function pointers in
   14700 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
   14701 */
   14702 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
   14703   static const sqlite3_mem_methods defaultMethods = {
   14704      sqlite3MemMalloc,
   14705      sqlite3MemFree,
   14706      sqlite3MemRealloc,
   14707      sqlite3MemSize,
   14708      sqlite3MemRoundup,
   14709      sqlite3MemInit,
   14710      sqlite3MemShutdown,
   14711      0
   14712   };
   14713   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
   14714 }
   14715 
   14716 /*
   14717 ** Set the "type" of an allocation.
   14718 */
   14719 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
   14720   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   14721     struct MemBlockHdr *pHdr;
   14722     pHdr = sqlite3MemsysGetHeader(p);
   14723     assert( pHdr->iForeGuard==FOREGUARD );
   14724     pHdr->eType = eType;
   14725   }
   14726 }
   14727 
   14728 /*
   14729 ** Return TRUE if the mask of type in eType matches the type of the
   14730 ** allocation p.  Also return true if p==NULL.
   14731 **
   14732 ** This routine is designed for use within an assert() statement, to
   14733 ** verify the type of an allocation.  For example:
   14734 **
   14735 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   14736 */
   14737 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
   14738   int rc = 1;
   14739   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   14740     struct MemBlockHdr *pHdr;
   14741     pHdr = sqlite3MemsysGetHeader(p);
   14742     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   14743     if( (pHdr->eType&eType)==0 ){
   14744       rc = 0;
   14745     }
   14746   }
   14747   return rc;
   14748 }
   14749 
   14750 /*
   14751 ** Return TRUE if the mask of type in eType matches no bits of the type of the
   14752 ** allocation p.  Also return true if p==NULL.
   14753 **
   14754 ** This routine is designed for use within an assert() statement, to
   14755 ** verify the type of an allocation.  For example:
   14756 **
   14757 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   14758 */
   14759 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
   14760   int rc = 1;
   14761   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
   14762     struct MemBlockHdr *pHdr;
   14763     pHdr = sqlite3MemsysGetHeader(p);
   14764     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
   14765     if( (pHdr->eType&eType)!=0 ){
   14766       rc = 0;
   14767     }
   14768   }
   14769   return rc;
   14770 }
   14771 
   14772 /*
   14773 ** Set the number of backtrace levels kept for each allocation.
   14774 ** A value of zero turns off backtracing.  The number is always rounded
   14775 ** up to a multiple of 2.
   14776 */
   14777 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
   14778   if( depth<0 ){ depth = 0; }
   14779   if( depth>20 ){ depth = 20; }
   14780   depth = (depth+1)&0xfe;
   14781   mem.nBacktrace = depth;
   14782 }
   14783 
   14784 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
   14785   mem.xBacktrace = xBacktrace;
   14786 }
   14787 
   14788 /*
   14789 ** Set the title string for subsequent allocations.
   14790 */
   14791 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
   14792   unsigned int n = sqlite3Strlen30(zTitle) + 1;
   14793   sqlite3_mutex_enter(mem.mutex);
   14794   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
   14795   memcpy(mem.zTitle, zTitle, n);
   14796   mem.zTitle[n] = 0;
   14797   mem.nTitle = ROUND8(n);
   14798   sqlite3_mutex_leave(mem.mutex);
   14799 }
   14800 
   14801 SQLITE_PRIVATE void sqlite3MemdebugSync(){
   14802   struct MemBlockHdr *pHdr;
   14803   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   14804     void **pBt = (void**)pHdr;
   14805     pBt -= pHdr->nBacktraceSlots;
   14806     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
   14807   }
   14808 }
   14809 
   14810 /*
   14811 ** Open the file indicated and write a log of all unfreed memory
   14812 ** allocations into that log.
   14813 */
   14814 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   14815   FILE *out;
   14816   struct MemBlockHdr *pHdr;
   14817   void **pBt;
   14818   int i;
   14819   out = fopen(zFilename, "w");
   14820   if( out==0 ){
   14821     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   14822                     zFilename);
   14823     return;
   14824   }
   14825   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
   14826     char *z = (char*)pHdr;
   14827     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
   14828     fprintf(out, "**** %lld bytes at %p from %s ****\n",
   14829             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
   14830     if( pHdr->nBacktrace ){
   14831       fflush(out);
   14832       pBt = (void**)pHdr;
   14833       pBt -= pHdr->nBacktraceSlots;
   14834       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
   14835       fprintf(out, "\n");
   14836     }
   14837   }
   14838   fprintf(out, "COUNTS:\n");
   14839   for(i=0; i<NCSIZE-1; i++){
   14840     if( mem.nAlloc[i] ){
   14841       fprintf(out, "   %5d: %10d %10d %10d\n",
   14842             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
   14843     }
   14844   }
   14845   if( mem.nAlloc[NCSIZE-1] ){
   14846     fprintf(out, "   %5d: %10d %10d %10d\n",
   14847              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
   14848              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
   14849   }
   14850   fclose(out);
   14851 }
   14852 
   14853 /*
   14854 ** Return the number of times sqlite3MemMalloc() has been called.
   14855 */
   14856 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
   14857   int i;
   14858   int nTotal = 0;
   14859   for(i=0; i<NCSIZE; i++){
   14860     nTotal += mem.nAlloc[i];
   14861   }
   14862   return nTotal;
   14863 }
   14864 
   14865 
   14866 #endif /* SQLITE_MEMDEBUG */
   14867 
   14868 /************** End of mem2.c ************************************************/
   14869 /************** Begin file mem3.c ********************************************/
   14870 /*
   14871 ** 2007 October 14
   14872 **
   14873 ** The author disclaims copyright to this source code.  In place of
   14874 ** a legal notice, here is a blessing:
   14875 **
   14876 **    May you do good and not evil.
   14877 **    May you find forgiveness for yourself and forgive others.
   14878 **    May you share freely, never taking more than you give.
   14879 **
   14880 *************************************************************************
   14881 ** This file contains the C functions that implement a memory
   14882 ** allocation subsystem for use by SQLite.
   14883 **
   14884 ** This version of the memory allocation subsystem omits all
   14885 ** use of malloc(). The SQLite user supplies a block of memory
   14886 ** before calling sqlite3_initialize() from which allocations
   14887 ** are made and returned by the xMalloc() and xRealloc()
   14888 ** implementations. Once sqlite3_initialize() has been called,
   14889 ** the amount of memory available to SQLite is fixed and cannot
   14890 ** be changed.
   14891 **
   14892 ** This version of the memory allocation subsystem is included
   14893 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
   14894 */
   14895 
   14896 /*
   14897 ** This version of the memory allocator is only built into the library
   14898 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
   14899 ** mean that the library will use a memory-pool by default, just that
   14900 ** it is available. The mempool allocator is activated by calling
   14901 ** sqlite3_config().
   14902 */
   14903 #ifdef SQLITE_ENABLE_MEMSYS3
   14904 
   14905 /*
   14906 ** Maximum size (in Mem3Blocks) of a "small" chunk.
   14907 */
   14908 #define MX_SMALL 10
   14909 
   14910 
   14911 /*
   14912 ** Number of freelist hash slots
   14913 */
   14914 #define N_HASH  61
   14915 
   14916 /*
   14917 ** A memory allocation (also called a "chunk") consists of two or
   14918 ** more blocks where each block is 8 bytes.  The first 8 bytes are
   14919 ** a header that is not returned to the user.
   14920 **
   14921 ** A chunk is two or more blocks that is either checked out or
   14922 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
   14923 ** size of the allocation in blocks if the allocation is free.
   14924 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
   14925 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
   14926 ** is true if the previous chunk is checked out and false if the
   14927 ** previous chunk is free.  The u.hdr.prevSize field is the size of
   14928 ** the previous chunk in blocks if the previous chunk is on the
   14929 ** freelist. If the previous chunk is checked out, then
   14930 ** u.hdr.prevSize can be part of the data for that chunk and should
   14931 ** not be read or written.
   14932 **
   14933 ** We often identify a chunk by its index in mem3.aPool[].  When
   14934 ** this is done, the chunk index refers to the second block of
   14935 ** the chunk.  In this way, the first chunk has an index of 1.
   14936 ** A chunk index of 0 means "no such chunk" and is the equivalent
   14937 ** of a NULL pointer.
   14938 **
   14939 ** The second block of free chunks is of the form u.list.  The
   14940 ** two fields form a double-linked list of chunks of related sizes.
   14941 ** Pointers to the head of the list are stored in mem3.aiSmall[]
   14942 ** for smaller chunks and mem3.aiHash[] for larger chunks.
   14943 **
   14944 ** The second block of a chunk is user data if the chunk is checked
   14945 ** out.  If a chunk is checked out, the user data may extend into
   14946 ** the u.hdr.prevSize value of the following chunk.
   14947 */
   14948 typedef struct Mem3Block Mem3Block;
   14949 struct Mem3Block {
   14950   union {
   14951     struct {
   14952       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
   14953       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
   14954     } hdr;
   14955     struct {
   14956       u32 next;       /* Index in mem3.aPool[] of next free chunk */
   14957       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
   14958     } list;
   14959   } u;
   14960 };
   14961 
   14962 /*
   14963 ** All of the static variables used by this module are collected
   14964 ** into a single structure named "mem3".  This is to keep the
   14965 ** static variables organized and to reduce namespace pollution
   14966 ** when this module is combined with other in the amalgamation.
   14967 */
   14968 static SQLITE_WSD struct Mem3Global {
   14969   /*
   14970   ** Memory available for allocation. nPool is the size of the array
   14971   ** (in Mem3Blocks) pointed to by aPool less 2.
   14972   */
   14973   u32 nPool;
   14974   Mem3Block *aPool;
   14975 
   14976   /*
   14977   ** True if we are evaluating an out-of-memory callback.
   14978   */
   14979   int alarmBusy;
   14980 
   14981   /*
   14982   ** Mutex to control access to the memory allocation subsystem.
   14983   */
   14984   sqlite3_mutex *mutex;
   14985 
   14986   /*
   14987   ** The minimum amount of free space that we have seen.
   14988   */
   14989   u32 mnMaster;
   14990 
   14991   /*
   14992   ** iMaster is the index of the master chunk.  Most new allocations
   14993   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
   14994   ** of the current master.  iMaster is 0 if there is not master chunk.
   14995   ** The master chunk is not in either the aiHash[] or aiSmall[].
   14996   */
   14997   u32 iMaster;
   14998   u32 szMaster;
   14999 
   15000   /*
   15001   ** Array of lists of free blocks according to the block size
   15002   ** for smaller chunks, or a hash on the block size for larger
   15003   ** chunks.
   15004   */
   15005   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
   15006   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
   15007 } mem3 = { 97535575 };
   15008 
   15009 #define mem3 GLOBAL(struct Mem3Global, mem3)
   15010 
   15011 /*
   15012 ** Unlink the chunk at mem3.aPool[i] from list it is currently
   15013 ** on.  *pRoot is the list that i is a member of.
   15014 */
   15015 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
   15016   u32 next = mem3.aPool[i].u.list.next;
   15017   u32 prev = mem3.aPool[i].u.list.prev;
   15018   assert( sqlite3_mutex_held(mem3.mutex) );
   15019   if( prev==0 ){
   15020     *pRoot = next;
   15021   }else{
   15022     mem3.aPool[prev].u.list.next = next;
   15023   }
   15024   if( next ){
   15025     mem3.aPool[next].u.list.prev = prev;
   15026   }
   15027   mem3.aPool[i].u.list.next = 0;
   15028   mem3.aPool[i].u.list.prev = 0;
   15029 }
   15030 
   15031 /*
   15032 ** Unlink the chunk at index i from
   15033 ** whatever list is currently a member of.
   15034 */
   15035 static void memsys3Unlink(u32 i){
   15036   u32 size, hash;
   15037   assert( sqlite3_mutex_held(mem3.mutex) );
   15038   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   15039   assert( i>=1 );
   15040   size = mem3.aPool[i-1].u.hdr.size4x/4;
   15041   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   15042   assert( size>=2 );
   15043   if( size <= MX_SMALL ){
   15044     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
   15045   }else{
   15046     hash = size % N_HASH;
   15047     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   15048   }
   15049 }
   15050 
   15051 /*
   15052 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
   15053 ** at *pRoot.
   15054 */
   15055 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
   15056   assert( sqlite3_mutex_held(mem3.mutex) );
   15057   mem3.aPool[i].u.list.next = *pRoot;
   15058   mem3.aPool[i].u.list.prev = 0;
   15059   if( *pRoot ){
   15060     mem3.aPool[*pRoot].u.list.prev = i;
   15061   }
   15062   *pRoot = i;
   15063 }
   15064 
   15065 /*
   15066 ** Link the chunk at index i into either the appropriate
   15067 ** small chunk list, or into the large chunk hash table.
   15068 */
   15069 static void memsys3Link(u32 i){
   15070   u32 size, hash;
   15071   assert( sqlite3_mutex_held(mem3.mutex) );
   15072   assert( i>=1 );
   15073   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
   15074   size = mem3.aPool[i-1].u.hdr.size4x/4;
   15075   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
   15076   assert( size>=2 );
   15077   if( size <= MX_SMALL ){
   15078     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
   15079   }else{
   15080     hash = size % N_HASH;
   15081     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
   15082   }
   15083 }
   15084 
   15085 /*
   15086 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   15087 ** will already be held (obtained by code in malloc.c) if
   15088 ** sqlite3GlobalConfig.bMemStat is true.
   15089 */
   15090 static void memsys3Enter(void){
   15091   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
   15092     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   15093   }
   15094   sqlite3_mutex_enter(mem3.mutex);
   15095 }
   15096 static void memsys3Leave(void){
   15097   sqlite3_mutex_leave(mem3.mutex);
   15098 }
   15099 
   15100 /*
   15101 ** Called when we are unable to satisfy an allocation of nBytes.
   15102 */
   15103 static void memsys3OutOfMemory(int nByte){
   15104   if( !mem3.alarmBusy ){
   15105     mem3.alarmBusy = 1;
   15106     assert( sqlite3_mutex_held(mem3.mutex) );
   15107     sqlite3_mutex_leave(mem3.mutex);
   15108     sqlite3_release_memory(nByte);
   15109     sqlite3_mutex_enter(mem3.mutex);
   15110     mem3.alarmBusy = 0;
   15111   }
   15112 }
   15113 
   15114 
   15115 /*
   15116 ** Chunk i is a free chunk that has been unlinked.  Adjust its
   15117 ** size parameters for check-out and return a pointer to the
   15118 ** user portion of the chunk.
   15119 */
   15120 static void *memsys3Checkout(u32 i, u32 nBlock){
   15121   u32 x;
   15122   assert( sqlite3_mutex_held(mem3.mutex) );
   15123   assert( i>=1 );
   15124   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
   15125   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
   15126   x = mem3.aPool[i-1].u.hdr.size4x;
   15127   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
   15128   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
   15129   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
   15130   return &mem3.aPool[i];
   15131 }
   15132 
   15133 /*
   15134 ** Carve a piece off of the end of the mem3.iMaster free chunk.
   15135 ** Return a pointer to the new allocation.  Or, if the master chunk
   15136 ** is not large enough, return 0.
   15137 */
   15138 static void *memsys3FromMaster(u32 nBlock){
   15139   assert( sqlite3_mutex_held(mem3.mutex) );
   15140   assert( mem3.szMaster>=nBlock );
   15141   if( nBlock>=mem3.szMaster-1 ){
   15142     /* Use the entire master */
   15143     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
   15144     mem3.iMaster = 0;
   15145     mem3.szMaster = 0;
   15146     mem3.mnMaster = 0;
   15147     return p;
   15148   }else{
   15149     /* Split the master block.  Return the tail. */
   15150     u32 newi, x;
   15151     newi = mem3.iMaster + mem3.szMaster - nBlock;
   15152     assert( newi > mem3.iMaster+1 );
   15153     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
   15154     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
   15155     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
   15156     mem3.szMaster -= nBlock;
   15157     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
   15158     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   15159     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   15160     if( mem3.szMaster < mem3.mnMaster ){
   15161       mem3.mnMaster = mem3.szMaster;
   15162     }
   15163     return (void*)&mem3.aPool[newi];
   15164   }
   15165 }
   15166 
   15167 /*
   15168 ** *pRoot is the head of a list of free chunks of the same size
   15169 ** or same size hash.  In other words, *pRoot is an entry in either
   15170 ** mem3.aiSmall[] or mem3.aiHash[].
   15171 **
   15172 ** This routine examines all entries on the given list and tries
   15173 ** to coalesce each entries with adjacent free chunks.
   15174 **
   15175 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
   15176 ** the current mem3.iMaster with the new larger chunk.  In order for
   15177 ** this mem3.iMaster replacement to work, the master chunk must be
   15178 ** linked into the hash tables.  That is not the normal state of
   15179 ** affairs, of course.  The calling routine must link the master
   15180 ** chunk before invoking this routine, then must unlink the (possibly
   15181 ** changed) master chunk once this routine has finished.
   15182 */
   15183 static void memsys3Merge(u32 *pRoot){
   15184   u32 iNext, prev, size, i, x;
   15185 
   15186   assert( sqlite3_mutex_held(mem3.mutex) );
   15187   for(i=*pRoot; i>0; i=iNext){
   15188     iNext = mem3.aPool[i].u.list.next;
   15189     size = mem3.aPool[i-1].u.hdr.size4x;
   15190     assert( (size&1)==0 );
   15191     if( (size&2)==0 ){
   15192       memsys3UnlinkFromList(i, pRoot);
   15193       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
   15194       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
   15195       if( prev==iNext ){
   15196         iNext = mem3.aPool[prev].u.list.next;
   15197       }
   15198       memsys3Unlink(prev);
   15199       size = i + size/4 - prev;
   15200       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
   15201       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
   15202       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
   15203       memsys3Link(prev);
   15204       i = prev;
   15205     }else{
   15206       size /= 4;
   15207     }
   15208     if( size>mem3.szMaster ){
   15209       mem3.iMaster = i;
   15210       mem3.szMaster = size;
   15211     }
   15212   }
   15213 }
   15214 
   15215 /*
   15216 ** Return a block of memory of at least nBytes in size.
   15217 ** Return NULL if unable.
   15218 **
   15219 ** This function assumes that the necessary mutexes, if any, are
   15220 ** already held by the caller. Hence "Unsafe".
   15221 */
   15222 static void *memsys3MallocUnsafe(int nByte){
   15223   u32 i;
   15224   u32 nBlock;
   15225   u32 toFree;
   15226 
   15227   assert( sqlite3_mutex_held(mem3.mutex) );
   15228   assert( sizeof(Mem3Block)==8 );
   15229   if( nByte<=12 ){
   15230     nBlock = 2;
   15231   }else{
   15232     nBlock = (nByte + 11)/8;
   15233   }
   15234   assert( nBlock>=2 );
   15235 
   15236   /* STEP 1:
   15237   ** Look for an entry of the correct size in either the small
   15238   ** chunk table or in the large chunk hash table.  This is
   15239   ** successful most of the time (about 9 times out of 10).
   15240   */
   15241   if( nBlock <= MX_SMALL ){
   15242     i = mem3.aiSmall[nBlock-2];
   15243     if( i>0 ){
   15244       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
   15245       return memsys3Checkout(i, nBlock);
   15246     }
   15247   }else{
   15248     int hash = nBlock % N_HASH;
   15249     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
   15250       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
   15251         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
   15252         return memsys3Checkout(i, nBlock);
   15253       }
   15254     }
   15255   }
   15256 
   15257   /* STEP 2:
   15258   ** Try to satisfy the allocation by carving a piece off of the end
   15259   ** of the master chunk.  This step usually works if step 1 fails.
   15260   */
   15261   if( mem3.szMaster>=nBlock ){
   15262     return memsys3FromMaster(nBlock);
   15263   }
   15264 
   15265 
   15266   /* STEP 3:
   15267   ** Loop through the entire memory pool.  Coalesce adjacent free
   15268   ** chunks.  Recompute the master chunk as the largest free chunk.
   15269   ** Then try again to satisfy the allocation by carving a piece off
   15270   ** of the end of the master chunk.  This step happens very
   15271   ** rarely (we hope!)
   15272   */
   15273   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
   15274     memsys3OutOfMemory(toFree);
   15275     if( mem3.iMaster ){
   15276       memsys3Link(mem3.iMaster);
   15277       mem3.iMaster = 0;
   15278       mem3.szMaster = 0;
   15279     }
   15280     for(i=0; i<N_HASH; i++){
   15281       memsys3Merge(&mem3.aiHash[i]);
   15282     }
   15283     for(i=0; i<MX_SMALL-1; i++){
   15284       memsys3Merge(&mem3.aiSmall[i]);
   15285     }
   15286     if( mem3.szMaster ){
   15287       memsys3Unlink(mem3.iMaster);
   15288       if( mem3.szMaster>=nBlock ){
   15289         return memsys3FromMaster(nBlock);
   15290       }
   15291     }
   15292   }
   15293 
   15294   /* If none of the above worked, then we fail. */
   15295   return 0;
   15296 }
   15297 
   15298 /*
   15299 ** Free an outstanding memory allocation.
   15300 **
   15301 ** This function assumes that the necessary mutexes, if any, are
   15302 ** already held by the caller. Hence "Unsafe".
   15303 */
   15304 void memsys3FreeUnsafe(void *pOld){
   15305   Mem3Block *p = (Mem3Block*)pOld;
   15306   int i;
   15307   u32 size, x;
   15308   assert( sqlite3_mutex_held(mem3.mutex) );
   15309   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
   15310   i = p - mem3.aPool;
   15311   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
   15312   size = mem3.aPool[i-1].u.hdr.size4x/4;
   15313   assert( i+size<=mem3.nPool+1 );
   15314   mem3.aPool[i-1].u.hdr.size4x &= ~1;
   15315   mem3.aPool[i+size-1].u.hdr.prevSize = size;
   15316   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   15317   memsys3Link(i);
   15318 
   15319   /* Try to expand the master using the newly freed chunk */
   15320   if( mem3.iMaster ){
   15321     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
   15322       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
   15323       mem3.iMaster -= size;
   15324       mem3.szMaster += size;
   15325       memsys3Unlink(mem3.iMaster);
   15326       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   15327       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   15328       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   15329     }
   15330     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
   15331     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
   15332       memsys3Unlink(mem3.iMaster+mem3.szMaster);
   15333       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
   15334       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
   15335       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
   15336     }
   15337   }
   15338 }
   15339 
   15340 /*
   15341 ** Return the size of an outstanding allocation, in bytes.  The
   15342 ** size returned omits the 8-byte header overhead.  This only
   15343 ** works for chunks that are currently checked out.
   15344 */
   15345 static int memsys3Size(void *p){
   15346   Mem3Block *pBlock;
   15347   if( p==0 ) return 0;
   15348   pBlock = (Mem3Block*)p;
   15349   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
   15350   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
   15351 }
   15352 
   15353 /*
   15354 ** Round up a request size to the next valid allocation size.
   15355 */
   15356 static int memsys3Roundup(int n){
   15357   if( n<=12 ){
   15358     return 12;
   15359   }else{
   15360     return ((n+11)&~7) - 4;
   15361   }
   15362 }
   15363 
   15364 /*
   15365 ** Allocate nBytes of memory.
   15366 */
   15367 static void *memsys3Malloc(int nBytes){
   15368   sqlite3_int64 *p;
   15369   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
   15370   memsys3Enter();
   15371   p = memsys3MallocUnsafe(nBytes);
   15372   memsys3Leave();
   15373   return (void*)p;
   15374 }
   15375 
   15376 /*
   15377 ** Free memory.
   15378 */
   15379 void memsys3Free(void *pPrior){
   15380   assert( pPrior );
   15381   memsys3Enter();
   15382   memsys3FreeUnsafe(pPrior);
   15383   memsys3Leave();
   15384 }
   15385 
   15386 /*
   15387 ** Change the size of an existing memory allocation
   15388 */
   15389 void *memsys3Realloc(void *pPrior, int nBytes){
   15390   int nOld;
   15391   void *p;
   15392   if( pPrior==0 ){
   15393     return sqlite3_malloc(nBytes);
   15394   }
   15395   if( nBytes<=0 ){
   15396     sqlite3_free(pPrior);
   15397     return 0;
   15398   }
   15399   nOld = memsys3Size(pPrior);
   15400   if( nBytes<=nOld && nBytes>=nOld-128 ){
   15401     return pPrior;
   15402   }
   15403   memsys3Enter();
   15404   p = memsys3MallocUnsafe(nBytes);
   15405   if( p ){
   15406     if( nOld<nBytes ){
   15407       memcpy(p, pPrior, nOld);
   15408     }else{
   15409       memcpy(p, pPrior, nBytes);
   15410     }
   15411     memsys3FreeUnsafe(pPrior);
   15412   }
   15413   memsys3Leave();
   15414   return p;
   15415 }
   15416 
   15417 /*
   15418 ** Initialize this module.
   15419 */
   15420 static int memsys3Init(void *NotUsed){
   15421   UNUSED_PARAMETER(NotUsed);
   15422   if( !sqlite3GlobalConfig.pHeap ){
   15423     return SQLITE_ERROR;
   15424   }
   15425 
   15426   /* Store a pointer to the memory block in global structure mem3. */
   15427   assert( sizeof(Mem3Block)==8 );
   15428   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   15429   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
   15430 
   15431   /* Initialize the master block. */
   15432   mem3.szMaster = mem3.nPool;
   15433   mem3.mnMaster = mem3.szMaster;
   15434   mem3.iMaster = 1;
   15435   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
   15436   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   15437   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
   15438 
   15439   return SQLITE_OK;
   15440 }
   15441 
   15442 /*
   15443 ** Deinitialize this module.
   15444 */
   15445 static void memsys3Shutdown(void *NotUsed){
   15446   UNUSED_PARAMETER(NotUsed);
   15447   mem3.mutex = 0;
   15448   return;
   15449 }
   15450 
   15451 
   15452 
   15453 /*
   15454 ** Open the file indicated and write a log of all unfreed memory
   15455 ** allocations into that log.
   15456 */
   15457 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
   15458 #ifdef SQLITE_DEBUG
   15459   FILE *out;
   15460   u32 i, j;
   15461   u32 size;
   15462   if( zFilename==0 || zFilename[0]==0 ){
   15463     out = stdout;
   15464   }else{
   15465     out = fopen(zFilename, "w");
   15466     if( out==0 ){
   15467       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   15468                       zFilename);
   15469       return;
   15470     }
   15471   }
   15472   memsys3Enter();
   15473   fprintf(out, "CHUNKS:\n");
   15474   for(i=1; i<=mem3.nPool; i+=size/4){
   15475     size = mem3.aPool[i-1].u.hdr.size4x;
   15476     if( size/4<=1 ){
   15477       fprintf(out, "%p size error\n", &mem3.aPool[i]);
   15478       assert( 0 );
   15479       break;
   15480     }
   15481     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
   15482       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
   15483       assert( 0 );
   15484       break;
   15485     }
   15486     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
   15487       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
   15488       assert( 0 );
   15489       break;
   15490     }
   15491     if( size&1 ){
   15492       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
   15493     }else{
   15494       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
   15495                   i==mem3.iMaster ? " **master**" : "");
   15496     }
   15497   }
   15498   for(i=0; i<MX_SMALL-1; i++){
   15499     if( mem3.aiSmall[i]==0 ) continue;
   15500     fprintf(out, "small(%2d):", i);
   15501     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
   15502       fprintf(out, " %p(%d)", &mem3.aPool[j],
   15503               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   15504     }
   15505     fprintf(out, "\n");
   15506   }
   15507   for(i=0; i<N_HASH; i++){
   15508     if( mem3.aiHash[i]==0 ) continue;
   15509     fprintf(out, "hash(%2d):", i);
   15510     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
   15511       fprintf(out, " %p(%d)", &mem3.aPool[j],
   15512               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
   15513     }
   15514     fprintf(out, "\n");
   15515   }
   15516   fprintf(out, "master=%d\n", mem3.iMaster);
   15517   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
   15518   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
   15519   sqlite3_mutex_leave(mem3.mutex);
   15520   if( out==stdout ){
   15521     fflush(stdout);
   15522   }else{
   15523     fclose(out);
   15524   }
   15525 #else
   15526   UNUSED_PARAMETER(zFilename);
   15527 #endif
   15528 }
   15529 
   15530 /*
   15531 ** This routine is the only routine in this file with external
   15532 ** linkage.
   15533 **
   15534 ** Populate the low-level memory allocation function pointers in
   15535 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
   15536 ** arguments specify the block of memory to manage.
   15537 **
   15538 ** This routine is only called by sqlite3_config(), and therefore
   15539 ** is not required to be threadsafe (it is not).
   15540 */
   15541 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
   15542   static const sqlite3_mem_methods mempoolMethods = {
   15543      memsys3Malloc,
   15544      memsys3Free,
   15545      memsys3Realloc,
   15546      memsys3Size,
   15547      memsys3Roundup,
   15548      memsys3Init,
   15549      memsys3Shutdown,
   15550      0
   15551   };
   15552   return &mempoolMethods;
   15553 }
   15554 
   15555 #endif /* SQLITE_ENABLE_MEMSYS3 */
   15556 
   15557 /************** End of mem3.c ************************************************/
   15558 /************** Begin file mem5.c ********************************************/
   15559 /*
   15560 ** 2007 October 14
   15561 **
   15562 ** The author disclaims copyright to this source code.  In place of
   15563 ** a legal notice, here is a blessing:
   15564 **
   15565 **    May you do good and not evil.
   15566 **    May you find forgiveness for yourself and forgive others.
   15567 **    May you share freely, never taking more than you give.
   15568 **
   15569 *************************************************************************
   15570 ** This file contains the C functions that implement a memory
   15571 ** allocation subsystem for use by SQLite.
   15572 **
   15573 ** This version of the memory allocation subsystem omits all
   15574 ** use of malloc(). The application gives SQLite a block of memory
   15575 ** before calling sqlite3_initialize() from which allocations
   15576 ** are made and returned by the xMalloc() and xRealloc()
   15577 ** implementations. Once sqlite3_initialize() has been called,
   15578 ** the amount of memory available to SQLite is fixed and cannot
   15579 ** be changed.
   15580 **
   15581 ** This version of the memory allocation subsystem is included
   15582 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
   15583 **
   15584 ** This memory allocator uses the following algorithm:
   15585 **
   15586 **   1.  All memory allocations sizes are rounded up to a power of 2.
   15587 **
   15588 **   2.  If two adjacent free blocks are the halves of a larger block,
   15589 **       then the two blocks are coalesed into the single larger block.
   15590 **
   15591 **   3.  New memory is allocated from the first available free block.
   15592 **
   15593 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
   15594 ** Concerning Dynamic Storage Allocation". Journal of the Association for
   15595 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
   15596 **
   15597 ** Let n be the size of the largest allocation divided by the minimum
   15598 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
   15599 ** be the maximum amount of memory ever outstanding at one time.  Let
   15600 ** N be the total amount of memory available for allocation.  Robson
   15601 ** proved that this memory allocator will never breakdown due to
   15602 ** fragmentation as long as the following constraint holds:
   15603 **
   15604 **      N >=  M*(1 + log2(n)/2) - n + 1
   15605 **
   15606 ** The sqlite3_status() logic tracks the maximum values of n and M so
   15607 ** that an application can, at any time, verify this constraint.
   15608 */
   15609 
   15610 /*
   15611 ** This version of the memory allocator is used only when
   15612 ** SQLITE_ENABLE_MEMSYS5 is defined.
   15613 */
   15614 #ifdef SQLITE_ENABLE_MEMSYS5
   15615 
   15616 /*
   15617 ** A minimum allocation is an instance of the following structure.
   15618 ** Larger allocations are an array of these structures where the
   15619 ** size of the array is a power of 2.
   15620 **
   15621 ** The size of this object must be a power of two.  That fact is
   15622 ** verified in memsys5Init().
   15623 */
   15624 typedef struct Mem5Link Mem5Link;
   15625 struct Mem5Link {
   15626   int next;       /* Index of next free chunk */
   15627   int prev;       /* Index of previous free chunk */
   15628 };
   15629 
   15630 /*
   15631 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
   15632 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
   15633 ** it is not actually possible to reach this limit.
   15634 */
   15635 #define LOGMAX 30
   15636 
   15637 /*
   15638 ** Masks used for mem5.aCtrl[] elements.
   15639 */
   15640 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
   15641 #define CTRL_FREE     0x20    /* True if not checked out */
   15642 
   15643 /*
   15644 ** All of the static variables used by this module are collected
   15645 ** into a single structure named "mem5".  This is to keep the
   15646 ** static variables organized and to reduce namespace pollution
   15647 ** when this module is combined with other in the amalgamation.
   15648 */
   15649 static SQLITE_WSD struct Mem5Global {
   15650   /*
   15651   ** Memory available for allocation
   15652   */
   15653   int szAtom;      /* Smallest possible allocation in bytes */
   15654   int nBlock;      /* Number of szAtom sized blocks in zPool */
   15655   u8 *zPool;       /* Memory available to be allocated */
   15656 
   15657   /*
   15658   ** Mutex to control access to the memory allocation subsystem.
   15659   */
   15660   sqlite3_mutex *mutex;
   15661 
   15662   /*
   15663   ** Performance statistics
   15664   */
   15665   u64 nAlloc;         /* Total number of calls to malloc */
   15666   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
   15667   u64 totalExcess;    /* Total internal fragmentation */
   15668   u32 currentOut;     /* Current checkout, including internal fragmentation */
   15669   u32 currentCount;   /* Current number of distinct checkouts */
   15670   u32 maxOut;         /* Maximum instantaneous currentOut */
   15671   u32 maxCount;       /* Maximum instantaneous currentCount */
   15672   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
   15673 
   15674   /*
   15675   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   15676   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
   15677   ** and so forth.
   15678   */
   15679   int aiFreelist[LOGMAX+1];
   15680 
   15681   /*
   15682   ** Space for tracking which blocks are checked out and the size
   15683   ** of each block.  One byte per block.
   15684   */
   15685   u8 *aCtrl;
   15686 
   15687 } mem5 = { 0 };
   15688 
   15689 /*
   15690 ** Access the static variable through a macro for SQLITE_OMIT_WSD
   15691 */
   15692 #define mem5 GLOBAL(struct Mem5Global, mem5)
   15693 
   15694 /*
   15695 ** Assuming mem5.zPool is divided up into an array of Mem5Link
   15696 ** structures, return a pointer to the idx-th such lik.
   15697 */
   15698 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
   15699 
   15700 /*
   15701 ** Unlink the chunk at mem5.aPool[i] from list it is currently
   15702 ** on.  It should be found on mem5.aiFreelist[iLogsize].
   15703 */
   15704 static void memsys5Unlink(int i, int iLogsize){
   15705   int next, prev;
   15706   assert( i>=0 && i<mem5.nBlock );
   15707   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   15708   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   15709 
   15710   next = MEM5LINK(i)->next;
   15711   prev = MEM5LINK(i)->prev;
   15712   if( prev<0 ){
   15713     mem5.aiFreelist[iLogsize] = next;
   15714   }else{
   15715     MEM5LINK(prev)->next = next;
   15716   }
   15717   if( next>=0 ){
   15718     MEM5LINK(next)->prev = prev;
   15719   }
   15720 }
   15721 
   15722 /*
   15723 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
   15724 ** free list.
   15725 */
   15726 static void memsys5Link(int i, int iLogsize){
   15727   int x;
   15728   assert( sqlite3_mutex_held(mem5.mutex) );
   15729   assert( i>=0 && i<mem5.nBlock );
   15730   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   15731   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
   15732 
   15733   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
   15734   MEM5LINK(i)->prev = -1;
   15735   if( x>=0 ){
   15736     assert( x<mem5.nBlock );
   15737     MEM5LINK(x)->prev = i;
   15738   }
   15739   mem5.aiFreelist[iLogsize] = i;
   15740 }
   15741 
   15742 /*
   15743 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
   15744 ** will already be held (obtained by code in malloc.c) if
   15745 ** sqlite3GlobalConfig.bMemStat is true.
   15746 */
   15747 static void memsys5Enter(void){
   15748   sqlite3_mutex_enter(mem5.mutex);
   15749 }
   15750 static void memsys5Leave(void){
   15751   sqlite3_mutex_leave(mem5.mutex);
   15752 }
   15753 
   15754 /*
   15755 ** Return the size of an outstanding allocation, in bytes.  The
   15756 ** size returned omits the 8-byte header overhead.  This only
   15757 ** works for chunks that are currently checked out.
   15758 */
   15759 static int memsys5Size(void *p){
   15760   int iSize = 0;
   15761   if( p ){
   15762     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
   15763     assert( i>=0 && i<mem5.nBlock );
   15764     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
   15765   }
   15766   return iSize;
   15767 }
   15768 
   15769 /*
   15770 ** Find the first entry on the freelist iLogsize.  Unlink that
   15771 ** entry and return its index.
   15772 */
   15773 static int memsys5UnlinkFirst(int iLogsize){
   15774   int i;
   15775   int iFirst;
   15776 
   15777   assert( iLogsize>=0 && iLogsize<=LOGMAX );
   15778   i = iFirst = mem5.aiFreelist[iLogsize];
   15779   assert( iFirst>=0 );
   15780   while( i>0 ){
   15781     if( i<iFirst ) iFirst = i;
   15782     i = MEM5LINK(i)->next;
   15783   }
   15784   memsys5Unlink(iFirst, iLogsize);
   15785   return iFirst;
   15786 }
   15787 
   15788 /*
   15789 ** Return a block of memory of at least nBytes in size.
   15790 ** Return NULL if unable.  Return NULL if nBytes==0.
   15791 **
   15792 ** The caller guarantees that nByte positive.
   15793 **
   15794 ** The caller has obtained a mutex prior to invoking this
   15795 ** routine so there is never any chance that two or more
   15796 ** threads can be in this routine at the same time.
   15797 */
   15798 static void *memsys5MallocUnsafe(int nByte){
   15799   int i;           /* Index of a mem5.aPool[] slot */
   15800   int iBin;        /* Index into mem5.aiFreelist[] */
   15801   int iFullSz;     /* Size of allocation rounded up to power of 2 */
   15802   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
   15803 
   15804   /* nByte must be a positive */
   15805   assert( nByte>0 );
   15806 
   15807   /* Keep track of the maximum allocation request.  Even unfulfilled
   15808   ** requests are counted */
   15809   if( (u32)nByte>mem5.maxRequest ){
   15810     mem5.maxRequest = nByte;
   15811   }
   15812 
   15813   /* Abort if the requested allocation size is larger than the largest
   15814   ** power of two that we can represent using 32-bit signed integers.
   15815   */
   15816   if( nByte > 0x40000000 ){
   15817     return 0;
   15818   }
   15819 
   15820   /* Round nByte up to the next valid power of two */
   15821   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
   15822 
   15823   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
   15824   ** block.  If not, then split a block of the next larger power of
   15825   ** two in order to create a new free block of size iLogsize.
   15826   */
   15827   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
   15828   if( iBin>LOGMAX ){
   15829     testcase( sqlite3GlobalConfig.xLog!=0 );
   15830     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
   15831     return 0;
   15832   }
   15833   i = memsys5UnlinkFirst(iBin);
   15834   while( iBin>iLogsize ){
   15835     int newSize;
   15836 
   15837     iBin--;
   15838     newSize = 1 << iBin;
   15839     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
   15840     memsys5Link(i+newSize, iBin);
   15841   }
   15842   mem5.aCtrl[i] = iLogsize;
   15843 
   15844   /* Update allocator performance statistics. */
   15845   mem5.nAlloc++;
   15846   mem5.totalAlloc += iFullSz;
   15847   mem5.totalExcess += iFullSz - nByte;
   15848   mem5.currentCount++;
   15849   mem5.currentOut += iFullSz;
   15850   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   15851   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
   15852 
   15853   /* Return a pointer to the allocated memory. */
   15854   return (void*)&mem5.zPool[i*mem5.szAtom];
   15855 }
   15856 
   15857 /*
   15858 ** Free an outstanding memory allocation.
   15859 */
   15860 static void memsys5FreeUnsafe(void *pOld){
   15861   u32 size, iLogsize;
   15862   int iBlock;
   15863 
   15864   /* Set iBlock to the index of the block pointed to by pOld in
   15865   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   15866   */
   15867   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
   15868 
   15869   /* Check that the pointer pOld points to a valid, non-free block. */
   15870   assert( iBlock>=0 && iBlock<mem5.nBlock );
   15871   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
   15872   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
   15873 
   15874   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
   15875   size = 1<<iLogsize;
   15876   assert( iBlock+size-1<(u32)mem5.nBlock );
   15877 
   15878   mem5.aCtrl[iBlock] |= CTRL_FREE;
   15879   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
   15880   assert( mem5.currentCount>0 );
   15881   assert( mem5.currentOut>=(size*mem5.szAtom) );
   15882   mem5.currentCount--;
   15883   mem5.currentOut -= size*mem5.szAtom;
   15884   assert( mem5.currentOut>0 || mem5.currentCount==0 );
   15885   assert( mem5.currentCount>0 || mem5.currentOut==0 );
   15886 
   15887   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   15888   while( ALWAYS(iLogsize<LOGMAX) ){
   15889     int iBuddy;
   15890     if( (iBlock>>iLogsize) & 1 ){
   15891       iBuddy = iBlock - size;
   15892     }else{
   15893       iBuddy = iBlock + size;
   15894     }
   15895     assert( iBuddy>=0 );
   15896     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
   15897     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
   15898     memsys5Unlink(iBuddy, iLogsize);
   15899     iLogsize++;
   15900     if( iBuddy<iBlock ){
   15901       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
   15902       mem5.aCtrl[iBlock] = 0;
   15903       iBlock = iBuddy;
   15904     }else{
   15905       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   15906       mem5.aCtrl[iBuddy] = 0;
   15907     }
   15908     size *= 2;
   15909   }
   15910   memsys5Link(iBlock, iLogsize);
   15911 }
   15912 
   15913 /*
   15914 ** Allocate nBytes of memory
   15915 */
   15916 static void *memsys5Malloc(int nBytes){
   15917   sqlite3_int64 *p = 0;
   15918   if( nBytes>0 ){
   15919     memsys5Enter();
   15920     p = memsys5MallocUnsafe(nBytes);
   15921     memsys5Leave();
   15922   }
   15923   return (void*)p;
   15924 }
   15925 
   15926 /*
   15927 ** Free memory.
   15928 **
   15929 ** The outer layer memory allocator prevents this routine from
   15930 ** being called with pPrior==0.
   15931 */
   15932 static void memsys5Free(void *pPrior){
   15933   assert( pPrior!=0 );
   15934   memsys5Enter();
   15935   memsys5FreeUnsafe(pPrior);
   15936   memsys5Leave();
   15937 }
   15938 
   15939 /*
   15940 ** Change the size of an existing memory allocation.
   15941 **
   15942 ** The outer layer memory allocator prevents this routine from
   15943 ** being called with pPrior==0.
   15944 **
   15945 ** nBytes is always a value obtained from a prior call to
   15946 ** memsys5Round().  Hence nBytes is always a non-negative power
   15947 ** of two.  If nBytes==0 that means that an oversize allocation
   15948 ** (an allocation larger than 0x40000000) was requested and this
   15949 ** routine should return 0 without freeing pPrior.
   15950 */
   15951 static void *memsys5Realloc(void *pPrior, int nBytes){
   15952   int nOld;
   15953   void *p;
   15954   assert( pPrior!=0 );
   15955   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
   15956   assert( nBytes>=0 );
   15957   if( nBytes==0 ){
   15958     return 0;
   15959   }
   15960   nOld = memsys5Size(pPrior);
   15961   if( nBytes<=nOld ){
   15962     return pPrior;
   15963   }
   15964   memsys5Enter();
   15965   p = memsys5MallocUnsafe(nBytes);
   15966   if( p ){
   15967     memcpy(p, pPrior, nOld);
   15968     memsys5FreeUnsafe(pPrior);
   15969   }
   15970   memsys5Leave();
   15971   return p;
   15972 }
   15973 
   15974 /*
   15975 ** Round up a request size to the next valid allocation size.  If
   15976 ** the allocation is too large to be handled by this allocation system,
   15977 ** return 0.
   15978 **
   15979 ** All allocations must be a power of two and must be expressed by a
   15980 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
   15981 ** or 1073741824 bytes.
   15982 */
   15983 static int memsys5Roundup(int n){
   15984   int iFullSz;
   15985   if( n > 0x40000000 ) return 0;
   15986   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
   15987   return iFullSz;
   15988 }
   15989 
   15990 /*
   15991 ** Return the ceiling of the logarithm base 2 of iValue.
   15992 **
   15993 ** Examples:   memsys5Log(1) -> 0
   15994 **             memsys5Log(2) -> 1
   15995 **             memsys5Log(4) -> 2
   15996 **             memsys5Log(5) -> 3
   15997 **             memsys5Log(8) -> 3
   15998 **             memsys5Log(9) -> 4
   15999 */
   16000 static int memsys5Log(int iValue){
   16001   int iLog;
   16002   for(iLog=0; (1<<iLog)<iValue; iLog++);
   16003   return iLog;
   16004 }
   16005 
   16006 /*
   16007 ** Initialize the memory allocator.
   16008 **
   16009 ** This routine is not threadsafe.  The caller must be holding a mutex
   16010 ** to prevent multiple threads from entering at the same time.
   16011 */
   16012 static int memsys5Init(void *NotUsed){
   16013   int ii;            /* Loop counter */
   16014   int nByte;         /* Number of bytes of memory available to this allocator */
   16015   u8 *zByte;         /* Memory usable by this allocator */
   16016   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
   16017   int iOffset;       /* An offset into mem5.aCtrl[] */
   16018 
   16019   UNUSED_PARAMETER(NotUsed);
   16020 
   16021   /* For the purposes of this routine, disable the mutex */
   16022   mem5.mutex = 0;
   16023 
   16024   /* The size of a Mem5Link object must be a power of two.  Verify that
   16025   ** this is case.
   16026   */
   16027   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
   16028 
   16029   nByte = sqlite3GlobalConfig.nHeap;
   16030   zByte = (u8*)sqlite3GlobalConfig.pHeap;
   16031   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
   16032 
   16033   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
   16034   mem5.szAtom = (1<<nMinLog);
   16035   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
   16036     mem5.szAtom = mem5.szAtom << 1;
   16037   }
   16038 
   16039   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
   16040   mem5.zPool = zByte;
   16041   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
   16042 
   16043   for(ii=0; ii<=LOGMAX; ii++){
   16044     mem5.aiFreelist[ii] = -1;
   16045   }
   16046 
   16047   iOffset = 0;
   16048   for(ii=LOGMAX; ii>=0; ii--){
   16049     int nAlloc = (1<<ii);
   16050     if( (iOffset+nAlloc)<=mem5.nBlock ){
   16051       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
   16052       memsys5Link(iOffset, ii);
   16053       iOffset += nAlloc;
   16054     }
   16055     assert((iOffset+nAlloc)>mem5.nBlock);
   16056   }
   16057 
   16058   /* If a mutex is required for normal operation, allocate one */
   16059   if( sqlite3GlobalConfig.bMemstat==0 ){
   16060     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   16061   }
   16062 
   16063   return SQLITE_OK;
   16064 }
   16065 
   16066 /*
   16067 ** Deinitialize this module.
   16068 */
   16069 static void memsys5Shutdown(void *NotUsed){
   16070   UNUSED_PARAMETER(NotUsed);
   16071   mem5.mutex = 0;
   16072   return;
   16073 }
   16074 
   16075 #ifdef SQLITE_TEST
   16076 /*
   16077 ** Open the file indicated and write a log of all unfreed memory
   16078 ** allocations into that log.
   16079 */
   16080 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
   16081   FILE *out;
   16082   int i, j, n;
   16083   int nMinLog;
   16084 
   16085   if( zFilename==0 || zFilename[0]==0 ){
   16086     out = stdout;
   16087   }else{
   16088     out = fopen(zFilename, "w");
   16089     if( out==0 ){
   16090       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
   16091                       zFilename);
   16092       return;
   16093     }
   16094   }
   16095   memsys5Enter();
   16096   nMinLog = memsys5Log(mem5.szAtom);
   16097   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
   16098     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
   16099     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
   16100   }
   16101   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
   16102   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
   16103   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
   16104   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
   16105   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
   16106   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
   16107   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
   16108   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
   16109   memsys5Leave();
   16110   if( out==stdout ){
   16111     fflush(stdout);
   16112   }else{
   16113     fclose(out);
   16114   }
   16115 }
   16116 #endif
   16117 
   16118 /*
   16119 ** This routine is the only routine in this file with external
   16120 ** linkage. It returns a pointer to a static sqlite3_mem_methods
   16121 ** struct populated with the memsys5 methods.
   16122 */
   16123 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
   16124   static const sqlite3_mem_methods memsys5Methods = {
   16125      memsys5Malloc,
   16126      memsys5Free,
   16127      memsys5Realloc,
   16128      memsys5Size,
   16129      memsys5Roundup,
   16130      memsys5Init,
   16131      memsys5Shutdown,
   16132      0
   16133   };
   16134   return &memsys5Methods;
   16135 }
   16136 
   16137 #endif /* SQLITE_ENABLE_MEMSYS5 */
   16138 
   16139 /************** End of mem5.c ************************************************/
   16140 /************** Begin file mutex.c *******************************************/
   16141 /*
   16142 ** 2007 August 14
   16143 **
   16144 ** The author disclaims copyright to this source code.  In place of
   16145 ** a legal notice, here is a blessing:
   16146 **
   16147 **    May you do good and not evil.
   16148 **    May you find forgiveness for yourself and forgive others.
   16149 **    May you share freely, never taking more than you give.
   16150 **
   16151 *************************************************************************
   16152 ** This file contains the C functions that implement mutexes.
   16153 **
   16154 ** This file contains code that is common across all mutex implementations.
   16155 */
   16156 
   16157 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
   16158 /*
   16159 ** For debugging purposes, record when the mutex subsystem is initialized
   16160 ** and uninitialized so that we can assert() if there is an attempt to
   16161 ** allocate a mutex while the system is uninitialized.
   16162 */
   16163 static SQLITE_WSD int mutexIsInit = 0;
   16164 #endif /* SQLITE_DEBUG */
   16165 
   16166 
   16167 #ifndef SQLITE_MUTEX_OMIT
   16168 /*
   16169 ** Initialize the mutex system.
   16170 */
   16171 SQLITE_PRIVATE int sqlite3MutexInit(void){
   16172   int rc = SQLITE_OK;
   16173   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
   16174     /* If the xMutexAlloc method has not been set, then the user did not
   16175     ** install a mutex implementation via sqlite3_config() prior to
   16176     ** sqlite3_initialize() being called. This block copies pointers to
   16177     ** the default implementation into the sqlite3GlobalConfig structure.
   16178     */
   16179     sqlite3_mutex_methods const *pFrom;
   16180     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
   16181 
   16182     if( sqlite3GlobalConfig.bCoreMutex ){
   16183       pFrom = sqlite3DefaultMutex();
   16184     }else{
   16185       pFrom = sqlite3NoopMutex();
   16186     }
   16187     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
   16188     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
   16189            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
   16190     pTo->xMutexAlloc = pFrom->xMutexAlloc;
   16191   }
   16192   rc = sqlite3GlobalConfig.mutex.xMutexInit();
   16193 
   16194 #ifdef SQLITE_DEBUG
   16195   GLOBAL(int, mutexIsInit) = 1;
   16196 #endif
   16197 
   16198   return rc;
   16199 }
   16200 
   16201 /*
   16202 ** Shutdown the mutex system. This call frees resources allocated by
   16203 ** sqlite3MutexInit().
   16204 */
   16205 SQLITE_PRIVATE int sqlite3MutexEnd(void){
   16206   int rc = SQLITE_OK;
   16207   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
   16208     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
   16209   }
   16210 
   16211 #ifdef SQLITE_DEBUG
   16212   GLOBAL(int, mutexIsInit) = 0;
   16213 #endif
   16214 
   16215   return rc;
   16216 }
   16217 
   16218 /*
   16219 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
   16220 */
   16221 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
   16222 #ifndef SQLITE_OMIT_AUTOINIT
   16223   if( sqlite3_initialize() ) return 0;
   16224 #endif
   16225   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   16226 }
   16227 
   16228 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
   16229   if( !sqlite3GlobalConfig.bCoreMutex ){
   16230     return 0;
   16231   }
   16232   assert( GLOBAL(int, mutexIsInit) );
   16233   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
   16234 }
   16235 
   16236 /*
   16237 ** Free a dynamic mutex.
   16238 */
   16239 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
   16240   if( p ){
   16241     sqlite3GlobalConfig.mutex.xMutexFree(p);
   16242   }
   16243 }
   16244 
   16245 /*
   16246 ** Obtain the mutex p. If some other thread already has the mutex, block
   16247 ** until it can be obtained.
   16248 */
   16249 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
   16250   if( p ){
   16251     sqlite3GlobalConfig.mutex.xMutexEnter(p);
   16252   }
   16253 }
   16254 
   16255 /*
   16256 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
   16257 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
   16258 */
   16259 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
   16260   int rc = SQLITE_OK;
   16261   if( p ){
   16262     return sqlite3GlobalConfig.mutex.xMutexTry(p);
   16263   }
   16264   return rc;
   16265 }
   16266 
   16267 /*
   16268 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
   16269 ** entered by the same thread.  The behavior is undefined if the mutex
   16270 ** is not currently entered. If a NULL pointer is passed as an argument
   16271 ** this function is a no-op.
   16272 */
   16273 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
   16274   if( p ){
   16275     sqlite3GlobalConfig.mutex.xMutexLeave(p);
   16276   }
   16277 }
   16278 
   16279 #ifndef NDEBUG
   16280 /*
   16281 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   16282 ** intended for use inside assert() statements.
   16283 */
   16284 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
   16285   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   16286 }
   16287 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
   16288   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   16289 }
   16290 #endif
   16291 
   16292 #endif /* SQLITE_MUTEX_OMIT */
   16293 
   16294 /************** End of mutex.c ***********************************************/
   16295 /************** Begin file mutex_noop.c **************************************/
   16296 /*
   16297 ** 2008 October 07
   16298 **
   16299 ** The author disclaims copyright to this source code.  In place of
   16300 ** a legal notice, here is a blessing:
   16301 **
   16302 **    May you do good and not evil.
   16303 **    May you find forgiveness for yourself and forgive others.
   16304 **    May you share freely, never taking more than you give.
   16305 **
   16306 *************************************************************************
   16307 ** This file contains the C functions that implement mutexes.
   16308 **
   16309 ** This implementation in this file does not provide any mutual
   16310 ** exclusion and is thus suitable for use only in applications
   16311 ** that use SQLite in a single thread.  The routines defined
   16312 ** here are place-holders.  Applications can substitute working
   16313 ** mutex routines at start-time using the
   16314 **
   16315 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
   16316 **
   16317 ** interface.
   16318 **
   16319 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
   16320 ** that does error checking on mutexes to make sure they are being
   16321 ** called correctly.
   16322 */
   16323 
   16324 #ifndef SQLITE_MUTEX_OMIT
   16325 
   16326 #ifndef SQLITE_DEBUG
   16327 /*
   16328 ** Stub routines for all mutex methods.
   16329 **
   16330 ** This routines provide no mutual exclusion or error checking.
   16331 */
   16332 static int noopMutexInit(void){ return SQLITE_OK; }
   16333 static int noopMutexEnd(void){ return SQLITE_OK; }
   16334 static sqlite3_mutex *noopMutexAlloc(int id){
   16335   UNUSED_PARAMETER(id);
   16336   return (sqlite3_mutex*)8;
   16337 }
   16338 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   16339 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   16340 static int noopMutexTry(sqlite3_mutex *p){
   16341   UNUSED_PARAMETER(p);
   16342   return SQLITE_OK;
   16343 }
   16344 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
   16345 
   16346 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   16347   static const sqlite3_mutex_methods sMutex = {
   16348     noopMutexInit,
   16349     noopMutexEnd,
   16350     noopMutexAlloc,
   16351     noopMutexFree,
   16352     noopMutexEnter,
   16353     noopMutexTry,
   16354     noopMutexLeave,
   16355 
   16356     0,
   16357     0,
   16358   };
   16359 
   16360   return &sMutex;
   16361 }
   16362 #endif /* !SQLITE_DEBUG */
   16363 
   16364 #ifdef SQLITE_DEBUG
   16365 /*
   16366 ** In this implementation, error checking is provided for testing
   16367 ** and debugging purposes.  The mutexes still do not provide any
   16368 ** mutual exclusion.
   16369 */
   16370 
   16371 /*
   16372 ** The mutex object
   16373 */
   16374 typedef struct sqlite3_debug_mutex {
   16375   int id;     /* The mutex type */
   16376   int cnt;    /* Number of entries without a matching leave */
   16377 } sqlite3_debug_mutex;
   16378 
   16379 /*
   16380 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   16381 ** intended for use inside assert() statements.
   16382 */
   16383 static int debugMutexHeld(sqlite3_mutex *pX){
   16384   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16385   return p==0 || p->cnt>0;
   16386 }
   16387 static int debugMutexNotheld(sqlite3_mutex *pX){
   16388   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16389   return p==0 || p->cnt==0;
   16390 }
   16391 
   16392 /*
   16393 ** Initialize and deinitialize the mutex subsystem.
   16394 */
   16395 static int debugMutexInit(void){ return SQLITE_OK; }
   16396 static int debugMutexEnd(void){ return SQLITE_OK; }
   16397 
   16398 /*
   16399 ** The sqlite3_mutex_alloc() routine allocates a new
   16400 ** mutex and returns a pointer to it.  If it returns NULL
   16401 ** that means that a mutex could not be allocated.
   16402 */
   16403 static sqlite3_mutex *debugMutexAlloc(int id){
   16404   static sqlite3_debug_mutex aStatic[6];
   16405   sqlite3_debug_mutex *pNew = 0;
   16406   switch( id ){
   16407     case SQLITE_MUTEX_FAST:
   16408     case SQLITE_MUTEX_RECURSIVE: {
   16409       pNew = sqlite3Malloc(sizeof(*pNew));
   16410       if( pNew ){
   16411         pNew->id = id;
   16412         pNew->cnt = 0;
   16413       }
   16414       break;
   16415     }
   16416     default: {
   16417       assert( id-2 >= 0 );
   16418       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
   16419       pNew = &aStatic[id-2];
   16420       pNew->id = id;
   16421       break;
   16422     }
   16423   }
   16424   return (sqlite3_mutex*)pNew;
   16425 }
   16426 
   16427 /*
   16428 ** This routine deallocates a previously allocated mutex.
   16429 */
   16430 static void debugMutexFree(sqlite3_mutex *pX){
   16431   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16432   assert( p->cnt==0 );
   16433   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   16434   sqlite3_free(p);
   16435 }
   16436 
   16437 /*
   16438 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   16439 ** to enter a mutex.  If another thread is already within the mutex,
   16440 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   16441 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   16442 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   16443 ** be entered multiple times by the same thread.  In such cases the,
   16444 ** mutex must be exited an equal number of times before another thread
   16445 ** can enter.  If the same thread tries to enter any other kind of mutex
   16446 ** more than once, the behavior is undefined.
   16447 */
   16448 static void debugMutexEnter(sqlite3_mutex *pX){
   16449   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16450   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   16451   p->cnt++;
   16452 }
   16453 static int debugMutexTry(sqlite3_mutex *pX){
   16454   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16455   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   16456   p->cnt++;
   16457   return SQLITE_OK;
   16458 }
   16459 
   16460 /*
   16461 ** The sqlite3_mutex_leave() routine exits a mutex that was
   16462 ** previously entered by the same thread.  The behavior
   16463 ** is undefined if the mutex is not currently entered or
   16464 ** is not currently allocated.  SQLite will never do either.
   16465 */
   16466 static void debugMutexLeave(sqlite3_mutex *pX){
   16467   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
   16468   assert( debugMutexHeld(pX) );
   16469   p->cnt--;
   16470   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
   16471 }
   16472 
   16473 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
   16474   static const sqlite3_mutex_methods sMutex = {
   16475     debugMutexInit,
   16476     debugMutexEnd,
   16477     debugMutexAlloc,
   16478     debugMutexFree,
   16479     debugMutexEnter,
   16480     debugMutexTry,
   16481     debugMutexLeave,
   16482 
   16483     debugMutexHeld,
   16484     debugMutexNotheld
   16485   };
   16486 
   16487   return &sMutex;
   16488 }
   16489 #endif /* SQLITE_DEBUG */
   16490 
   16491 /*
   16492 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
   16493 ** is used regardless of the run-time threadsafety setting.
   16494 */
   16495 #ifdef SQLITE_MUTEX_NOOP
   16496 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   16497   return sqlite3NoopMutex();
   16498 }
   16499 #endif /* SQLITE_MUTEX_NOOP */
   16500 #endif /* SQLITE_MUTEX_OMIT */
   16501 
   16502 /************** End of mutex_noop.c ******************************************/
   16503 /************** Begin file mutex_os2.c ***************************************/
   16504 /*
   16505 ** 2007 August 28
   16506 **
   16507 ** The author disclaims copyright to this source code.  In place of
   16508 ** a legal notice, here is a blessing:
   16509 **
   16510 **    May you do good and not evil.
   16511 **    May you find forgiveness for yourself and forgive others.
   16512 **    May you share freely, never taking more than you give.
   16513 **
   16514 *************************************************************************
   16515 ** This file contains the C functions that implement mutexes for OS/2
   16516 */
   16517 
   16518 /*
   16519 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
   16520 ** See the mutex.h file for details.
   16521 */
   16522 #ifdef SQLITE_MUTEX_OS2
   16523 
   16524 /********************** OS/2 Mutex Implementation **********************
   16525 **
   16526 ** This implementation of mutexes is built using the OS/2 API.
   16527 */
   16528 
   16529 /*
   16530 ** The mutex object
   16531 ** Each recursive mutex is an instance of the following structure.
   16532 */
   16533 struct sqlite3_mutex {
   16534   HMTX mutex;       /* Mutex controlling the lock */
   16535   int  id;          /* Mutex type */
   16536   int  nRef;        /* Number of references */
   16537   TID  owner;       /* Thread holding this mutex */
   16538 };
   16539 
   16540 #define OS2_MUTEX_INITIALIZER   0,0,0,0
   16541 
   16542 /*
   16543 ** Initialize and deinitialize the mutex subsystem.
   16544 */
   16545 static int os2MutexInit(void){ return SQLITE_OK; }
   16546 static int os2MutexEnd(void){ return SQLITE_OK; }
   16547 
   16548 /*
   16549 ** The sqlite3_mutex_alloc() routine allocates a new
   16550 ** mutex and returns a pointer to it.  If it returns NULL
   16551 ** that means that a mutex could not be allocated.
   16552 ** SQLite will unwind its stack and return an error.  The argument
   16553 ** to sqlite3_mutex_alloc() is one of these integer constants:
   16554 **
   16555 ** <ul>
   16556 ** <li>  SQLITE_MUTEX_FAST               0
   16557 ** <li>  SQLITE_MUTEX_RECURSIVE          1
   16558 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
   16559 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
   16560 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
   16561 ** </ul>
   16562 **
   16563 ** The first two constants cause sqlite3_mutex_alloc() to create
   16564 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   16565 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   16566 ** The mutex implementation does not need to make a distinction
   16567 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   16568 ** not want to.  But SQLite will only request a recursive mutex in
   16569 ** cases where it really needs one.  If a faster non-recursive mutex
   16570 ** implementation is available on the host platform, the mutex subsystem
   16571 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   16572 **
   16573 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   16574 ** a pointer to a static preexisting mutex.  Three static mutexes are
   16575 ** used by the current version of SQLite.  Future versions of SQLite
   16576 ** may add additional static mutexes.  Static mutexes are for internal
   16577 ** use by SQLite only.  Applications that use SQLite mutexes should
   16578 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   16579 ** SQLITE_MUTEX_RECURSIVE.
   16580 **
   16581 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   16582 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   16583 ** returns a different mutex on every call.  But for the static
   16584 ** mutex types, the same mutex is returned on every call that has
   16585 ** the same type number.
   16586 */
   16587 static sqlite3_mutex *os2MutexAlloc(int iType){
   16588   sqlite3_mutex *p = NULL;
   16589   switch( iType ){
   16590     case SQLITE_MUTEX_FAST:
   16591     case SQLITE_MUTEX_RECURSIVE: {
   16592       p = sqlite3MallocZero( sizeof(*p) );
   16593       if( p ){
   16594         p->id = iType;
   16595         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
   16596           sqlite3_free( p );
   16597           p = NULL;
   16598         }
   16599       }
   16600       break;
   16601     }
   16602     default: {
   16603       static volatile int isInit = 0;
   16604       static sqlite3_mutex staticMutexes[] = {
   16605         { OS2_MUTEX_INITIALIZER, },
   16606         { OS2_MUTEX_INITIALIZER, },
   16607         { OS2_MUTEX_INITIALIZER, },
   16608         { OS2_MUTEX_INITIALIZER, },
   16609         { OS2_MUTEX_INITIALIZER, },
   16610         { OS2_MUTEX_INITIALIZER, },
   16611       };
   16612       if ( !isInit ){
   16613         APIRET rc;
   16614         PTIB ptib;
   16615         PPIB ppib;
   16616         HMTX mutex;
   16617         char name[32];
   16618         DosGetInfoBlocks( &ptib, &ppib );
   16619         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
   16620                           ppib->pib_ulpid );
   16621         while( !isInit ){
   16622           mutex = 0;
   16623           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
   16624           if( rc == NO_ERROR ){
   16625             unsigned int i;
   16626             if( !isInit ){
   16627               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
   16628                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
   16629               }
   16630               isInit = 1;
   16631             }
   16632             DosCloseMutexSem( mutex );
   16633           }else if( rc == ERROR_DUPLICATE_NAME ){
   16634             DosSleep( 1 );
   16635           }else{
   16636             return p;
   16637           }
   16638         }
   16639       }
   16640       assert( iType-2 >= 0 );
   16641       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
   16642       p = &staticMutexes[iType-2];
   16643       p->id = iType;
   16644       break;
   16645     }
   16646   }
   16647   return p;
   16648 }
   16649 
   16650 
   16651 /*
   16652 ** This routine deallocates a previously allocated mutex.
   16653 ** SQLite is careful to deallocate every mutex that it allocates.
   16654 */
   16655 static void os2MutexFree(sqlite3_mutex *p){
   16656   if( p==0 ) return;
   16657   assert( p->nRef==0 );
   16658   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   16659   DosCloseMutexSem( p->mutex );
   16660   sqlite3_free( p );
   16661 }
   16662 
   16663 #ifdef SQLITE_DEBUG
   16664 /*
   16665 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   16666 ** intended for use inside assert() statements.
   16667 */
   16668 static int os2MutexHeld(sqlite3_mutex *p){
   16669   TID tid;
   16670   PID pid;
   16671   ULONG ulCount;
   16672   PTIB ptib;
   16673   if( p!=0 ) {
   16674     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   16675   } else {
   16676     DosGetInfoBlocks(&ptib, NULL);
   16677     tid = ptib->tib_ptib2->tib2_ultid;
   16678   }
   16679   return p==0 || (p->nRef!=0 && p->owner==tid);
   16680 }
   16681 static int os2MutexNotheld(sqlite3_mutex *p){
   16682   TID tid;
   16683   PID pid;
   16684   ULONG ulCount;
   16685   PTIB ptib;
   16686   if( p!= 0 ) {
   16687     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
   16688   } else {
   16689     DosGetInfoBlocks(&ptib, NULL);
   16690     tid = ptib->tib_ptib2->tib2_ultid;
   16691   }
   16692   return p==0 || p->nRef==0 || p->owner!=tid;
   16693 }
   16694 #endif
   16695 
   16696 /*
   16697 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   16698 ** to enter a mutex.  If another thread is already within the mutex,
   16699 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   16700 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   16701 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   16702 ** be entered multiple times by the same thread.  In such cases the,
   16703 ** mutex must be exited an equal number of times before another thread
   16704 ** can enter.  If the same thread tries to enter any other kind of mutex
   16705 ** more than once, the behavior is undefined.
   16706 */
   16707 static void os2MutexEnter(sqlite3_mutex *p){
   16708   TID tid;
   16709   PID holder1;
   16710   ULONG holder2;
   16711   if( p==0 ) return;
   16712   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   16713   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
   16714   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   16715   p->owner = tid;
   16716   p->nRef++;
   16717 }
   16718 static int os2MutexTry(sqlite3_mutex *p){
   16719   int rc;
   16720   TID tid;
   16721   PID holder1;
   16722   ULONG holder2;
   16723   if( p==0 ) return SQLITE_OK;
   16724   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
   16725   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
   16726     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   16727     p->owner = tid;
   16728     p->nRef++;
   16729     rc = SQLITE_OK;
   16730   } else {
   16731     rc = SQLITE_BUSY;
   16732   }
   16733 
   16734   return rc;
   16735 }
   16736 
   16737 /*
   16738 ** The sqlite3_mutex_leave() routine exits a mutex that was
   16739 ** previously entered by the same thread.  The behavior
   16740 ** is undefined if the mutex is not currently entered or
   16741 ** is not currently allocated.  SQLite will never do either.
   16742 */
   16743 static void os2MutexLeave(sqlite3_mutex *p){
   16744   TID tid;
   16745   PID holder1;
   16746   ULONG holder2;
   16747   if( p==0 ) return;
   16748   assert( p->nRef>0 );
   16749   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
   16750   assert( p->owner==tid );
   16751   p->nRef--;
   16752   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   16753   DosReleaseMutexSem(p->mutex);
   16754 }
   16755 
   16756 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   16757   static const sqlite3_mutex_methods sMutex = {
   16758     os2MutexInit,
   16759     os2MutexEnd,
   16760     os2MutexAlloc,
   16761     os2MutexFree,
   16762     os2MutexEnter,
   16763     os2MutexTry,
   16764     os2MutexLeave,
   16765 #ifdef SQLITE_DEBUG
   16766     os2MutexHeld,
   16767     os2MutexNotheld
   16768 #endif
   16769   };
   16770 
   16771   return &sMutex;
   16772 }
   16773 #endif /* SQLITE_MUTEX_OS2 */
   16774 
   16775 /************** End of mutex_os2.c *******************************************/
   16776 /************** Begin file mutex_unix.c **************************************/
   16777 /*
   16778 ** 2007 August 28
   16779 **
   16780 ** The author disclaims copyright to this source code.  In place of
   16781 ** a legal notice, here is a blessing:
   16782 **
   16783 **    May you do good and not evil.
   16784 **    May you find forgiveness for yourself and forgive others.
   16785 **    May you share freely, never taking more than you give.
   16786 **
   16787 *************************************************************************
   16788 ** This file contains the C functions that implement mutexes for pthreads
   16789 */
   16790 
   16791 /*
   16792 ** The code in this file is only used if we are compiling threadsafe
   16793 ** under unix with pthreads.
   16794 **
   16795 ** Note that this implementation requires a version of pthreads that
   16796 ** supports recursive mutexes.
   16797 */
   16798 #ifdef SQLITE_MUTEX_PTHREADS
   16799 
   16800 #include <pthread.h>
   16801 
   16802 /*
   16803 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
   16804 ** are necessary under two condidtions:  (1) Debug builds and (2) using
   16805 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
   16806 */
   16807 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
   16808 # define SQLITE_MUTEX_NREF 1
   16809 #else
   16810 # define SQLITE_MUTEX_NREF 0
   16811 #endif
   16812 
   16813 /*
   16814 ** Each recursive mutex is an instance of the following structure.
   16815 */
   16816 struct sqlite3_mutex {
   16817   pthread_mutex_t mutex;     /* Mutex controlling the lock */
   16818 #if SQLITE_MUTEX_NREF
   16819   int id;                    /* Mutex type */
   16820   volatile int nRef;         /* Number of entrances */
   16821   volatile pthread_t owner;  /* Thread that is within this mutex */
   16822   int trace;                 /* True to trace changes */
   16823 #endif
   16824 };
   16825 #if SQLITE_MUTEX_NREF
   16826 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
   16827 #else
   16828 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
   16829 #endif
   16830 
   16831 /*
   16832 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   16833 ** intended for use only inside assert() statements.  On some platforms,
   16834 ** there might be race conditions that can cause these routines to
   16835 ** deliver incorrect results.  In particular, if pthread_equal() is
   16836 ** not an atomic operation, then these routines might delivery
   16837 ** incorrect results.  On most platforms, pthread_equal() is a
   16838 ** comparison of two integers and is therefore atomic.  But we are
   16839 ** told that HPUX is not such a platform.  If so, then these routines
   16840 ** will not always work correctly on HPUX.
   16841 **
   16842 ** On those platforms where pthread_equal() is not atomic, SQLite
   16843 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
   16844 ** make sure no assert() statements are evaluated and hence these
   16845 ** routines are never called.
   16846 */
   16847 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
   16848 static int pthreadMutexHeld(sqlite3_mutex *p){
   16849   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
   16850 }
   16851 static int pthreadMutexNotheld(sqlite3_mutex *p){
   16852   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
   16853 }
   16854 #endif
   16855 
   16856 /*
   16857 ** Initialize and deinitialize the mutex subsystem.
   16858 */
   16859 static int pthreadMutexInit(void){ return SQLITE_OK; }
   16860 static int pthreadMutexEnd(void){ return SQLITE_OK; }
   16861 
   16862 /*
   16863 ** The sqlite3_mutex_alloc() routine allocates a new
   16864 ** mutex and returns a pointer to it.  If it returns NULL
   16865 ** that means that a mutex could not be allocated.  SQLite
   16866 ** will unwind its stack and return an error.  The argument
   16867 ** to sqlite3_mutex_alloc() is one of these integer constants:
   16868 **
   16869 ** <ul>
   16870 ** <li>  SQLITE_MUTEX_FAST
   16871 ** <li>  SQLITE_MUTEX_RECURSIVE
   16872 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   16873 ** <li>  SQLITE_MUTEX_STATIC_MEM
   16874 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   16875 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   16876 ** <li>  SQLITE_MUTEX_STATIC_LRU
   16877 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   16878 ** </ul>
   16879 **
   16880 ** The first two constants cause sqlite3_mutex_alloc() to create
   16881 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   16882 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   16883 ** The mutex implementation does not need to make a distinction
   16884 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   16885 ** not want to.  But SQLite will only request a recursive mutex in
   16886 ** cases where it really needs one.  If a faster non-recursive mutex
   16887 ** implementation is available on the host platform, the mutex subsystem
   16888 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   16889 **
   16890 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   16891 ** a pointer to a static preexisting mutex.  Six static mutexes are
   16892 ** used by the current version of SQLite.  Future versions of SQLite
   16893 ** may add additional static mutexes.  Static mutexes are for internal
   16894 ** use by SQLite only.  Applications that use SQLite mutexes should
   16895 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   16896 ** SQLITE_MUTEX_RECURSIVE.
   16897 **
   16898 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   16899 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   16900 ** returns a different mutex on every call.  But for the static
   16901 ** mutex types, the same mutex is returned on every call that has
   16902 ** the same type number.
   16903 */
   16904 static sqlite3_mutex *pthreadMutexAlloc(int iType){
   16905   static sqlite3_mutex staticMutexes[] = {
   16906     SQLITE3_MUTEX_INITIALIZER,
   16907     SQLITE3_MUTEX_INITIALIZER,
   16908     SQLITE3_MUTEX_INITIALIZER,
   16909     SQLITE3_MUTEX_INITIALIZER,
   16910     SQLITE3_MUTEX_INITIALIZER,
   16911     SQLITE3_MUTEX_INITIALIZER
   16912   };
   16913   sqlite3_mutex *p;
   16914   switch( iType ){
   16915     case SQLITE_MUTEX_RECURSIVE: {
   16916       p = sqlite3MallocZero( sizeof(*p) );
   16917       if( p ){
   16918 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   16919         /* If recursive mutexes are not available, we will have to
   16920         ** build our own.  See below. */
   16921         pthread_mutex_init(&p->mutex, 0);
   16922 #else
   16923         /* Use a recursive mutex if it is available */
   16924         pthread_mutexattr_t recursiveAttr;
   16925         pthread_mutexattr_init(&recursiveAttr);
   16926         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
   16927         pthread_mutex_init(&p->mutex, &recursiveAttr);
   16928         pthread_mutexattr_destroy(&recursiveAttr);
   16929 #endif
   16930 #if SQLITE_MUTEX_NREF
   16931         p->id = iType;
   16932 #endif
   16933       }
   16934       break;
   16935     }
   16936     case SQLITE_MUTEX_FAST: {
   16937       p = sqlite3MallocZero( sizeof(*p) );
   16938       if( p ){
   16939 #if SQLITE_MUTEX_NREF
   16940         p->id = iType;
   16941 #endif
   16942         pthread_mutex_init(&p->mutex, 0);
   16943       }
   16944       break;
   16945     }
   16946     default: {
   16947       assert( iType-2 >= 0 );
   16948       assert( iType-2 < ArraySize(staticMutexes) );
   16949       p = &staticMutexes[iType-2];
   16950 #if SQLITE_MUTEX_NREF
   16951       p->id = iType;
   16952 #endif
   16953       break;
   16954     }
   16955   }
   16956   return p;
   16957 }
   16958 
   16959 
   16960 /*
   16961 ** This routine deallocates a previously
   16962 ** allocated mutex.  SQLite is careful to deallocate every
   16963 ** mutex that it allocates.
   16964 */
   16965 static void pthreadMutexFree(sqlite3_mutex *p){
   16966   assert( p->nRef==0 );
   16967   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   16968   pthread_mutex_destroy(&p->mutex);
   16969   sqlite3_free(p);
   16970 }
   16971 
   16972 /*
   16973 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   16974 ** to enter a mutex.  If another thread is already within the mutex,
   16975 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   16976 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   16977 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   16978 ** be entered multiple times by the same thread.  In such cases the,
   16979 ** mutex must be exited an equal number of times before another thread
   16980 ** can enter.  If the same thread tries to enter any other kind of mutex
   16981 ** more than once, the behavior is undefined.
   16982 */
   16983 static void pthreadMutexEnter(sqlite3_mutex *p){
   16984   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   16985 
   16986 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   16987   /* If recursive mutexes are not available, then we have to grow
   16988   ** our own.  This implementation assumes that pthread_equal()
   16989   ** is atomic - that it cannot be deceived into thinking self
   16990   ** and p->owner are equal if p->owner changes between two values
   16991   ** that are not equal to self while the comparison is taking place.
   16992   ** This implementation also assumes a coherent cache - that
   16993   ** separate processes cannot read different values from the same
   16994   ** address at the same time.  If either of these two conditions
   16995   ** are not met, then the mutexes will fail and problems will result.
   16996   */
   16997   {
   16998     pthread_t self = pthread_self();
   16999     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   17000       p->nRef++;
   17001     }else{
   17002       pthread_mutex_lock(&p->mutex);
   17003       assert( p->nRef==0 );
   17004       p->owner = self;
   17005       p->nRef = 1;
   17006     }
   17007   }
   17008 #else
   17009   /* Use the built-in recursive mutexes if they are available.
   17010   */
   17011   pthread_mutex_lock(&p->mutex);
   17012 #if SQLITE_MUTEX_NREF
   17013   assert( p->nRef>0 || p->owner==0 );
   17014   p->owner = pthread_self();
   17015   p->nRef++;
   17016 #endif
   17017 #endif
   17018 
   17019 #ifdef SQLITE_DEBUG
   17020   if( p->trace ){
   17021     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17022   }
   17023 #endif
   17024 }
   17025 static int pthreadMutexTry(sqlite3_mutex *p){
   17026   int rc;
   17027   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
   17028 
   17029 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   17030   /* If recursive mutexes are not available, then we have to grow
   17031   ** our own.  This implementation assumes that pthread_equal()
   17032   ** is atomic - that it cannot be deceived into thinking self
   17033   ** and p->owner are equal if p->owner changes between two values
   17034   ** that are not equal to self while the comparison is taking place.
   17035   ** This implementation also assumes a coherent cache - that
   17036   ** separate processes cannot read different values from the same
   17037   ** address at the same time.  If either of these two conditions
   17038   ** are not met, then the mutexes will fail and problems will result.
   17039   */
   17040   {
   17041     pthread_t self = pthread_self();
   17042     if( p->nRef>0 && pthread_equal(p->owner, self) ){
   17043       p->nRef++;
   17044       rc = SQLITE_OK;
   17045     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
   17046       assert( p->nRef==0 );
   17047       p->owner = self;
   17048       p->nRef = 1;
   17049       rc = SQLITE_OK;
   17050     }else{
   17051       rc = SQLITE_BUSY;
   17052     }
   17053   }
   17054 #else
   17055   /* Use the built-in recursive mutexes if they are available.
   17056   */
   17057   if( pthread_mutex_trylock(&p->mutex)==0 ){
   17058 #if SQLITE_MUTEX_NREF
   17059     p->owner = pthread_self();
   17060     p->nRef++;
   17061 #endif
   17062     rc = SQLITE_OK;
   17063   }else{
   17064     rc = SQLITE_BUSY;
   17065   }
   17066 #endif
   17067 
   17068 #ifdef SQLITE_DEBUG
   17069   if( rc==SQLITE_OK && p->trace ){
   17070     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17071   }
   17072 #endif
   17073   return rc;
   17074 }
   17075 
   17076 /*
   17077 ** The sqlite3_mutex_leave() routine exits a mutex that was
   17078 ** previously entered by the same thread.  The behavior
   17079 ** is undefined if the mutex is not currently entered or
   17080 ** is not currently allocated.  SQLite will never do either.
   17081 */
   17082 static void pthreadMutexLeave(sqlite3_mutex *p){
   17083   assert( pthreadMutexHeld(p) );
   17084 #if SQLITE_MUTEX_NREF
   17085   p->nRef--;
   17086   if( p->nRef==0 ) p->owner = 0;
   17087 #endif
   17088   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   17089 
   17090 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
   17091   if( p->nRef==0 ){
   17092     pthread_mutex_unlock(&p->mutex);
   17093   }
   17094 #else
   17095   pthread_mutex_unlock(&p->mutex);
   17096 #endif
   17097 
   17098 #ifdef SQLITE_DEBUG
   17099   if( p->trace ){
   17100     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17101   }
   17102 #endif
   17103 }
   17104 
   17105 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   17106   static const sqlite3_mutex_methods sMutex = {
   17107     pthreadMutexInit,
   17108     pthreadMutexEnd,
   17109     pthreadMutexAlloc,
   17110     pthreadMutexFree,
   17111     pthreadMutexEnter,
   17112     pthreadMutexTry,
   17113     pthreadMutexLeave,
   17114 #ifdef SQLITE_DEBUG
   17115     pthreadMutexHeld,
   17116     pthreadMutexNotheld
   17117 #else
   17118     0,
   17119     0
   17120 #endif
   17121   };
   17122 
   17123   return &sMutex;
   17124 }
   17125 
   17126 #endif /* SQLITE_MUTEX_PTHREAD */
   17127 
   17128 /************** End of mutex_unix.c ******************************************/
   17129 /************** Begin file mutex_w32.c ***************************************/
   17130 /*
   17131 ** 2007 August 14
   17132 **
   17133 ** The author disclaims copyright to this source code.  In place of
   17134 ** a legal notice, here is a blessing:
   17135 **
   17136 **    May you do good and not evil.
   17137 **    May you find forgiveness for yourself and forgive others.
   17138 **    May you share freely, never taking more than you give.
   17139 **
   17140 *************************************************************************
   17141 ** This file contains the C functions that implement mutexes for win32
   17142 */
   17143 
   17144 /*
   17145 ** The code in this file is only used if we are compiling multithreaded
   17146 ** on a win32 system.
   17147 */
   17148 #ifdef SQLITE_MUTEX_W32
   17149 
   17150 /*
   17151 ** Each recursive mutex is an instance of the following structure.
   17152 */
   17153 struct sqlite3_mutex {
   17154   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
   17155   int id;                    /* Mutex type */
   17156 #ifdef SQLITE_DEBUG
   17157   volatile int nRef;         /* Number of enterances */
   17158   volatile DWORD owner;      /* Thread holding this mutex */
   17159   int trace;                 /* True to trace changes */
   17160 #endif
   17161 };
   17162 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
   17163 #ifdef SQLITE_DEBUG
   17164 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
   17165 #else
   17166 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
   17167 #endif
   17168 
   17169 /*
   17170 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   17171 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   17172 **
   17173 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   17174 ** the LockFileEx() API.  But we can still statically link against that
   17175 ** API as long as we don't call it win running Win95/98/ME.  A call to
   17176 ** this routine is used to determine if the host is Win95/98/ME or
   17177 ** WinNT/2K/XP so that we will know whether or not we can safely call
   17178 ** the LockFileEx() API.
   17179 **
   17180 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
   17181 ** which is only available if your application was compiled with
   17182 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
   17183 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
   17184 ** this out as well.
   17185 */
   17186 #if 0
   17187 #if SQLITE_OS_WINCE
   17188 # define mutexIsNT()  (1)
   17189 #else
   17190   static int mutexIsNT(void){
   17191     static int osType = 0;
   17192     if( osType==0 ){
   17193       OSVERSIONINFO sInfo;
   17194       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   17195       GetVersionEx(&sInfo);
   17196       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   17197     }
   17198     return osType==2;
   17199   }
   17200 #endif /* SQLITE_OS_WINCE */
   17201 #endif
   17202 
   17203 #ifdef SQLITE_DEBUG
   17204 /*
   17205 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
   17206 ** intended for use only inside assert() statements.
   17207 */
   17208 static int winMutexHeld(sqlite3_mutex *p){
   17209   return p->nRef!=0 && p->owner==GetCurrentThreadId();
   17210 }
   17211 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
   17212   return p->nRef==0 || p->owner!=tid;
   17213 }
   17214 static int winMutexNotheld(sqlite3_mutex *p){
   17215   DWORD tid = GetCurrentThreadId();
   17216   return winMutexNotheld2(p, tid);
   17217 }
   17218 #endif
   17219 
   17220 
   17221 /*
   17222 ** Initialize and deinitialize the mutex subsystem.
   17223 */
   17224 static sqlite3_mutex winMutex_staticMutexes[6] = {
   17225   SQLITE3_MUTEX_INITIALIZER,
   17226   SQLITE3_MUTEX_INITIALIZER,
   17227   SQLITE3_MUTEX_INITIALIZER,
   17228   SQLITE3_MUTEX_INITIALIZER,
   17229   SQLITE3_MUTEX_INITIALIZER,
   17230   SQLITE3_MUTEX_INITIALIZER
   17231 };
   17232 static int winMutex_isInit = 0;
   17233 /* As winMutexInit() and winMutexEnd() are called as part
   17234 ** of the sqlite3_initialize and sqlite3_shutdown()
   17235 ** processing, the "interlocked" magic is probably not
   17236 ** strictly necessary.
   17237 */
   17238 static long winMutex_lock = 0;
   17239 
   17240 static int winMutexInit(void){
   17241   /* The first to increment to 1 does actual initialization */
   17242   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
   17243     int i;
   17244     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   17245       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
   17246     }
   17247     winMutex_isInit = 1;
   17248   }else{
   17249     /* Someone else is in the process of initing the static mutexes */
   17250     while( !winMutex_isInit ){
   17251       Sleep(1);
   17252     }
   17253   }
   17254   return SQLITE_OK;
   17255 }
   17256 
   17257 static int winMutexEnd(void){
   17258   /* The first to decrement to 0 does actual shutdown
   17259   ** (which should be the last to shutdown.) */
   17260   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
   17261     if( winMutex_isInit==1 ){
   17262       int i;
   17263       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
   17264         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
   17265       }
   17266       winMutex_isInit = 0;
   17267     }
   17268   }
   17269   return SQLITE_OK;
   17270 }
   17271 
   17272 /*
   17273 ** The sqlite3_mutex_alloc() routine allocates a new
   17274 ** mutex and returns a pointer to it.  If it returns NULL
   17275 ** that means that a mutex could not be allocated.  SQLite
   17276 ** will unwind its stack and return an error.  The argument
   17277 ** to sqlite3_mutex_alloc() is one of these integer constants:
   17278 **
   17279 ** <ul>
   17280 ** <li>  SQLITE_MUTEX_FAST
   17281 ** <li>  SQLITE_MUTEX_RECURSIVE
   17282 ** <li>  SQLITE_MUTEX_STATIC_MASTER
   17283 ** <li>  SQLITE_MUTEX_STATIC_MEM
   17284 ** <li>  SQLITE_MUTEX_STATIC_MEM2
   17285 ** <li>  SQLITE_MUTEX_STATIC_PRNG
   17286 ** <li>  SQLITE_MUTEX_STATIC_LRU
   17287 ** <li>  SQLITE_MUTEX_STATIC_LRU2
   17288 ** </ul>
   17289 **
   17290 ** The first two constants cause sqlite3_mutex_alloc() to create
   17291 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
   17292 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
   17293 ** The mutex implementation does not need to make a distinction
   17294 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
   17295 ** not want to.  But SQLite will only request a recursive mutex in
   17296 ** cases where it really needs one.  If a faster non-recursive mutex
   17297 ** implementation is available on the host platform, the mutex subsystem
   17298 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
   17299 **
   17300 ** The other allowed parameters to sqlite3_mutex_alloc() each return
   17301 ** a pointer to a static preexisting mutex.  Six static mutexes are
   17302 ** used by the current version of SQLite.  Future versions of SQLite
   17303 ** may add additional static mutexes.  Static mutexes are for internal
   17304 ** use by SQLite only.  Applications that use SQLite mutexes should
   17305 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
   17306 ** SQLITE_MUTEX_RECURSIVE.
   17307 **
   17308 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
   17309 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
   17310 ** returns a different mutex on every call.  But for the static
   17311 ** mutex types, the same mutex is returned on every call that has
   17312 ** the same type number.
   17313 */
   17314 static sqlite3_mutex *winMutexAlloc(int iType){
   17315   sqlite3_mutex *p;
   17316 
   17317   switch( iType ){
   17318     case SQLITE_MUTEX_FAST:
   17319     case SQLITE_MUTEX_RECURSIVE: {
   17320       p = sqlite3MallocZero( sizeof(*p) );
   17321       if( p ){
   17322 #ifdef SQLITE_DEBUG
   17323         p->id = iType;
   17324 #endif
   17325         InitializeCriticalSection(&p->mutex);
   17326       }
   17327       break;
   17328     }
   17329     default: {
   17330       assert( winMutex_isInit==1 );
   17331       assert( iType-2 >= 0 );
   17332       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
   17333       p = &winMutex_staticMutexes[iType-2];
   17334 #ifdef SQLITE_DEBUG
   17335       p->id = iType;
   17336 #endif
   17337       break;
   17338     }
   17339   }
   17340   return p;
   17341 }
   17342 
   17343 
   17344 /*
   17345 ** This routine deallocates a previously
   17346 ** allocated mutex.  SQLite is careful to deallocate every
   17347 ** mutex that it allocates.
   17348 */
   17349 static void winMutexFree(sqlite3_mutex *p){
   17350   assert( p );
   17351   assert( p->nRef==0 && p->owner==0 );
   17352   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
   17353   DeleteCriticalSection(&p->mutex);
   17354   sqlite3_free(p);
   17355 }
   17356 
   17357 /*
   17358 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
   17359 ** to enter a mutex.  If another thread is already within the mutex,
   17360 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
   17361 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
   17362 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
   17363 ** be entered multiple times by the same thread.  In such cases the,
   17364 ** mutex must be exited an equal number of times before another thread
   17365 ** can enter.  If the same thread tries to enter any other kind of mutex
   17366 ** more than once, the behavior is undefined.
   17367 */
   17368 static void winMutexEnter(sqlite3_mutex *p){
   17369 #ifdef SQLITE_DEBUG
   17370   DWORD tid = GetCurrentThreadId();
   17371   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   17372 #endif
   17373   EnterCriticalSection(&p->mutex);
   17374 #ifdef SQLITE_DEBUG
   17375   assert( p->nRef>0 || p->owner==0 );
   17376   p->owner = tid;
   17377   p->nRef++;
   17378   if( p->trace ){
   17379     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17380   }
   17381 #endif
   17382 }
   17383 static int winMutexTry(sqlite3_mutex *p){
   17384 #ifndef NDEBUG
   17385   DWORD tid = GetCurrentThreadId();
   17386 #endif
   17387   int rc = SQLITE_BUSY;
   17388   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
   17389   /*
   17390   ** The sqlite3_mutex_try() routine is very rarely used, and when it
   17391   ** is used it is merely an optimization.  So it is OK for it to always
   17392   ** fail.
   17393   **
   17394   ** The TryEnterCriticalSection() interface is only available on WinNT.
   17395   ** And some windows compilers complain if you try to use it without
   17396   ** first doing some #defines that prevent SQLite from building on Win98.
   17397   ** For that reason, we will omit this optimization for now.  See
   17398   ** ticket #2685.
   17399   */
   17400 #if 0
   17401   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
   17402     p->owner = tid;
   17403     p->nRef++;
   17404     rc = SQLITE_OK;
   17405   }
   17406 #else
   17407   UNUSED_PARAMETER(p);
   17408 #endif
   17409 #ifdef SQLITE_DEBUG
   17410   if( rc==SQLITE_OK && p->trace ){
   17411     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17412   }
   17413 #endif
   17414   return rc;
   17415 }
   17416 
   17417 /*
   17418 ** The sqlite3_mutex_leave() routine exits a mutex that was
   17419 ** previously entered by the same thread.  The behavior
   17420 ** is undefined if the mutex is not currently entered or
   17421 ** is not currently allocated.  SQLite will never do either.
   17422 */
   17423 static void winMutexLeave(sqlite3_mutex *p){
   17424 #ifndef NDEBUG
   17425   DWORD tid = GetCurrentThreadId();
   17426   assert( p->nRef>0 );
   17427   assert( p->owner==tid );
   17428   p->nRef--;
   17429   if( p->nRef==0 ) p->owner = 0;
   17430   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
   17431 #endif
   17432   LeaveCriticalSection(&p->mutex);
   17433 #ifdef SQLITE_DEBUG
   17434   if( p->trace ){
   17435     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
   17436   }
   17437 #endif
   17438 }
   17439 
   17440 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   17441   static const sqlite3_mutex_methods sMutex = {
   17442     winMutexInit,
   17443     winMutexEnd,
   17444     winMutexAlloc,
   17445     winMutexFree,
   17446     winMutexEnter,
   17447     winMutexTry,
   17448     winMutexLeave,
   17449 #ifdef SQLITE_DEBUG
   17450     winMutexHeld,
   17451     winMutexNotheld
   17452 #else
   17453     0,
   17454     0
   17455 #endif
   17456   };
   17457 
   17458   return &sMutex;
   17459 }
   17460 #endif /* SQLITE_MUTEX_W32 */
   17461 
   17462 /************** End of mutex_w32.c *******************************************/
   17463 /************** Begin file malloc.c ******************************************/
   17464 /*
   17465 ** 2001 September 15
   17466 **
   17467 ** The author disclaims copyright to this source code.  In place of
   17468 ** a legal notice, here is a blessing:
   17469 **
   17470 **    May you do good and not evil.
   17471 **    May you find forgiveness for yourself and forgive others.
   17472 **    May you share freely, never taking more than you give.
   17473 **
   17474 *************************************************************************
   17475 **
   17476 ** Memory allocation functions used throughout sqlite.
   17477 */
   17478 
   17479 /*
   17480 ** Attempt to release up to n bytes of non-essential memory currently
   17481 ** held by SQLite. An example of non-essential memory is memory used to
   17482 ** cache database pages that are not currently in use.
   17483 */
   17484 SQLITE_API int sqlite3_release_memory(int n){
   17485 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   17486   return sqlite3PcacheReleaseMemory(n);
   17487 #else
   17488   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
   17489   ** is a no-op returning zero if SQLite is not compiled with
   17490   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
   17491   UNUSED_PARAMETER(n);
   17492   return 0;
   17493 #endif
   17494 }
   17495 
   17496 /*
   17497 ** An instance of the following object records the location of
   17498 ** each unused scratch buffer.
   17499 */
   17500 typedef struct ScratchFreeslot {
   17501   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
   17502 } ScratchFreeslot;
   17503 
   17504 /*
   17505 ** State information local to the memory allocation subsystem.
   17506 */
   17507 static SQLITE_WSD struct Mem0Global {
   17508   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   17509 
   17510   /*
   17511   ** The alarm callback and its arguments.  The mem0.mutex lock will
   17512   ** be held while the callback is running.  Recursive calls into
   17513   ** the memory subsystem are allowed, but no new callbacks will be
   17514   ** issued.
   17515   */
   17516   sqlite3_int64 alarmThreshold;
   17517   void (*alarmCallback)(void*, sqlite3_int64,int);
   17518   void *alarmArg;
   17519 
   17520   /*
   17521   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
   17522   ** (so that a range test can be used to determine if an allocation
   17523   ** being freed came from pScratch) and a pointer to the list of
   17524   ** unused scratch allocations.
   17525   */
   17526   void *pScratchEnd;
   17527   ScratchFreeslot *pScratchFree;
   17528   u32 nScratchFree;
   17529 
   17530   /*
   17531   ** True if heap is nearly "full" where "full" is defined by the
   17532   ** sqlite3_soft_heap_limit() setting.
   17533   */
   17534   int nearlyFull;
   17535 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
   17536 
   17537 #define mem0 GLOBAL(struct Mem0Global, mem0)
   17538 
   17539 /*
   17540 ** This routine runs when the memory allocator sees that the
   17541 ** total memory allocation is about to exceed the soft heap
   17542 ** limit.
   17543 */
   17544 static void softHeapLimitEnforcer(
   17545   void *NotUsed,
   17546   sqlite3_int64 NotUsed2,
   17547   int allocSize
   17548 ){
   17549   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   17550   sqlite3_release_memory(allocSize);
   17551 }
   17552 
   17553 /*
   17554 ** Change the alarm callback
   17555 */
   17556 static int sqlite3MemoryAlarm(
   17557   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   17558   void *pArg,
   17559   sqlite3_int64 iThreshold
   17560 ){
   17561   int nUsed;
   17562   sqlite3_mutex_enter(mem0.mutex);
   17563   mem0.alarmCallback = xCallback;
   17564   mem0.alarmArg = pArg;
   17565   mem0.alarmThreshold = iThreshold;
   17566   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   17567   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
   17568   sqlite3_mutex_leave(mem0.mutex);
   17569   return SQLITE_OK;
   17570 }
   17571 
   17572 #ifndef SQLITE_OMIT_DEPRECATED
   17573 /*
   17574 ** Deprecated external interface.  Internal/core SQLite code
   17575 ** should call sqlite3MemoryAlarm.
   17576 */
   17577 SQLITE_API int sqlite3_memory_alarm(
   17578   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
   17579   void *pArg,
   17580   sqlite3_int64 iThreshold
   17581 ){
   17582   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
   17583 }
   17584 #endif
   17585 
   17586 /*
   17587 ** Set the soft heap-size limit for the library. Passing a zero or
   17588 ** negative value indicates no limit.
   17589 */
   17590 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   17591   sqlite3_int64 priorLimit;
   17592   sqlite3_int64 excess;
   17593 #ifndef SQLITE_OMIT_AUTOINIT
   17594   sqlite3_initialize();
   17595 #endif
   17596   sqlite3_mutex_enter(mem0.mutex);
   17597   priorLimit = mem0.alarmThreshold;
   17598   sqlite3_mutex_leave(mem0.mutex);
   17599   if( n<0 ) return priorLimit;
   17600   if( n>0 ){
   17601     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
   17602   }else{
   17603     sqlite3MemoryAlarm(0, 0, 0);
   17604   }
   17605   excess = sqlite3_memory_used() - n;
   17606   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
   17607   return priorLimit;
   17608 }
   17609 SQLITE_API void sqlite3_soft_heap_limit(int n){
   17610   if( n<0 ) n = 0;
   17611   sqlite3_soft_heap_limit64(n);
   17612 }
   17613 
   17614 /*
   17615 ** Initialize the memory allocation subsystem.
   17616 */
   17617 SQLITE_PRIVATE int sqlite3MallocInit(void){
   17618   if( sqlite3GlobalConfig.m.xMalloc==0 ){
   17619     sqlite3MemSetDefault();
   17620   }
   17621   memset(&mem0, 0, sizeof(mem0));
   17622   if( sqlite3GlobalConfig.bCoreMutex ){
   17623     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
   17624   }
   17625   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
   17626       && sqlite3GlobalConfig.nScratch>0 ){
   17627     int i, n, sz;
   17628     ScratchFreeslot *pSlot;
   17629     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
   17630     sqlite3GlobalConfig.szScratch = sz;
   17631     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
   17632     n = sqlite3GlobalConfig.nScratch;
   17633     mem0.pScratchFree = pSlot;
   17634     mem0.nScratchFree = n;
   17635     for(i=0; i<n-1; i++){
   17636       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
   17637       pSlot = pSlot->pNext;
   17638     }
   17639     pSlot->pNext = 0;
   17640     mem0.pScratchEnd = (void*)&pSlot[1];
   17641   }else{
   17642     mem0.pScratchEnd = 0;
   17643     sqlite3GlobalConfig.pScratch = 0;
   17644     sqlite3GlobalConfig.szScratch = 0;
   17645     sqlite3GlobalConfig.nScratch = 0;
   17646   }
   17647   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
   17648       || sqlite3GlobalConfig.nPage<1 ){
   17649     sqlite3GlobalConfig.pPage = 0;
   17650     sqlite3GlobalConfig.szPage = 0;
   17651     sqlite3GlobalConfig.nPage = 0;
   17652   }
   17653   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
   17654 }
   17655 
   17656 /*
   17657 ** Return true if the heap is currently under memory pressure - in other
   17658 ** words if the amount of heap used is close to the limit set by
   17659 ** sqlite3_soft_heap_limit().
   17660 */
   17661 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
   17662   return mem0.nearlyFull;
   17663 }
   17664 
   17665 /*
   17666 ** Deinitialize the memory allocation subsystem.
   17667 */
   17668 SQLITE_PRIVATE void sqlite3MallocEnd(void){
   17669   if( sqlite3GlobalConfig.m.xShutdown ){
   17670     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
   17671   }
   17672   memset(&mem0, 0, sizeof(mem0));
   17673 }
   17674 
   17675 /*
   17676 ** Return the amount of memory currently checked out.
   17677 */
   17678 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
   17679   int n, mx;
   17680   sqlite3_int64 res;
   17681   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
   17682   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
   17683   return res;
   17684 }
   17685 
   17686 /*
   17687 ** Return the maximum amount of memory that has ever been
   17688 ** checked out since either the beginning of this process
   17689 ** or since the most recent reset.
   17690 */
   17691 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
   17692   int n, mx;
   17693   sqlite3_int64 res;
   17694   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
   17695   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
   17696   return res;
   17697 }
   17698 
   17699 /*
   17700 ** Trigger the alarm
   17701 */
   17702 static void sqlite3MallocAlarm(int nByte){
   17703   void (*xCallback)(void*,sqlite3_int64,int);
   17704   sqlite3_int64 nowUsed;
   17705   void *pArg;
   17706   if( mem0.alarmCallback==0 ) return;
   17707   xCallback = mem0.alarmCallback;
   17708   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   17709   pArg = mem0.alarmArg;
   17710   mem0.alarmCallback = 0;
   17711   sqlite3_mutex_leave(mem0.mutex);
   17712   xCallback(pArg, nowUsed, nByte);
   17713   sqlite3_mutex_enter(mem0.mutex);
   17714   mem0.alarmCallback = xCallback;
   17715   mem0.alarmArg = pArg;
   17716 }
   17717 
   17718 /*
   17719 ** Do a memory allocation with statistics and alarms.  Assume the
   17720 ** lock is already held.
   17721 */
   17722 static int mallocWithAlarm(int n, void **pp){
   17723   int nFull;
   17724   void *p;
   17725   assert( sqlite3_mutex_held(mem0.mutex) );
   17726   nFull = sqlite3GlobalConfig.m.xRoundup(n);
   17727   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
   17728   if( mem0.alarmCallback!=0 ){
   17729     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
   17730     if( nUsed+nFull >= mem0.alarmThreshold ){
   17731       mem0.nearlyFull = 1;
   17732       sqlite3MallocAlarm(nFull);
   17733     }else{
   17734       mem0.nearlyFull = 0;
   17735     }
   17736   }
   17737   p = sqlite3GlobalConfig.m.xMalloc(nFull);
   17738 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   17739   if( p==0 && mem0.alarmCallback ){
   17740     sqlite3MallocAlarm(nFull);
   17741     p = sqlite3GlobalConfig.m.xMalloc(nFull);
   17742   }
   17743 #endif
   17744   if( p ){
   17745     nFull = sqlite3MallocSize(p);
   17746     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
   17747     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
   17748   }
   17749   *pp = p;
   17750   return nFull;
   17751 }
   17752 
   17753 /*
   17754 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
   17755 ** assumes the memory subsystem has already been initialized.
   17756 */
   17757 SQLITE_PRIVATE void *sqlite3Malloc(int n){
   17758   void *p;
   17759   if( n<=0               /* IMP: R-65312-04917 */
   17760    || n>=0x7fffff00
   17761   ){
   17762     /* A memory allocation of a number of bytes which is near the maximum
   17763     ** signed integer value might cause an integer overflow inside of the
   17764     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
   17765     ** 255 bytes of overhead.  SQLite itself will never use anything near
   17766     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
   17767     p = 0;
   17768   }else if( sqlite3GlobalConfig.bMemstat ){
   17769     sqlite3_mutex_enter(mem0.mutex);
   17770     mallocWithAlarm(n, &p);
   17771     sqlite3_mutex_leave(mem0.mutex);
   17772   }else{
   17773     p = sqlite3GlobalConfig.m.xMalloc(n);
   17774   }
   17775   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
   17776   return p;
   17777 }
   17778 
   17779 /*
   17780 ** This version of the memory allocation is for use by the application.
   17781 ** First make sure the memory subsystem is initialized, then do the
   17782 ** allocation.
   17783 */
   17784 SQLITE_API void *sqlite3_malloc(int n){
   17785 #ifndef SQLITE_OMIT_AUTOINIT
   17786   if( sqlite3_initialize() ) return 0;
   17787 #endif
   17788   return sqlite3Malloc(n);
   17789 }
   17790 
   17791 /*
   17792 ** Each thread may only have a single outstanding allocation from
   17793 ** xScratchMalloc().  We verify this constraint in the single-threaded
   17794 ** case by setting scratchAllocOut to 1 when an allocation
   17795 ** is outstanding clearing it when the allocation is freed.
   17796 */
   17797 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   17798 static int scratchAllocOut = 0;
   17799 #endif
   17800 
   17801 
   17802 /*
   17803 ** Allocate memory that is to be used and released right away.
   17804 ** This routine is similar to alloca() in that it is not intended
   17805 ** for situations where the memory might be held long-term.  This
   17806 ** routine is intended to get memory to old large transient data
   17807 ** structures that would not normally fit on the stack of an
   17808 ** embedded processor.
   17809 */
   17810 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
   17811   void *p;
   17812   assert( n>0 );
   17813 
   17814   sqlite3_mutex_enter(mem0.mutex);
   17815   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
   17816     p = mem0.pScratchFree;
   17817     mem0.pScratchFree = mem0.pScratchFree->pNext;
   17818     mem0.nScratchFree--;
   17819     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
   17820     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   17821     sqlite3_mutex_leave(mem0.mutex);
   17822   }else{
   17823     if( sqlite3GlobalConfig.bMemstat ){
   17824       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
   17825       n = mallocWithAlarm(n, &p);
   17826       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
   17827       sqlite3_mutex_leave(mem0.mutex);
   17828     }else{
   17829       sqlite3_mutex_leave(mem0.mutex);
   17830       p = sqlite3GlobalConfig.m.xMalloc(n);
   17831     }
   17832     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
   17833   }
   17834   assert( sqlite3_mutex_notheld(mem0.mutex) );
   17835 
   17836 
   17837 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   17838   /* Verify that no more than two scratch allocations per thread
   17839   ** are outstanding at one time.  (This is only checked in the
   17840   ** single-threaded case since checking in the multi-threaded case
   17841   ** would be much more complicated.) */
   17842   assert( scratchAllocOut<=1 );
   17843   if( p ) scratchAllocOut++;
   17844 #endif
   17845 
   17846   return p;
   17847 }
   17848 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
   17849   if( p ){
   17850 
   17851 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
   17852     /* Verify that no more than two scratch allocation per thread
   17853     ** is outstanding at one time.  (This is only checked in the
   17854     ** single-threaded case since checking in the multi-threaded case
   17855     ** would be much more complicated.) */
   17856     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
   17857     scratchAllocOut--;
   17858 #endif
   17859 
   17860     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
   17861       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
   17862       ScratchFreeslot *pSlot;
   17863       pSlot = (ScratchFreeslot*)p;
   17864       sqlite3_mutex_enter(mem0.mutex);
   17865       pSlot->pNext = mem0.pScratchFree;
   17866       mem0.pScratchFree = pSlot;
   17867       mem0.nScratchFree++;
   17868       assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
   17869       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
   17870       sqlite3_mutex_leave(mem0.mutex);
   17871     }else{
   17872       /* Release memory back to the heap */
   17873       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
   17874       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
   17875       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   17876       if( sqlite3GlobalConfig.bMemstat ){
   17877         int iSize = sqlite3MallocSize(p);
   17878         sqlite3_mutex_enter(mem0.mutex);
   17879         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
   17880         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
   17881         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   17882         sqlite3GlobalConfig.m.xFree(p);
   17883         sqlite3_mutex_leave(mem0.mutex);
   17884       }else{
   17885         sqlite3GlobalConfig.m.xFree(p);
   17886       }
   17887     }
   17888   }
   17889 }
   17890 
   17891 /*
   17892 ** TRUE if p is a lookaside memory allocation from db
   17893 */
   17894 #ifndef SQLITE_OMIT_LOOKASIDE
   17895 static int isLookaside(sqlite3 *db, void *p){
   17896   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
   17897 }
   17898 #else
   17899 #define isLookaside(A,B) 0
   17900 #endif
   17901 
   17902 /*
   17903 ** Return the size of a memory allocation previously obtained from
   17904 ** sqlite3Malloc() or sqlite3_malloc().
   17905 */
   17906 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
   17907   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   17908   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   17909   return sqlite3GlobalConfig.m.xSize(p);
   17910 }
   17911 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
   17912   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   17913   if( db && isLookaside(db, p) ){
   17914     return db->lookaside.sz;
   17915   }else{
   17916     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   17917     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   17918     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   17919     return sqlite3GlobalConfig.m.xSize(p);
   17920   }
   17921 }
   17922 
   17923 /*
   17924 ** Free memory previously obtained from sqlite3Malloc().
   17925 */
   17926 SQLITE_API void sqlite3_free(void *p){
   17927   if( p==0 ) return;  /* IMP: R-49053-54554 */
   17928   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
   17929   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   17930   if( sqlite3GlobalConfig.bMemstat ){
   17931     sqlite3_mutex_enter(mem0.mutex);
   17932     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
   17933     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
   17934     sqlite3GlobalConfig.m.xFree(p);
   17935     sqlite3_mutex_leave(mem0.mutex);
   17936   }else{
   17937     sqlite3GlobalConfig.m.xFree(p);
   17938   }
   17939 }
   17940 
   17941 /*
   17942 ** Free memory that might be associated with a particular database
   17943 ** connection.
   17944 */
   17945 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
   17946   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   17947   if( db ){
   17948     if( db->pnBytesFreed ){
   17949       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
   17950       return;
   17951     }
   17952     if( isLookaside(db, p) ){
   17953       LookasideSlot *pBuf = (LookasideSlot*)p;
   17954       pBuf->pNext = db->lookaside.pFree;
   17955       db->lookaside.pFree = pBuf;
   17956       db->lookaside.nOut--;
   17957       return;
   17958     }
   17959   }
   17960   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   17961   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   17962   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
   17963   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   17964   sqlite3_free(p);
   17965 }
   17966 
   17967 /*
   17968 ** Change the size of an existing memory allocation
   17969 */
   17970 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
   17971   int nOld, nNew;
   17972   void *pNew;
   17973   if( pOld==0 ){
   17974     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
   17975   }
   17976   if( nBytes<=0 ){
   17977     sqlite3_free(pOld); /* IMP: R-31593-10574 */
   17978     return 0;
   17979   }
   17980   if( nBytes>=0x7fffff00 ){
   17981     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
   17982     return 0;
   17983   }
   17984   nOld = sqlite3MallocSize(pOld);
   17985   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
   17986   ** argument to xRealloc is always a value returned by a prior call to
   17987   ** xRoundup. */
   17988   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
   17989   if( nOld==nNew ){
   17990     pNew = pOld;
   17991   }else if( sqlite3GlobalConfig.bMemstat ){
   17992     sqlite3_mutex_enter(mem0.mutex);
   17993     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
   17994     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
   17995           mem0.alarmThreshold ){
   17996       sqlite3MallocAlarm(nNew-nOld);
   17997     }
   17998     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
   17999     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
   18000     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   18001     if( pNew==0 && mem0.alarmCallback ){
   18002       sqlite3MallocAlarm(nBytes);
   18003       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   18004     }
   18005     if( pNew ){
   18006       nNew = sqlite3MallocSize(pNew);
   18007       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
   18008     }
   18009     sqlite3_mutex_leave(mem0.mutex);
   18010   }else{
   18011     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
   18012   }
   18013   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
   18014   return pNew;
   18015 }
   18016 
   18017 /*
   18018 ** The public interface to sqlite3Realloc.  Make sure that the memory
   18019 ** subsystem is initialized prior to invoking sqliteRealloc.
   18020 */
   18021 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
   18022 #ifndef SQLITE_OMIT_AUTOINIT
   18023   if( sqlite3_initialize() ) return 0;
   18024 #endif
   18025   return sqlite3Realloc(pOld, n);
   18026 }
   18027 
   18028 
   18029 /*
   18030 ** Allocate and zero memory.
   18031 */
   18032 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
   18033   void *p = sqlite3Malloc(n);
   18034   if( p ){
   18035     memset(p, 0, n);
   18036   }
   18037   return p;
   18038 }
   18039 
   18040 /*
   18041 ** Allocate and zero memory.  If the allocation fails, make
   18042 ** the mallocFailed flag in the connection pointer.
   18043 */
   18044 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
   18045   void *p = sqlite3DbMallocRaw(db, n);
   18046   if( p ){
   18047     memset(p, 0, n);
   18048   }
   18049   return p;
   18050 }
   18051 
   18052 /*
   18053 ** Allocate and zero memory.  If the allocation fails, make
   18054 ** the mallocFailed flag in the connection pointer.
   18055 **
   18056 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
   18057 ** failure on the same database connection) then always return 0.
   18058 ** Hence for a particular database connection, once malloc starts
   18059 ** failing, it fails consistently until mallocFailed is reset.
   18060 ** This is an important assumption.  There are many places in the
   18061 ** code that do things like this:
   18062 **
   18063 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   18064 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   18065 **         if( b ) a[10] = 9;
   18066 **
   18067 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   18068 ** that all prior mallocs (ex: "a") worked too.
   18069 */
   18070 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
   18071   void *p;
   18072   assert( db==0 || sqlite3_mutex_held(db->mutex) );
   18073   assert( db==0 || db->pnBytesFreed==0 );
   18074 #ifndef SQLITE_OMIT_LOOKASIDE
   18075   if( db ){
   18076     LookasideSlot *pBuf;
   18077     if( db->mallocFailed ){
   18078       return 0;
   18079     }
   18080     if( db->lookaside.bEnabled && n<=db->lookaside.sz
   18081          && (pBuf = db->lookaside.pFree)!=0 ){
   18082       db->lookaside.pFree = pBuf->pNext;
   18083       db->lookaside.nOut++;
   18084       if( db->lookaside.nOut>db->lookaside.mxOut ){
   18085         db->lookaside.mxOut = db->lookaside.nOut;
   18086       }
   18087       return (void*)pBuf;
   18088     }
   18089   }
   18090 #else
   18091   if( db && db->mallocFailed ){
   18092     return 0;
   18093   }
   18094 #endif
   18095   p = sqlite3Malloc(n);
   18096   if( !p && db ){
   18097     db->mallocFailed = 1;
   18098   }
   18099   sqlite3MemdebugSetType(p, MEMTYPE_DB |
   18100          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   18101   return p;
   18102 }
   18103 
   18104 /*
   18105 ** Resize the block of memory pointed to by p to n bytes. If the
   18106 ** resize fails, set the mallocFailed flag in the connection object.
   18107 */
   18108 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
   18109   void *pNew = 0;
   18110   assert( db!=0 );
   18111   assert( sqlite3_mutex_held(db->mutex) );
   18112   if( db->mallocFailed==0 ){
   18113     if( p==0 ){
   18114       return sqlite3DbMallocRaw(db, n);
   18115     }
   18116     if( isLookaside(db, p) ){
   18117       if( n<=db->lookaside.sz ){
   18118         return p;
   18119       }
   18120       pNew = sqlite3DbMallocRaw(db, n);
   18121       if( pNew ){
   18122         memcpy(pNew, p, db->lookaside.sz);
   18123         sqlite3DbFree(db, p);
   18124       }
   18125     }else{
   18126       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
   18127       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
   18128       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   18129       pNew = sqlite3_realloc(p, n);
   18130       if( !pNew ){
   18131         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
   18132         db->mallocFailed = 1;
   18133       }
   18134       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
   18135             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   18136     }
   18137   }
   18138   return pNew;
   18139 }
   18140 
   18141 /*
   18142 ** Attempt to reallocate p.  If the reallocation fails, then free p
   18143 ** and set the mallocFailed flag in the database connection.
   18144 */
   18145 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
   18146   void *pNew;
   18147   pNew = sqlite3DbRealloc(db, p, n);
   18148   if( !pNew ){
   18149     sqlite3DbFree(db, p);
   18150   }
   18151   return pNew;
   18152 }
   18153 
   18154 /*
   18155 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
   18156 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
   18157 ** is because when memory debugging is turned on, these two functions are
   18158 ** called via macros that record the current file and line number in the
   18159 ** ThreadData structure.
   18160 */
   18161 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
   18162   char *zNew;
   18163   size_t n;
   18164   if( z==0 ){
   18165     return 0;
   18166   }
   18167   n = sqlite3Strlen30(z) + 1;
   18168   assert( (n&0x7fffffff)==n );
   18169   zNew = sqlite3DbMallocRaw(db, (int)n);
   18170   if( zNew ){
   18171     memcpy(zNew, z, n);
   18172   }
   18173   return zNew;
   18174 }
   18175 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
   18176   char *zNew;
   18177   if( z==0 ){
   18178     return 0;
   18179   }
   18180   assert( (n&0x7fffffff)==n );
   18181   zNew = sqlite3DbMallocRaw(db, n+1);
   18182   if( zNew ){
   18183     memcpy(zNew, z, n);
   18184     zNew[n] = 0;
   18185   }
   18186   return zNew;
   18187 }
   18188 
   18189 /*
   18190 ** Create a string from the zFromat argument and the va_list that follows.
   18191 ** Store the string in memory obtained from sqliteMalloc() and make *pz
   18192 ** point to that string.
   18193 */
   18194 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
   18195   va_list ap;
   18196   char *z;
   18197 
   18198   va_start(ap, zFormat);
   18199   z = sqlite3VMPrintf(db, zFormat, ap);
   18200   va_end(ap);
   18201   sqlite3DbFree(db, *pz);
   18202   *pz = z;
   18203 }
   18204 
   18205 
   18206 /*
   18207 ** This function must be called before exiting any API function (i.e.
   18208 ** returning control to the user) that has called sqlite3_malloc or
   18209 ** sqlite3_realloc.
   18210 **
   18211 ** The returned value is normally a copy of the second argument to this
   18212 ** function. However, if a malloc() failure has occurred since the previous
   18213 ** invocation SQLITE_NOMEM is returned instead.
   18214 **
   18215 ** If the first argument, db, is not NULL and a malloc() error has occurred,
   18216 ** then the connection error-code (the value returned by sqlite3_errcode())
   18217 ** is set to SQLITE_NOMEM.
   18218 */
   18219 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   18220   /* If the db handle is not NULL, then we must hold the connection handle
   18221   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
   18222   ** is unsafe, as is the call to sqlite3Error().
   18223   */
   18224   assert( !db || sqlite3_mutex_held(db->mutex) );
   18225   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
   18226     sqlite3Error(db, SQLITE_NOMEM, 0);
   18227     db->mallocFailed = 0;
   18228     rc = SQLITE_NOMEM;
   18229   }
   18230   return rc & (db ? db->errMask : 0xff);
   18231 }
   18232 
   18233 /************** End of malloc.c **********************************************/
   18234 /************** Begin file printf.c ******************************************/
   18235 /*
   18236 ** The "printf" code that follows dates from the 1980's.  It is in
   18237 ** the public domain.  The original comments are included here for
   18238 ** completeness.  They are very out-of-date but might be useful as
   18239 ** an historical reference.  Most of the "enhancements" have been backed
   18240 ** out so that the functionality is now the same as standard printf().
   18241 **
   18242 **************************************************************************
   18243 **
   18244 ** The following modules is an enhanced replacement for the "printf" subroutines
   18245 ** found in the standard C library.  The following enhancements are
   18246 ** supported:
   18247 **
   18248 **      +  Additional functions.  The standard set of "printf" functions
   18249 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
   18250 **         vsprintf.  This module adds the following:
   18251 **
   18252 **           *  snprintf -- Works like sprintf, but has an extra argument
   18253 **                          which is the size of the buffer written to.
   18254 **
   18255 **           *  mprintf --  Similar to sprintf.  Writes output to memory
   18256 **                          obtained from malloc.
   18257 **
   18258 **           *  xprintf --  Calls a function to dispose of output.
   18259 **
   18260 **           *  nprintf --  No output, but returns the number of characters
   18261 **                          that would have been output by printf.
   18262 **
   18263 **           *  A v- version (ex: vsnprintf) of every function is also
   18264 **              supplied.
   18265 **
   18266 **      +  A few extensions to the formatting notation are supported:
   18267 **
   18268 **           *  The "=" flag (similar to "-") causes the output to be
   18269 **              be centered in the appropriately sized field.
   18270 **
   18271 **           *  The %b field outputs an integer in binary notation.
   18272 **
   18273 **           *  The %c field now accepts a precision.  The character output
   18274 **              is repeated by the number of times the precision specifies.
   18275 **
   18276 **           *  The %' field works like %c, but takes as its character the
   18277 **              next character of the format string, instead of the next
   18278 **              argument.  For example,  printf("%.78'-")  prints 78 minus
   18279 **              signs, the same as  printf("%.78c",'-').
   18280 **
   18281 **      +  When compiled using GCC on a SPARC, this version of printf is
   18282 **         faster than the library printf for SUN OS 4.1.
   18283 **
   18284 **      +  All functions are fully reentrant.
   18285 **
   18286 */
   18287 
   18288 /*
   18289 ** Conversion types fall into various categories as defined by the
   18290 ** following enumeration.
   18291 */
   18292 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
   18293 #define etFLOAT       2 /* Floating point.  %f */
   18294 #define etEXP         3 /* Exponentional notation. %e and %E */
   18295 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
   18296 #define etSIZE        5 /* Return number of characters processed so far. %n */
   18297 #define etSTRING      6 /* Strings. %s */
   18298 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
   18299 #define etPERCENT     8 /* Percent symbol. %% */
   18300 #define etCHARX       9 /* Characters. %c */
   18301 /* The rest are extensions, not normally found in printf() */
   18302 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
   18303 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
   18304                           NULL pointers replaced by SQL NULL.  %Q */
   18305 #define etTOKEN      12 /* a pointer to a Token structure */
   18306 #define etSRCLIST    13 /* a pointer to a SrcList */
   18307 #define etPOINTER    14 /* The %p conversion */
   18308 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
   18309 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
   18310 
   18311 #define etINVALID     0 /* Any unrecognized conversion type */
   18312 
   18313 
   18314 /*
   18315 ** An "etByte" is an 8-bit unsigned value.
   18316 */
   18317 typedef unsigned char etByte;
   18318 
   18319 /*
   18320 ** Each builtin conversion character (ex: the 'd' in "%d") is described
   18321 ** by an instance of the following structure
   18322 */
   18323 typedef struct et_info {   /* Information about each format field */
   18324   char fmttype;            /* The format field code letter */
   18325   etByte base;             /* The base for radix conversion */
   18326   etByte flags;            /* One or more of FLAG_ constants below */
   18327   etByte type;             /* Conversion paradigm */
   18328   etByte charset;          /* Offset into aDigits[] of the digits string */
   18329   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
   18330 } et_info;
   18331 
   18332 /*
   18333 ** Allowed values for et_info.flags
   18334 */
   18335 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
   18336 #define FLAG_INTERN  2     /* True if for internal use only */
   18337 #define FLAG_STRING  4     /* Allow infinity precision */
   18338 
   18339 
   18340 /*
   18341 ** The following table is searched linearly, so it is good to put the
   18342 ** most frequently used conversion types first.
   18343 */
   18344 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
   18345 static const char aPrefix[] = "-x0\000X0";
   18346 static const et_info fmtinfo[] = {
   18347   {  'd', 10, 1, etRADIX,      0,  0 },
   18348   {  's',  0, 4, etSTRING,     0,  0 },
   18349   {  'g',  0, 1, etGENERIC,    30, 0 },
   18350   {  'z',  0, 4, etDYNSTRING,  0,  0 },
   18351   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
   18352   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
   18353   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
   18354   {  'c',  0, 0, etCHARX,      0,  0 },
   18355   {  'o',  8, 0, etRADIX,      0,  2 },
   18356   {  'u', 10, 0, etRADIX,      0,  0 },
   18357   {  'x', 16, 0, etRADIX,      16, 1 },
   18358   {  'X', 16, 0, etRADIX,      0,  4 },
   18359 #ifndef SQLITE_OMIT_FLOATING_POINT
   18360   {  'f',  0, 1, etFLOAT,      0,  0 },
   18361   {  'e',  0, 1, etEXP,        30, 0 },
   18362   {  'E',  0, 1, etEXP,        14, 0 },
   18363   {  'G',  0, 1, etGENERIC,    14, 0 },
   18364 #endif
   18365   {  'i', 10, 1, etRADIX,      0,  0 },
   18366   {  'n',  0, 0, etSIZE,       0,  0 },
   18367   {  '%',  0, 0, etPERCENT,    0,  0 },
   18368   {  'p', 16, 0, etPOINTER,    0,  1 },
   18369 
   18370 /* All the rest have the FLAG_INTERN bit set and are thus for internal
   18371 ** use only */
   18372   {  'T',  0, 2, etTOKEN,      0,  0 },
   18373   {  'S',  0, 2, etSRCLIST,    0,  0 },
   18374   {  'r', 10, 3, etORDINAL,    0,  0 },
   18375 };
   18376 
   18377 /*
   18378 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
   18379 ** conversions will work.
   18380 */
   18381 #ifndef SQLITE_OMIT_FLOATING_POINT
   18382 /*
   18383 ** "*val" is a double such that 0.1 <= *val < 10.0
   18384 ** Return the ascii code for the leading digit of *val, then
   18385 ** multiply "*val" by 10.0 to renormalize.
   18386 **
   18387 ** Example:
   18388 **     input:     *val = 3.14159
   18389 **     output:    *val = 1.4159    function return = '3'
   18390 **
   18391 ** The counter *cnt is incremented each time.  After counter exceeds
   18392 ** 16 (the number of significant digits in a 64-bit float) '0' is
   18393 ** always returned.
   18394 */
   18395 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
   18396   int digit;
   18397   LONGDOUBLE_TYPE d;
   18398   if( (*cnt)++ >= 16 ) return '0';
   18399   digit = (int)*val;
   18400   d = digit;
   18401   digit += '0';
   18402   *val = (*val - d)*10.0;
   18403   return (char)digit;
   18404 }
   18405 #endif /* SQLITE_OMIT_FLOATING_POINT */
   18406 
   18407 /*
   18408 ** Append N space characters to the given string buffer.
   18409 */
   18410 static void appendSpace(StrAccum *pAccum, int N){
   18411   static const char zSpaces[] = "                             ";
   18412   while( N>=(int)sizeof(zSpaces)-1 ){
   18413     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
   18414     N -= sizeof(zSpaces)-1;
   18415   }
   18416   if( N>0 ){
   18417     sqlite3StrAccumAppend(pAccum, zSpaces, N);
   18418   }
   18419 }
   18420 
   18421 /*
   18422 ** On machines with a small stack size, you can redefine the
   18423 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
   18424 */
   18425 #ifndef SQLITE_PRINT_BUF_SIZE
   18426 # if defined(SQLITE_SMALL_STACK)
   18427 #   define SQLITE_PRINT_BUF_SIZE 50
   18428 # else
   18429 #   define SQLITE_PRINT_BUF_SIZE 350
   18430 # endif
   18431 #endif
   18432 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
   18433 
   18434 /*
   18435 ** The root program.  All variations call this core.
   18436 **
   18437 ** INPUTS:
   18438 **   func   This is a pointer to a function taking three arguments
   18439 **            1. A pointer to anything.  Same as the "arg" parameter.
   18440 **            2. A pointer to the list of characters to be output
   18441 **               (Note, this list is NOT null terminated.)
   18442 **            3. An integer number of characters to be output.
   18443 **               (Note: This number might be zero.)
   18444 **
   18445 **   arg    This is the pointer to anything which will be passed as the
   18446 **          first argument to "func".  Use it for whatever you like.
   18447 **
   18448 **   fmt    This is the format string, as in the usual print.
   18449 **
   18450 **   ap     This is a pointer to a list of arguments.  Same as in
   18451 **          vfprint.
   18452 **
   18453 ** OUTPUTS:
   18454 **          The return value is the total number of characters sent to
   18455 **          the function "func".  Returns -1 on a error.
   18456 **
   18457 ** Note that the order in which automatic variables are declared below
   18458 ** seems to make a big difference in determining how fast this beast
   18459 ** will run.
   18460 */
   18461 SQLITE_PRIVATE void sqlite3VXPrintf(
   18462   StrAccum *pAccum,                  /* Accumulate results here */
   18463   int useExtended,                   /* Allow extended %-conversions */
   18464   const char *fmt,                   /* Format string */
   18465   va_list ap                         /* arguments */
   18466 ){
   18467   int c;                     /* Next character in the format string */
   18468   char *bufpt;               /* Pointer to the conversion buffer */
   18469   int precision;             /* Precision of the current field */
   18470   int length;                /* Length of the field */
   18471   int idx;                   /* A general purpose loop counter */
   18472   int width;                 /* Width of the current field */
   18473   etByte flag_leftjustify;   /* True if "-" flag is present */
   18474   etByte flag_plussign;      /* True if "+" flag is present */
   18475   etByte flag_blanksign;     /* True if " " flag is present */
   18476   etByte flag_alternateform; /* True if "#" flag is present */
   18477   etByte flag_altform2;      /* True if "!" flag is present */
   18478   etByte flag_zeropad;       /* True if field width constant starts with zero */
   18479   etByte flag_long;          /* True if "l" flag is present */
   18480   etByte flag_longlong;      /* True if the "ll" flag is present */
   18481   etByte done;               /* Loop termination flag */
   18482   sqlite_uint64 longvalue;   /* Value for integer types */
   18483   LONGDOUBLE_TYPE realvalue; /* Value for real types */
   18484   const et_info *infop;      /* Pointer to the appropriate info structure */
   18485   char buf[etBUFSIZE];       /* Conversion buffer */
   18486   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
   18487   etByte xtype = 0;          /* Conversion paradigm */
   18488   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
   18489 #ifndef SQLITE_OMIT_FLOATING_POINT
   18490   int  exp, e2;              /* exponent of real numbers */
   18491   double rounder;            /* Used for rounding floating point values */
   18492   etByte flag_dp;            /* True if decimal point should be shown */
   18493   etByte flag_rtz;           /* True if trailing zeros should be removed */
   18494   etByte flag_exp;           /* True to force display of the exponent */
   18495   int nsd;                   /* Number of significant digits returned */
   18496 #endif
   18497 
   18498   length = 0;
   18499   bufpt = 0;
   18500   for(; (c=(*fmt))!=0; ++fmt){
   18501     if( c!='%' ){
   18502       int amt;
   18503       bufpt = (char *)fmt;
   18504       amt = 1;
   18505       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
   18506       sqlite3StrAccumAppend(pAccum, bufpt, amt);
   18507       if( c==0 ) break;
   18508     }
   18509     if( (c=(*++fmt))==0 ){
   18510       sqlite3StrAccumAppend(pAccum, "%", 1);
   18511       break;
   18512     }
   18513     /* Find out what flags are present */
   18514     flag_leftjustify = flag_plussign = flag_blanksign =
   18515      flag_alternateform = flag_altform2 = flag_zeropad = 0;
   18516     done = 0;
   18517     do{
   18518       switch( c ){
   18519         case '-':   flag_leftjustify = 1;     break;
   18520         case '+':   flag_plussign = 1;        break;
   18521         case ' ':   flag_blanksign = 1;       break;
   18522         case '#':   flag_alternateform = 1;   break;
   18523         case '!':   flag_altform2 = 1;        break;
   18524         case '0':   flag_zeropad = 1;         break;
   18525         default:    done = 1;                 break;
   18526       }
   18527     }while( !done && (c=(*++fmt))!=0 );
   18528     /* Get the field width */
   18529     width = 0;
   18530     if( c=='*' ){
   18531       width = va_arg(ap,int);
   18532       if( width<0 ){
   18533         flag_leftjustify = 1;
   18534         width = -width;
   18535       }
   18536       c = *++fmt;
   18537     }else{
   18538       while( c>='0' && c<='9' ){
   18539         width = width*10 + c - '0';
   18540         c = *++fmt;
   18541       }
   18542     }
   18543     if( width > etBUFSIZE-10 ){
   18544       width = etBUFSIZE-10;
   18545     }
   18546     /* Get the precision */
   18547     if( c=='.' ){
   18548       precision = 0;
   18549       c = *++fmt;
   18550       if( c=='*' ){
   18551         precision = va_arg(ap,int);
   18552         if( precision<0 ) precision = -precision;
   18553         c = *++fmt;
   18554       }else{
   18555         while( c>='0' && c<='9' ){
   18556           precision = precision*10 + c - '0';
   18557           c = *++fmt;
   18558         }
   18559       }
   18560     }else{
   18561       precision = -1;
   18562     }
   18563     /* Get the conversion type modifier */
   18564     if( c=='l' ){
   18565       flag_long = 1;
   18566       c = *++fmt;
   18567       if( c=='l' ){
   18568         flag_longlong = 1;
   18569         c = *++fmt;
   18570       }else{
   18571         flag_longlong = 0;
   18572       }
   18573     }else{
   18574       flag_long = flag_longlong = 0;
   18575     }
   18576     /* Fetch the info entry for the field */
   18577     infop = &fmtinfo[0];
   18578     xtype = etINVALID;
   18579     for(idx=0; idx<ArraySize(fmtinfo); idx++){
   18580       if( c==fmtinfo[idx].fmttype ){
   18581         infop = &fmtinfo[idx];
   18582         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
   18583           xtype = infop->type;
   18584         }else{
   18585           return;
   18586         }
   18587         break;
   18588       }
   18589     }
   18590     zExtra = 0;
   18591 
   18592 
   18593     /* Limit the precision to prevent overflowing buf[] during conversion */
   18594     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
   18595       precision = etBUFSIZE-40;
   18596     }
   18597 
   18598     /*
   18599     ** At this point, variables are initialized as follows:
   18600     **
   18601     **   flag_alternateform          TRUE if a '#' is present.
   18602     **   flag_altform2               TRUE if a '!' is present.
   18603     **   flag_plussign               TRUE if a '+' is present.
   18604     **   flag_leftjustify            TRUE if a '-' is present or if the
   18605     **                               field width was negative.
   18606     **   flag_zeropad                TRUE if the width began with 0.
   18607     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
   18608     **                               the conversion character.
   18609     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
   18610     **                               the conversion character.
   18611     **   flag_blanksign              TRUE if a ' ' is present.
   18612     **   width                       The specified field width.  This is
   18613     **                               always non-negative.  Zero is the default.
   18614     **   precision                   The specified precision.  The default
   18615     **                               is -1.
   18616     **   xtype                       The class of the conversion.
   18617     **   infop                       Pointer to the appropriate info struct.
   18618     */
   18619     switch( xtype ){
   18620       case etPOINTER:
   18621         flag_longlong = sizeof(char*)==sizeof(i64);
   18622         flag_long = sizeof(char*)==sizeof(long int);
   18623         /* Fall through into the next case */
   18624       case etORDINAL:
   18625       case etRADIX:
   18626         if( infop->flags & FLAG_SIGNED ){
   18627           i64 v;
   18628           if( flag_longlong ){
   18629             v = va_arg(ap,i64);
   18630           }else if( flag_long ){
   18631             v = va_arg(ap,long int);
   18632           }else{
   18633             v = va_arg(ap,int);
   18634           }
   18635           if( v<0 ){
   18636             longvalue = -v;
   18637             prefix = '-';
   18638           }else{
   18639             longvalue = v;
   18640             if( flag_plussign )        prefix = '+';
   18641             else if( flag_blanksign )  prefix = ' ';
   18642             else                       prefix = 0;
   18643           }
   18644         }else{
   18645           if( flag_longlong ){
   18646             longvalue = va_arg(ap,u64);
   18647           }else if( flag_long ){
   18648             longvalue = va_arg(ap,unsigned long int);
   18649           }else{
   18650             longvalue = va_arg(ap,unsigned int);
   18651           }
   18652           prefix = 0;
   18653         }
   18654         if( longvalue==0 ) flag_alternateform = 0;
   18655         if( flag_zeropad && precision<width-(prefix!=0) ){
   18656           precision = width-(prefix!=0);
   18657         }
   18658         bufpt = &buf[etBUFSIZE-1];
   18659         if( xtype==etORDINAL ){
   18660           static const char zOrd[] = "thstndrd";
   18661           int x = (int)(longvalue % 10);
   18662           if( x>=4 || (longvalue/10)%10==1 ){
   18663             x = 0;
   18664           }
   18665           buf[etBUFSIZE-3] = zOrd[x*2];
   18666           buf[etBUFSIZE-2] = zOrd[x*2+1];
   18667           bufpt -= 2;
   18668         }
   18669         {
   18670           register const char *cset;      /* Use registers for speed */
   18671           register int base;
   18672           cset = &aDigits[infop->charset];
   18673           base = infop->base;
   18674           do{                                           /* Convert to ascii */
   18675             *(--bufpt) = cset[longvalue%base];
   18676             longvalue = longvalue/base;
   18677           }while( longvalue>0 );
   18678         }
   18679         length = (int)(&buf[etBUFSIZE-1]-bufpt);
   18680         for(idx=precision-length; idx>0; idx--){
   18681           *(--bufpt) = '0';                             /* Zero pad */
   18682         }
   18683         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
   18684         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
   18685           const char *pre;
   18686           char x;
   18687           pre = &aPrefix[infop->prefix];
   18688           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
   18689         }
   18690         length = (int)(&buf[etBUFSIZE-1]-bufpt);
   18691         break;
   18692       case etFLOAT:
   18693       case etEXP:
   18694       case etGENERIC:
   18695         realvalue = va_arg(ap,double);
   18696 #ifdef SQLITE_OMIT_FLOATING_POINT
   18697         length = 0;
   18698 #else
   18699         if( precision<0 ) precision = 6;         /* Set default precision */
   18700         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
   18701         if( realvalue<0.0 ){
   18702           realvalue = -realvalue;
   18703           prefix = '-';
   18704         }else{
   18705           if( flag_plussign )          prefix = '+';
   18706           else if( flag_blanksign )    prefix = ' ';
   18707           else                         prefix = 0;
   18708         }
   18709         if( xtype==etGENERIC && precision>0 ) precision--;
   18710 #if 0
   18711         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
   18712         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
   18713 #else
   18714         /* It makes more sense to use 0.5 */
   18715         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
   18716 #endif
   18717         if( xtype==etFLOAT ) realvalue += rounder;
   18718         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
   18719         exp = 0;
   18720         if( sqlite3IsNaN((double)realvalue) ){
   18721           bufpt = "NaN";
   18722           length = 3;
   18723           break;
   18724         }
   18725         if( realvalue>0.0 ){
   18726           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
   18727           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
   18728           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
   18729           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
   18730           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
   18731           if( exp>350 ){
   18732             if( prefix=='-' ){
   18733               bufpt = "-Inf";
   18734             }else if( prefix=='+' ){
   18735               bufpt = "+Inf";
   18736             }else{
   18737               bufpt = "Inf";
   18738             }
   18739             length = sqlite3Strlen30(bufpt);
   18740             break;
   18741           }
   18742         }
   18743         bufpt = buf;
   18744         /*
   18745         ** If the field type is etGENERIC, then convert to either etEXP
   18746         ** or etFLOAT, as appropriate.
   18747         */
   18748         flag_exp = xtype==etEXP;
   18749         if( xtype!=etFLOAT ){
   18750           realvalue += rounder;
   18751           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
   18752         }
   18753         if( xtype==etGENERIC ){
   18754           flag_rtz = !flag_alternateform;
   18755           if( exp<-4 || exp>precision ){
   18756             xtype = etEXP;
   18757           }else{
   18758             precision = precision - exp;
   18759             xtype = etFLOAT;
   18760           }
   18761         }else{
   18762           flag_rtz = 0;
   18763         }
   18764         if( xtype==etEXP ){
   18765           e2 = 0;
   18766         }else{
   18767           e2 = exp;
   18768         }
   18769         nsd = 0;
   18770         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
   18771         /* The sign in front of the number */
   18772         if( prefix ){
   18773           *(bufpt++) = prefix;
   18774         }
   18775         /* Digits prior to the decimal point */
   18776         if( e2<0 ){
   18777           *(bufpt++) = '0';
   18778         }else{
   18779           for(; e2>=0; e2--){
   18780             *(bufpt++) = et_getdigit(&realvalue,&nsd);
   18781           }
   18782         }
   18783         /* The decimal point */
   18784         if( flag_dp ){
   18785           *(bufpt++) = '.';
   18786         }
   18787         /* "0" digits after the decimal point but before the first
   18788         ** significant digit of the number */
   18789         for(e2++; e2<0; precision--, e2++){
   18790           assert( precision>0 );
   18791           *(bufpt++) = '0';
   18792         }
   18793         /* Significant digits after the decimal point */
   18794         while( (precision--)>0 ){
   18795           *(bufpt++) = et_getdigit(&realvalue,&nsd);
   18796         }
   18797         /* Remove trailing zeros and the "." if no digits follow the "." */
   18798         if( flag_rtz && flag_dp ){
   18799           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
   18800           assert( bufpt>buf );
   18801           if( bufpt[-1]=='.' ){
   18802             if( flag_altform2 ){
   18803               *(bufpt++) = '0';
   18804             }else{
   18805               *(--bufpt) = 0;
   18806             }
   18807           }
   18808         }
   18809         /* Add the "eNNN" suffix */
   18810         if( flag_exp || xtype==etEXP ){
   18811           *(bufpt++) = aDigits[infop->charset];
   18812           if( exp<0 ){
   18813             *(bufpt++) = '-'; exp = -exp;
   18814           }else{
   18815             *(bufpt++) = '+';
   18816           }
   18817           if( exp>=100 ){
   18818             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
   18819             exp %= 100;
   18820           }
   18821           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
   18822           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
   18823         }
   18824         *bufpt = 0;
   18825 
   18826         /* The converted number is in buf[] and zero terminated. Output it.
   18827         ** Note that the number is in the usual order, not reversed as with
   18828         ** integer conversions. */
   18829         length = (int)(bufpt-buf);
   18830         bufpt = buf;
   18831 
   18832         /* Special case:  Add leading zeros if the flag_zeropad flag is
   18833         ** set and we are not left justified */
   18834         if( flag_zeropad && !flag_leftjustify && length < width){
   18835           int i;
   18836           int nPad = width - length;
   18837           for(i=width; i>=nPad; i--){
   18838             bufpt[i] = bufpt[i-nPad];
   18839           }
   18840           i = prefix!=0;
   18841           while( nPad-- ) bufpt[i++] = '0';
   18842           length = width;
   18843         }
   18844 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
   18845         break;
   18846       case etSIZE:
   18847         *(va_arg(ap,int*)) = pAccum->nChar;
   18848         length = width = 0;
   18849         break;
   18850       case etPERCENT:
   18851         buf[0] = '%';
   18852         bufpt = buf;
   18853         length = 1;
   18854         break;
   18855       case etCHARX:
   18856         c = va_arg(ap,int);
   18857         buf[0] = (char)c;
   18858         if( precision>=0 ){
   18859           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
   18860           length = precision;
   18861         }else{
   18862           length =1;
   18863         }
   18864         bufpt = buf;
   18865         break;
   18866       case etSTRING:
   18867       case etDYNSTRING:
   18868         bufpt = va_arg(ap,char*);
   18869         if( bufpt==0 ){
   18870           bufpt = "";
   18871         }else if( xtype==etDYNSTRING ){
   18872           zExtra = bufpt;
   18873         }
   18874         if( precision>=0 ){
   18875           for(length=0; length<precision && bufpt[length]; length++){}
   18876         }else{
   18877           length = sqlite3Strlen30(bufpt);
   18878         }
   18879         break;
   18880       case etSQLESCAPE:
   18881       case etSQLESCAPE2:
   18882       case etSQLESCAPE3: {
   18883         int i, j, k, n, isnull;
   18884         int needQuote;
   18885         char ch;
   18886         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
   18887         char *escarg = va_arg(ap,char*);
   18888         isnull = escarg==0;
   18889         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
   18890         k = precision;
   18891         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
   18892           if( ch==q )  n++;
   18893         }
   18894         needQuote = !isnull && xtype==etSQLESCAPE2;
   18895         n += i + 1 + needQuote*2;
   18896         if( n>etBUFSIZE ){
   18897           bufpt = zExtra = sqlite3Malloc( n );
   18898           if( bufpt==0 ){
   18899             pAccum->mallocFailed = 1;
   18900             return;
   18901           }
   18902         }else{
   18903           bufpt = buf;
   18904         }
   18905         j = 0;
   18906         if( needQuote ) bufpt[j++] = q;
   18907         k = i;
   18908         for(i=0; i<k; i++){
   18909           bufpt[j++] = ch = escarg[i];
   18910           if( ch==q ) bufpt[j++] = ch;
   18911         }
   18912         if( needQuote ) bufpt[j++] = q;
   18913         bufpt[j] = 0;
   18914         length = j;
   18915         /* The precision in %q and %Q means how many input characters to
   18916         ** consume, not the length of the output...
   18917         ** if( precision>=0 && precision<length ) length = precision; */
   18918         break;
   18919       }
   18920       case etTOKEN: {
   18921         Token *pToken = va_arg(ap, Token*);
   18922         if( pToken ){
   18923           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
   18924         }
   18925         length = width = 0;
   18926         break;
   18927       }
   18928       case etSRCLIST: {
   18929         SrcList *pSrc = va_arg(ap, SrcList*);
   18930         int k = va_arg(ap, int);
   18931         struct SrcList_item *pItem = &pSrc->a[k];
   18932         assert( k>=0 && k<pSrc->nSrc );
   18933         if( pItem->zDatabase ){
   18934           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
   18935           sqlite3StrAccumAppend(pAccum, ".", 1);
   18936         }
   18937         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
   18938         length = width = 0;
   18939         break;
   18940       }
   18941       default: {
   18942         assert( xtype==etINVALID );
   18943         return;
   18944       }
   18945     }/* End switch over the format type */
   18946     /*
   18947     ** The text of the conversion is pointed to by "bufpt" and is
   18948     ** "length" characters long.  The field width is "width".  Do
   18949     ** the output.
   18950     */
   18951     if( !flag_leftjustify ){
   18952       register int nspace;
   18953       nspace = width-length;
   18954       if( nspace>0 ){
   18955         appendSpace(pAccum, nspace);
   18956       }
   18957     }
   18958     if( length>0 ){
   18959       sqlite3StrAccumAppend(pAccum, bufpt, length);
   18960     }
   18961     if( flag_leftjustify ){
   18962       register int nspace;
   18963       nspace = width-length;
   18964       if( nspace>0 ){
   18965         appendSpace(pAccum, nspace);
   18966       }
   18967     }
   18968     if( zExtra ){
   18969       sqlite3_free(zExtra);
   18970     }
   18971   }/* End for loop over the format string */
   18972 } /* End of function */
   18973 
   18974 /*
   18975 ** Append N bytes of text from z to the StrAccum object.
   18976 */
   18977 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
   18978   assert( z!=0 || N==0 );
   18979   if( p->tooBig | p->mallocFailed ){
   18980     testcase(p->tooBig);
   18981     testcase(p->mallocFailed);
   18982     return;
   18983   }
   18984   if( N<0 ){
   18985     N = sqlite3Strlen30(z);
   18986   }
   18987   if( N==0 || NEVER(z==0) ){
   18988     return;
   18989   }
   18990   if( p->nChar+N >= p->nAlloc ){
   18991     char *zNew;
   18992     if( !p->useMalloc ){
   18993       p->tooBig = 1;
   18994       N = p->nAlloc - p->nChar - 1;
   18995       if( N<=0 ){
   18996         return;
   18997       }
   18998     }else{
   18999       i64 szNew = p->nChar;
   19000       szNew += N + 1;
   19001       if( szNew > p->mxAlloc ){
   19002         sqlite3StrAccumReset(p);
   19003         p->tooBig = 1;
   19004         return;
   19005       }else{
   19006         p->nAlloc = (int)szNew;
   19007       }
   19008       if( p->useMalloc==1 ){
   19009         zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
   19010       }else{
   19011         zNew = sqlite3_malloc(p->nAlloc);
   19012       }
   19013       if( zNew ){
   19014         memcpy(zNew, p->zText, p->nChar);
   19015         sqlite3StrAccumReset(p);
   19016         p->zText = zNew;
   19017       }else{
   19018         p->mallocFailed = 1;
   19019         sqlite3StrAccumReset(p);
   19020         return;
   19021       }
   19022     }
   19023   }
   19024   memcpy(&p->zText[p->nChar], z, N);
   19025   p->nChar += N;
   19026 }
   19027 
   19028 /*
   19029 ** Finish off a string by making sure it is zero-terminated.
   19030 ** Return a pointer to the resulting string.  Return a NULL
   19031 ** pointer if any kind of error was encountered.
   19032 */
   19033 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
   19034   if( p->zText ){
   19035     p->zText[p->nChar] = 0;
   19036     if( p->useMalloc && p->zText==p->zBase ){
   19037       if( p->useMalloc==1 ){
   19038         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
   19039       }else{
   19040         p->zText = sqlite3_malloc(p->nChar+1);
   19041       }
   19042       if( p->zText ){
   19043         memcpy(p->zText, p->zBase, p->nChar+1);
   19044       }else{
   19045         p->mallocFailed = 1;
   19046       }
   19047     }
   19048   }
   19049   return p->zText;
   19050 }
   19051 
   19052 /*
   19053 ** Reset an StrAccum string.  Reclaim all malloced memory.
   19054 */
   19055 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
   19056   if( p->zText!=p->zBase ){
   19057     if( p->useMalloc==1 ){
   19058       sqlite3DbFree(p->db, p->zText);
   19059     }else{
   19060       sqlite3_free(p->zText);
   19061     }
   19062   }
   19063   p->zText = 0;
   19064 }
   19065 
   19066 /*
   19067 ** Initialize a string accumulator
   19068 */
   19069 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
   19070   p->zText = p->zBase = zBase;
   19071   p->db = 0;
   19072   p->nChar = 0;
   19073   p->nAlloc = n;
   19074   p->mxAlloc = mx;
   19075   p->useMalloc = 1;
   19076   p->tooBig = 0;
   19077   p->mallocFailed = 0;
   19078 }
   19079 
   19080 /*
   19081 ** Print into memory obtained from sqliteMalloc().  Use the internal
   19082 ** %-conversion extensions.
   19083 */
   19084 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
   19085   char *z;
   19086   char zBase[SQLITE_PRINT_BUF_SIZE];
   19087   StrAccum acc;
   19088   assert( db!=0 );
   19089   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
   19090                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   19091   acc.db = db;
   19092   sqlite3VXPrintf(&acc, 1, zFormat, ap);
   19093   z = sqlite3StrAccumFinish(&acc);
   19094   if( acc.mallocFailed ){
   19095     db->mallocFailed = 1;
   19096   }
   19097   return z;
   19098 }
   19099 
   19100 /*
   19101 ** Print into memory obtained from sqliteMalloc().  Use the internal
   19102 ** %-conversion extensions.
   19103 */
   19104 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
   19105   va_list ap;
   19106   char *z;
   19107   va_start(ap, zFormat);
   19108   z = sqlite3VMPrintf(db, zFormat, ap);
   19109   va_end(ap);
   19110   return z;
   19111 }
   19112 
   19113 /*
   19114 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
   19115 ** the string and before returnning.  This routine is intended to be used
   19116 ** to modify an existing string.  For example:
   19117 **
   19118 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
   19119 **
   19120 */
   19121 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
   19122   va_list ap;
   19123   char *z;
   19124   va_start(ap, zFormat);
   19125   z = sqlite3VMPrintf(db, zFormat, ap);
   19126   va_end(ap);
   19127   sqlite3DbFree(db, zStr);
   19128   return z;
   19129 }
   19130 
   19131 /*
   19132 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
   19133 ** %-conversion extensions.
   19134 */
   19135 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   19136   char *z;
   19137   char zBase[SQLITE_PRINT_BUF_SIZE];
   19138   StrAccum acc;
   19139 #ifndef SQLITE_OMIT_AUTOINIT
   19140   if( sqlite3_initialize() ) return 0;
   19141 #endif
   19142   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
   19143   acc.useMalloc = 2;
   19144   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   19145   z = sqlite3StrAccumFinish(&acc);
   19146   return z;
   19147 }
   19148 
   19149 /*
   19150 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
   19151 ** %-conversion extensions.
   19152 */
   19153 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
   19154   va_list ap;
   19155   char *z;
   19156 #ifndef SQLITE_OMIT_AUTOINIT
   19157   if( sqlite3_initialize() ) return 0;
   19158 #endif
   19159   va_start(ap, zFormat);
   19160   z = sqlite3_vmprintf(zFormat, ap);
   19161   va_end(ap);
   19162   return z;
   19163 }
   19164 
   19165 /*
   19166 ** sqlite3_snprintf() works like snprintf() except that it ignores the
   19167 ** current locale settings.  This is important for SQLite because we
   19168 ** are not able to use a "," as the decimal point in place of "." as
   19169 ** specified by some locales.
   19170 */
   19171 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
   19172   char *z;
   19173   va_list ap;
   19174   StrAccum acc;
   19175 
   19176   if( n<=0 ){
   19177     return zBuf;
   19178   }
   19179   sqlite3StrAccumInit(&acc, zBuf, n, 0);
   19180   acc.useMalloc = 0;
   19181   va_start(ap,zFormat);
   19182   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   19183   va_end(ap);
   19184   z = sqlite3StrAccumFinish(&acc);
   19185   return z;
   19186 }
   19187 
   19188 /*
   19189 ** This is the routine that actually formats the sqlite3_log() message.
   19190 ** We house it in a separate routine from sqlite3_log() to avoid using
   19191 ** stack space on small-stack systems when logging is disabled.
   19192 **
   19193 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
   19194 ** allocate memory because it might be called while the memory allocator
   19195 ** mutex is held.
   19196 */
   19197 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
   19198   StrAccum acc;                          /* String accumulator */
   19199   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
   19200 
   19201   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
   19202   acc.useMalloc = 0;
   19203   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   19204   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
   19205                            sqlite3StrAccumFinish(&acc));
   19206 }
   19207 
   19208 /*
   19209 ** Format and write a message to the log if logging is enabled.
   19210 */
   19211 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
   19212   va_list ap;                             /* Vararg list */
   19213   if( sqlite3GlobalConfig.xLog ){
   19214     va_start(ap, zFormat);
   19215     renderLogMsg(iErrCode, zFormat, ap);
   19216     va_end(ap);
   19217   }
   19218 }
   19219 
   19220 #if defined(SQLITE_DEBUG)
   19221 /*
   19222 ** A version of printf() that understands %lld.  Used for debugging.
   19223 ** The printf() built into some versions of windows does not understand %lld
   19224 ** and segfaults if you give it a long long int.
   19225 */
   19226 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   19227   va_list ap;
   19228   StrAccum acc;
   19229   char zBuf[500];
   19230   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
   19231   acc.useMalloc = 0;
   19232   va_start(ap,zFormat);
   19233   sqlite3VXPrintf(&acc, 0, zFormat, ap);
   19234   va_end(ap);
   19235   sqlite3StrAccumFinish(&acc);
   19236   fprintf(stdout,"%s", zBuf);
   19237   fflush(stdout);
   19238 }
   19239 #endif
   19240 
   19241 #ifndef SQLITE_OMIT_TRACE
   19242 /*
   19243 ** variable-argument wrapper around sqlite3VXPrintf().
   19244 */
   19245 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
   19246   va_list ap;
   19247   va_start(ap,zFormat);
   19248   sqlite3VXPrintf(p, 1, zFormat, ap);
   19249   va_end(ap);
   19250 }
   19251 #endif
   19252 
   19253 /************** End of printf.c **********************************************/
   19254 /************** Begin file random.c ******************************************/
   19255 /*
   19256 ** 2001 September 15
   19257 **
   19258 ** The author disclaims copyright to this source code.  In place of
   19259 ** a legal notice, here is a blessing:
   19260 **
   19261 **    May you do good and not evil.
   19262 **    May you find forgiveness for yourself and forgive others.
   19263 **    May you share freely, never taking more than you give.
   19264 **
   19265 *************************************************************************
   19266 ** This file contains code to implement a pseudo-random number
   19267 ** generator (PRNG) for SQLite.
   19268 **
   19269 ** Random numbers are used by some of the database backends in order
   19270 ** to generate random integer keys for tables or random filenames.
   19271 */
   19272 
   19273 
   19274 /* All threads share a single random number generator.
   19275 ** This structure is the current state of the generator.
   19276 */
   19277 static SQLITE_WSD struct sqlite3PrngType {
   19278   unsigned char isInit;          /* True if initialized */
   19279   unsigned char i, j;            /* State variables */
   19280   unsigned char s[256];          /* State variables */
   19281 } sqlite3Prng;
   19282 
   19283 /*
   19284 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
   19285 ** must be held while executing this routine.
   19286 **
   19287 ** Why not just use a library random generator like lrand48() for this?
   19288 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
   19289 ** good source of random numbers.  The lrand48() library function may
   19290 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
   19291 ** subtle problems on some systems that could cause problems.  It is hard
   19292 ** to know.  To minimize the risk of problems due to bad lrand48()
   19293 ** implementations, SQLite uses this random number generator based
   19294 ** on RC4, which we know works very well.
   19295 **
   19296 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
   19297 ** randomness any more.  But we will leave this code in all the same.
   19298 */
   19299 static u8 randomByte(void){
   19300   unsigned char t;
   19301 
   19302 
   19303   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
   19304   ** state vector.  If writable static data is unsupported on the target,
   19305   ** we have to locate the state vector at run-time.  In the more common
   19306   ** case where writable static data is supported, wsdPrng can refer directly
   19307   ** to the "sqlite3Prng" state vector declared above.
   19308   */
   19309 #ifdef SQLITE_OMIT_WSD
   19310   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
   19311 # define wsdPrng p[0]
   19312 #else
   19313 # define wsdPrng sqlite3Prng
   19314 #endif
   19315 
   19316 
   19317   /* Initialize the state of the random number generator once,
   19318   ** the first time this routine is called.  The seed value does
   19319   ** not need to contain a lot of randomness since we are not
   19320   ** trying to do secure encryption or anything like that...
   19321   **
   19322   ** Nothing in this file or anywhere else in SQLite does any kind of
   19323   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
   19324   ** number generator) not as an encryption device.
   19325   */
   19326   if( !wsdPrng.isInit ){
   19327     int i;
   19328     char k[256];
   19329     wsdPrng.j = 0;
   19330     wsdPrng.i = 0;
   19331     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
   19332     for(i=0; i<256; i++){
   19333       wsdPrng.s[i] = (u8)i;
   19334     }
   19335     for(i=0; i<256; i++){
   19336       wsdPrng.j += wsdPrng.s[i] + k[i];
   19337       t = wsdPrng.s[wsdPrng.j];
   19338       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
   19339       wsdPrng.s[i] = t;
   19340     }
   19341     wsdPrng.isInit = 1;
   19342   }
   19343 
   19344   /* Generate and return single random byte
   19345   */
   19346   wsdPrng.i++;
   19347   t = wsdPrng.s[wsdPrng.i];
   19348   wsdPrng.j += t;
   19349   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
   19350   wsdPrng.s[wsdPrng.j] = t;
   19351   t += wsdPrng.s[wsdPrng.i];
   19352   return wsdPrng.s[t];
   19353 }
   19354 
   19355 /*
   19356 ** Return N random bytes.
   19357 */
   19358 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
   19359   unsigned char *zBuf = pBuf;
   19360 #if SQLITE_THREADSAFE
   19361   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
   19362 #endif
   19363   sqlite3_mutex_enter(mutex);
   19364   while( N-- ){
   19365     *(zBuf++) = randomByte();
   19366   }
   19367   sqlite3_mutex_leave(mutex);
   19368 }
   19369 
   19370 #ifndef SQLITE_OMIT_BUILTIN_TEST
   19371 /*
   19372 ** For testing purposes, we sometimes want to preserve the state of
   19373 ** PRNG and restore the PRNG to its saved state at a later time, or
   19374 ** to reset the PRNG to its initial state.  These routines accomplish
   19375 ** those tasks.
   19376 **
   19377 ** The sqlite3_test_control() interface calls these routines to
   19378 ** control the PRNG.
   19379 */
   19380 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
   19381 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
   19382   memcpy(
   19383     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   19384     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   19385     sizeof(sqlite3Prng)
   19386   );
   19387 }
   19388 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
   19389   memcpy(
   19390     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
   19391     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
   19392     sizeof(sqlite3Prng)
   19393   );
   19394 }
   19395 SQLITE_PRIVATE void sqlite3PrngResetState(void){
   19396   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
   19397 }
   19398 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   19399 
   19400 /************** End of random.c **********************************************/
   19401 /************** Begin file utf.c *********************************************/
   19402 /*
   19403 ** 2004 April 13
   19404 **
   19405 ** The author disclaims copyright to this source code.  In place of
   19406 ** a legal notice, here is a blessing:
   19407 **
   19408 **    May you do good and not evil.
   19409 **    May you find forgiveness for yourself and forgive others.
   19410 **    May you share freely, never taking more than you give.
   19411 **
   19412 *************************************************************************
   19413 ** This file contains routines used to translate between UTF-8,
   19414 ** UTF-16, UTF-16BE, and UTF-16LE.
   19415 **
   19416 ** Notes on UTF-8:
   19417 **
   19418 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
   19419 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
   19420 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
   19421 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
   19422 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
   19423 **
   19424 **
   19425 ** Notes on UTF-16:  (with wwww+1==uuuuu)
   19426 **
   19427 **      Word-0               Word-1          Value
   19428 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
   19429 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
   19430 **
   19431 **
   19432 ** BOM or Byte Order Mark:
   19433 **     0xff 0xfe   little-endian utf-16 follows
   19434 **     0xfe 0xff   big-endian utf-16 follows
   19435 **
   19436 */
   19437 
   19438 #ifndef SQLITE_AMALGAMATION
   19439 /*
   19440 ** The following constant value is used by the SQLITE_BIGENDIAN and
   19441 ** SQLITE_LITTLEENDIAN macros.
   19442 */
   19443 SQLITE_PRIVATE const int sqlite3one = 1;
   19444 #endif /* SQLITE_AMALGAMATION */
   19445 
   19446 /*
   19447 ** This lookup table is used to help decode the first byte of
   19448 ** a multi-byte UTF8 character.
   19449 */
   19450 static const unsigned char sqlite3Utf8Trans1[] = {
   19451   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   19452   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   19453   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
   19454   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
   19455   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   19456   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
   19457   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
   19458   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
   19459 };
   19460 
   19461 
   19462 #define WRITE_UTF8(zOut, c) {                          \
   19463   if( c<0x00080 ){                                     \
   19464     *zOut++ = (u8)(c&0xFF);                            \
   19465   }                                                    \
   19466   else if( c<0x00800 ){                                \
   19467     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
   19468     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   19469   }                                                    \
   19470   else if( c<0x10000 ){                                \
   19471     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
   19472     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   19473     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   19474   }else{                                               \
   19475     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
   19476     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
   19477     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
   19478     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
   19479   }                                                    \
   19480 }
   19481 
   19482 #define WRITE_UTF16LE(zOut, c) {                                    \
   19483   if( c<=0xFFFF ){                                                  \
   19484     *zOut++ = (u8)(c&0x00FF);                                       \
   19485     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   19486   }else{                                                            \
   19487     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   19488     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   19489     *zOut++ = (u8)(c&0x00FF);                                       \
   19490     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   19491   }                                                                 \
   19492 }
   19493 
   19494 #define WRITE_UTF16BE(zOut, c) {                                    \
   19495   if( c<=0xFFFF ){                                                  \
   19496     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
   19497     *zOut++ = (u8)(c&0x00FF);                                       \
   19498   }else{                                                            \
   19499     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
   19500     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
   19501     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
   19502     *zOut++ = (u8)(c&0x00FF);                                       \
   19503   }                                                                 \
   19504 }
   19505 
   19506 #define READ_UTF16LE(zIn, TERM, c){                                   \
   19507   c = (*zIn++);                                                       \
   19508   c += ((*zIn++)<<8);                                                 \
   19509   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   19510     int c2 = (*zIn++);                                                \
   19511     c2 += ((*zIn++)<<8);                                              \
   19512     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   19513   }                                                                   \
   19514 }
   19515 
   19516 #define READ_UTF16BE(zIn, TERM, c){                                   \
   19517   c = ((*zIn++)<<8);                                                  \
   19518   c += (*zIn++);                                                      \
   19519   if( c>=0xD800 && c<0xE000 && TERM ){                                \
   19520     int c2 = ((*zIn++)<<8);                                           \
   19521     c2 += (*zIn++);                                                   \
   19522     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
   19523   }                                                                   \
   19524 }
   19525 
   19526 /*
   19527 ** Translate a single UTF-8 character.  Return the unicode value.
   19528 **
   19529 ** During translation, assume that the byte that zTerm points
   19530 ** is a 0x00.
   19531 **
   19532 ** Write a pointer to the next unread byte back into *pzNext.
   19533 **
   19534 ** Notes On Invalid UTF-8:
   19535 **
   19536 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
   19537 **     be encoded as a multi-byte character.  Any multi-byte character that
   19538 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
   19539 **
   19540 **  *  This routine never allows a UTF16 surrogate value to be encoded.
   19541 **     If a multi-byte character attempts to encode a value between
   19542 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
   19543 **
   19544 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
   19545 **     byte of a character are interpreted as single-byte characters
   19546 **     and rendered as themselves even though they are technically
   19547 **     invalid characters.
   19548 **
   19549 **  *  This routine accepts an infinite number of different UTF8 encodings
   19550 **     for unicode values 0x80 and greater.  It do not change over-length
   19551 **     encodings to 0xfffd as some systems recommend.
   19552 */
   19553 #define READ_UTF8(zIn, zTerm, c)                           \
   19554   c = *(zIn++);                                            \
   19555   if( c>=0xc0 ){                                           \
   19556     c = sqlite3Utf8Trans1[c-0xc0];                         \
   19557     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
   19558       c = (c<<6) + (0x3f & *(zIn++));                      \
   19559     }                                                      \
   19560     if( c<0x80                                             \
   19561         || (c&0xFFFFF800)==0xD800                          \
   19562         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
   19563   }
   19564 SQLITE_PRIVATE int sqlite3Utf8Read(
   19565   const unsigned char *zIn,       /* First byte of UTF-8 character */
   19566   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
   19567 ){
   19568   int c;
   19569 
   19570   /* Same as READ_UTF8() above but without the zTerm parameter.
   19571   ** For this routine, we assume the UTF8 string is always zero-terminated.
   19572   */
   19573   c = *(zIn++);
   19574   if( c>=0xc0 ){
   19575     c = sqlite3Utf8Trans1[c-0xc0];
   19576     while( (*zIn & 0xc0)==0x80 ){
   19577       c = (c<<6) + (0x3f & *(zIn++));
   19578     }
   19579     if( c<0x80
   19580         || (c&0xFFFFF800)==0xD800
   19581         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
   19582   }
   19583   *pzNext = zIn;
   19584   return c;
   19585 }
   19586 
   19587 
   19588 
   19589 
   19590 /*
   19591 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
   19592 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
   19593 */
   19594 /* #define TRANSLATE_TRACE 1 */
   19595 
   19596 #ifndef SQLITE_OMIT_UTF16
   19597 /*
   19598 ** This routine transforms the internal text encoding used by pMem to
   19599 ** desiredEnc. It is an error if the string is already of the desired
   19600 ** encoding, or if *pMem does not contain a string value.
   19601 */
   19602 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
   19603   int len;                    /* Maximum length of output string in bytes */
   19604   unsigned char *zOut;                  /* Output buffer */
   19605   unsigned char *zIn;                   /* Input iterator */
   19606   unsigned char *zTerm;                 /* End of input */
   19607   unsigned char *z;                     /* Output iterator */
   19608   unsigned int c;
   19609 
   19610   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   19611   assert( pMem->flags&MEM_Str );
   19612   assert( pMem->enc!=desiredEnc );
   19613   assert( pMem->enc!=0 );
   19614   assert( pMem->n>=0 );
   19615 
   19616 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   19617   {
   19618     char zBuf[100];
   19619     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   19620     fprintf(stderr, "INPUT:  %s\n", zBuf);
   19621   }
   19622 #endif
   19623 
   19624   /* If the translation is between UTF-16 little and big endian, then
   19625   ** all that is required is to swap the byte order. This case is handled
   19626   ** differently from the others.
   19627   */
   19628   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
   19629     u8 temp;
   19630     int rc;
   19631     rc = sqlite3VdbeMemMakeWriteable(pMem);
   19632     if( rc!=SQLITE_OK ){
   19633       assert( rc==SQLITE_NOMEM );
   19634       return SQLITE_NOMEM;
   19635     }
   19636     zIn = (u8*)pMem->z;
   19637     zTerm = &zIn[pMem->n&~1];
   19638     while( zIn<zTerm ){
   19639       temp = *zIn;
   19640       *zIn = *(zIn+1);
   19641       zIn++;
   19642       *zIn++ = temp;
   19643     }
   19644     pMem->enc = desiredEnc;
   19645     goto translate_out;
   19646   }
   19647 
   19648   /* Set len to the maximum number of bytes required in the output buffer. */
   19649   if( desiredEnc==SQLITE_UTF8 ){
   19650     /* When converting from UTF-16, the maximum growth results from
   19651     ** translating a 2-byte character to a 4-byte UTF-8 character.
   19652     ** A single byte is required for the output string
   19653     ** nul-terminator.
   19654     */
   19655     pMem->n &= ~1;
   19656     len = pMem->n * 2 + 1;
   19657   }else{
   19658     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
   19659     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
   19660     ** character. Two bytes are required in the output buffer for the
   19661     ** nul-terminator.
   19662     */
   19663     len = pMem->n * 2 + 2;
   19664   }
   19665 
   19666   /* Set zIn to point at the start of the input buffer and zTerm to point 1
   19667   ** byte past the end.
   19668   **
   19669   ** Variable zOut is set to point at the output buffer, space obtained
   19670   ** from sqlite3_malloc().
   19671   */
   19672   zIn = (u8*)pMem->z;
   19673   zTerm = &zIn[pMem->n];
   19674   zOut = sqlite3DbMallocRaw(pMem->db, len);
   19675   if( !zOut ){
   19676     return SQLITE_NOMEM;
   19677   }
   19678   z = zOut;
   19679 
   19680   if( pMem->enc==SQLITE_UTF8 ){
   19681     if( desiredEnc==SQLITE_UTF16LE ){
   19682       /* UTF-8 -> UTF-16 Little-endian */
   19683       while( zIn<zTerm ){
   19684         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   19685         READ_UTF8(zIn, zTerm, c);
   19686         WRITE_UTF16LE(z, c);
   19687       }
   19688     }else{
   19689       assert( desiredEnc==SQLITE_UTF16BE );
   19690       /* UTF-8 -> UTF-16 Big-endian */
   19691       while( zIn<zTerm ){
   19692         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
   19693         READ_UTF8(zIn, zTerm, c);
   19694         WRITE_UTF16BE(z, c);
   19695       }
   19696     }
   19697     pMem->n = (int)(z - zOut);
   19698     *z++ = 0;
   19699   }else{
   19700     assert( desiredEnc==SQLITE_UTF8 );
   19701     if( pMem->enc==SQLITE_UTF16LE ){
   19702       /* UTF-16 Little-endian -> UTF-8 */
   19703       while( zIn<zTerm ){
   19704         READ_UTF16LE(zIn, zIn<zTerm, c);
   19705         WRITE_UTF8(z, c);
   19706       }
   19707     }else{
   19708       /* UTF-16 Big-endian -> UTF-8 */
   19709       while( zIn<zTerm ){
   19710         READ_UTF16BE(zIn, zIn<zTerm, c);
   19711         WRITE_UTF8(z, c);
   19712       }
   19713     }
   19714     pMem->n = (int)(z - zOut);
   19715   }
   19716   *z = 0;
   19717   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   19718 
   19719   sqlite3VdbeMemRelease(pMem);
   19720   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
   19721   pMem->enc = desiredEnc;
   19722   pMem->flags |= (MEM_Term|MEM_Dyn);
   19723   pMem->z = (char*)zOut;
   19724   pMem->zMalloc = pMem->z;
   19725 
   19726 translate_out:
   19727 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   19728   {
   19729     char zBuf[100];
   19730     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
   19731     fprintf(stderr, "OUTPUT: %s\n", zBuf);
   19732   }
   19733 #endif
   19734   return SQLITE_OK;
   19735 }
   19736 
   19737 /*
   19738 ** This routine checks for a byte-order mark at the beginning of the
   19739 ** UTF-16 string stored in *pMem. If one is present, it is removed and
   19740 ** the encoding of the Mem adjusted. This routine does not do any
   19741 ** byte-swapping, it just sets Mem.enc appropriately.
   19742 **
   19743 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
   19744 ** changed by this function.
   19745 */
   19746 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
   19747   int rc = SQLITE_OK;
   19748   u8 bom = 0;
   19749 
   19750   assert( pMem->n>=0 );
   19751   if( pMem->n>1 ){
   19752     u8 b1 = *(u8 *)pMem->z;
   19753     u8 b2 = *(((u8 *)pMem->z) + 1);
   19754     if( b1==0xFE && b2==0xFF ){
   19755       bom = SQLITE_UTF16BE;
   19756     }
   19757     if( b1==0xFF && b2==0xFE ){
   19758       bom = SQLITE_UTF16LE;
   19759     }
   19760   }
   19761 
   19762   if( bom ){
   19763     rc = sqlite3VdbeMemMakeWriteable(pMem);
   19764     if( rc==SQLITE_OK ){
   19765       pMem->n -= 2;
   19766       memmove(pMem->z, &pMem->z[2], pMem->n);
   19767       pMem->z[pMem->n] = '\0';
   19768       pMem->z[pMem->n+1] = '\0';
   19769       pMem->flags |= MEM_Term;
   19770       pMem->enc = bom;
   19771     }
   19772   }
   19773   return rc;
   19774 }
   19775 #endif /* SQLITE_OMIT_UTF16 */
   19776 
   19777 /*
   19778 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
   19779 ** return the number of unicode characters in pZ up to (but not including)
   19780 ** the first 0x00 byte. If nByte is not less than zero, return the
   19781 ** number of unicode characters in the first nByte of pZ (or up to
   19782 ** the first 0x00, whichever comes first).
   19783 */
   19784 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   19785   int r = 0;
   19786   const u8 *z = (const u8*)zIn;
   19787   const u8 *zTerm;
   19788   if( nByte>=0 ){
   19789     zTerm = &z[nByte];
   19790   }else{
   19791     zTerm = (const u8*)(-1);
   19792   }
   19793   assert( z<=zTerm );
   19794   while( *z!=0 && z<zTerm ){
   19795     SQLITE_SKIP_UTF8(z);
   19796     r++;
   19797   }
   19798   return r;
   19799 }
   19800 
   19801 /* This test function is not currently used by the automated test-suite.
   19802 ** Hence it is only available in debug builds.
   19803 */
   19804 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   19805 /*
   19806 ** Translate UTF-8 to UTF-8.
   19807 **
   19808 ** This has the effect of making sure that the string is well-formed
   19809 ** UTF-8.  Miscoded characters are removed.
   19810 **
   19811 ** The translation is done in-place (since it is impossible for the
   19812 ** correct UTF-8 encoding to be longer than a malformed encoding).
   19813 */
   19814 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
   19815   unsigned char *zOut = zIn;
   19816   unsigned char *zStart = zIn;
   19817   u32 c;
   19818 
   19819   while( zIn[0] ){
   19820     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
   19821     if( c!=0xfffd ){
   19822       WRITE_UTF8(zOut, c);
   19823     }
   19824   }
   19825   *zOut = 0;
   19826   return (int)(zOut - zStart);
   19827 }
   19828 #endif
   19829 
   19830 #ifndef SQLITE_OMIT_UTF16
   19831 /*
   19832 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
   19833 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
   19834 ** be freed by the calling function.
   19835 **
   19836 ** NULL is returned if there is an allocation error.
   19837 */
   19838 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
   19839   Mem m;
   19840   memset(&m, 0, sizeof(m));
   19841   m.db = db;
   19842   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
   19843   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   19844   if( db->mallocFailed ){
   19845     sqlite3VdbeMemRelease(&m);
   19846     m.z = 0;
   19847   }
   19848   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   19849   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   19850   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
   19851   assert( m.z || db->mallocFailed );
   19852   return m.z;
   19853 }
   19854 
   19855 /*
   19856 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
   19857 ** enc. A pointer to the new string is returned, and the value of *pnOut
   19858 ** is set to the length of the returned string in bytes. The call should
   19859 ** arrange to call sqlite3DbFree() on the returned pointer when it is
   19860 ** no longer required.
   19861 **
   19862 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
   19863 ** flag set.
   19864 */
   19865 #ifdef SQLITE_ENABLE_STAT2
   19866 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
   19867   Mem m;
   19868   memset(&m, 0, sizeof(m));
   19869   m.db = db;
   19870   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
   19871   if( sqlite3VdbeMemTranslate(&m, enc) ){
   19872     assert( db->mallocFailed );
   19873     return 0;
   19874   }
   19875   assert( m.z==m.zMalloc );
   19876   *pnOut = m.n;
   19877   return m.z;
   19878 }
   19879 #endif
   19880 
   19881 /*
   19882 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   19883 ** Return the number of bytes in the first nChar unicode characters
   19884 ** in pZ.  nChar must be non-negative.
   19885 */
   19886 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   19887   int c;
   19888   unsigned char const *z = zIn;
   19889   int n = 0;
   19890 
   19891   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
   19892     while( n<nChar ){
   19893       READ_UTF16BE(z, 1, c);
   19894       n++;
   19895     }
   19896   }else{
   19897     while( n<nChar ){
   19898       READ_UTF16LE(z, 1, c);
   19899       n++;
   19900     }
   19901   }
   19902   return (int)(z-(unsigned char const *)zIn);
   19903 }
   19904 
   19905 #if defined(SQLITE_TEST)
   19906 /*
   19907 ** This routine is called from the TCL test function "translate_selftest".
   19908 ** It checks that the primitives for serializing and deserializing
   19909 ** characters in each encoding are inverses of each other.
   19910 */
   19911 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
   19912   unsigned int i, t;
   19913   unsigned char zBuf[20];
   19914   unsigned char *z;
   19915   int n;
   19916   unsigned int c;
   19917 
   19918   for(i=0; i<0x00110000; i++){
   19919     z = zBuf;
   19920     WRITE_UTF8(z, i);
   19921     n = (int)(z-zBuf);
   19922     assert( n>0 && n<=4 );
   19923     z[0] = 0;
   19924     z = zBuf;
   19925     c = sqlite3Utf8Read(z, (const u8**)&z);
   19926     t = i;
   19927     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
   19928     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
   19929     assert( c==t );
   19930     assert( (z-zBuf)==n );
   19931   }
   19932   for(i=0; i<0x00110000; i++){
   19933     if( i>=0xD800 && i<0xE000 ) continue;
   19934     z = zBuf;
   19935     WRITE_UTF16LE(z, i);
   19936     n = (int)(z-zBuf);
   19937     assert( n>0 && n<=4 );
   19938     z[0] = 0;
   19939     z = zBuf;
   19940     READ_UTF16LE(z, 1, c);
   19941     assert( c==i );
   19942     assert( (z-zBuf)==n );
   19943   }
   19944   for(i=0; i<0x00110000; i++){
   19945     if( i>=0xD800 && i<0xE000 ) continue;
   19946     z = zBuf;
   19947     WRITE_UTF16BE(z, i);
   19948     n = (int)(z-zBuf);
   19949     assert( n>0 && n<=4 );
   19950     z[0] = 0;
   19951     z = zBuf;
   19952     READ_UTF16BE(z, 1, c);
   19953     assert( c==i );
   19954     assert( (z-zBuf)==n );
   19955   }
   19956 }
   19957 #endif /* SQLITE_TEST */
   19958 #endif /* SQLITE_OMIT_UTF16 */
   19959 
   19960 /************** End of utf.c *************************************************/
   19961 /************** Begin file util.c ********************************************/
   19962 /*
   19963 ** 2001 September 15
   19964 **
   19965 ** The author disclaims copyright to this source code.  In place of
   19966 ** a legal notice, here is a blessing:
   19967 **
   19968 **    May you do good and not evil.
   19969 **    May you find forgiveness for yourself and forgive others.
   19970 **    May you share freely, never taking more than you give.
   19971 **
   19972 *************************************************************************
   19973 ** Utility functions used throughout sqlite.
   19974 **
   19975 ** This file contains functions for allocating memory, comparing
   19976 ** strings, and stuff like that.
   19977 **
   19978 */
   19979 #ifdef SQLITE_HAVE_ISNAN
   19980 # include <math.h>
   19981 #endif
   19982 
   19983 /*
   19984 ** Routine needed to support the testcase() macro.
   19985 */
   19986 #ifdef SQLITE_COVERAGE_TEST
   19987 SQLITE_PRIVATE void sqlite3Coverage(int x){
   19988   static int dummy = 0;
   19989   dummy += x;
   19990 }
   19991 #endif
   19992 
   19993 #ifndef SQLITE_OMIT_FLOATING_POINT
   19994 /*
   19995 ** Return true if the floating point value is Not a Number (NaN).
   19996 **
   19997 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
   19998 ** Otherwise, we have our own implementation that works on most systems.
   19999 */
   20000 SQLITE_PRIVATE int sqlite3IsNaN(double x){
   20001   int rc;   /* The value return */
   20002 #if !defined(SQLITE_HAVE_ISNAN)
   20003   /*
   20004   ** Systems that support the isnan() library function should probably
   20005   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
   20006   ** found that many systems do not have a working isnan() function so
   20007   ** this implementation is provided as an alternative.
   20008   **
   20009   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
   20010   ** On the other hand, the use of -ffast-math comes with the following
   20011   ** warning:
   20012   **
   20013   **      This option [-ffast-math] should never be turned on by any
   20014   **      -O option since it can result in incorrect output for programs
   20015   **      which depend on an exact implementation of IEEE or ISO
   20016   **      rules/specifications for math functions.
   20017   **
   20018   ** Under MSVC, this NaN test may fail if compiled with a floating-
   20019   ** point precision mode other than /fp:precise.  From the MSDN
   20020   ** documentation:
   20021   **
   20022   **      The compiler [with /fp:precise] will properly handle comparisons
   20023   **      involving NaN. For example, x != x evaluates to true if x is NaN
   20024   **      ...
   20025   */
   20026 #ifdef __FAST_MATH__
   20027 # error SQLite will not work correctly with the -ffast-math option of GCC.
   20028 #endif
   20029   volatile double y = x;
   20030   volatile double z = y;
   20031   rc = (y!=z);
   20032 #else  /* if defined(SQLITE_HAVE_ISNAN) */
   20033   rc = isnan(x);
   20034 #endif /* SQLITE_HAVE_ISNAN */
   20035   testcase( rc );
   20036   return rc;
   20037 }
   20038 #endif /* SQLITE_OMIT_FLOATING_POINT */
   20039 
   20040 /*
   20041 ** Compute a string length that is limited to what can be stored in
   20042 ** lower 30 bits of a 32-bit signed integer.
   20043 **
   20044 ** The value returned will never be negative.  Nor will it ever be greater
   20045 ** than the actual length of the string.  For very long strings (greater
   20046 ** than 1GiB) the value returned might be less than the true string length.
   20047 */
   20048 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
   20049   const char *z2 = z;
   20050   if( z==0 ) return 0;
   20051   while( *z2 ){ z2++; }
   20052   return 0x3fffffff & (int)(z2 - z);
   20053 }
   20054 
   20055 /*
   20056 ** Set the most recent error code and error string for the sqlite
   20057 ** handle "db". The error code is set to "err_code".
   20058 **
   20059 ** If it is not NULL, string zFormat specifies the format of the
   20060 ** error string in the style of the printf functions: The following
   20061 ** format characters are allowed:
   20062 **
   20063 **      %s      Insert a string
   20064 **      %z      A string that should be freed after use
   20065 **      %d      Insert an integer
   20066 **      %T      Insert a token
   20067 **      %S      Insert the first element of a SrcList
   20068 **
   20069 ** zFormat and any string tokens that follow it are assumed to be
   20070 ** encoded in UTF-8.
   20071 **
   20072 ** To clear the most recent error for sqlite handle "db", sqlite3Error
   20073 ** should be called with err_code set to SQLITE_OK and zFormat set
   20074 ** to NULL.
   20075 */
   20076 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
   20077   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
   20078     db->errCode = err_code;
   20079     if( zFormat ){
   20080       char *z;
   20081       va_list ap;
   20082       va_start(ap, zFormat);
   20083       z = sqlite3VMPrintf(db, zFormat, ap);
   20084       va_end(ap);
   20085       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
   20086     }else{
   20087       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
   20088     }
   20089   }
   20090 }
   20091 
   20092 /*
   20093 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
   20094 ** The following formatting characters are allowed:
   20095 **
   20096 **      %s      Insert a string
   20097 **      %z      A string that should be freed after use
   20098 **      %d      Insert an integer
   20099 **      %T      Insert a token
   20100 **      %S      Insert the first element of a SrcList
   20101 **
   20102 ** This function should be used to report any error that occurs whilst
   20103 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
   20104 ** last thing the sqlite3_prepare() function does is copy the error
   20105 ** stored by this function into the database handle using sqlite3Error().
   20106 ** Function sqlite3Error() should be used during statement execution
   20107 ** (sqlite3_step() etc.).
   20108 */
   20109 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
   20110   char *zMsg;
   20111   va_list ap;
   20112   sqlite3 *db = pParse->db;
   20113   va_start(ap, zFormat);
   20114   zMsg = sqlite3VMPrintf(db, zFormat, ap);
   20115   va_end(ap);
   20116   if( db->suppressErr ){
   20117     sqlite3DbFree(db, zMsg);
   20118   }else{
   20119     pParse->nErr++;
   20120     sqlite3DbFree(db, pParse->zErrMsg);
   20121     pParse->zErrMsg = zMsg;
   20122     pParse->rc = SQLITE_ERROR;
   20123   }
   20124 }
   20125 
   20126 /*
   20127 ** Convert an SQL-style quoted string into a normal string by removing
   20128 ** the quote characters.  The conversion is done in-place.  If the
   20129 ** input does not begin with a quote character, then this routine
   20130 ** is a no-op.
   20131 **
   20132 ** The input string must be zero-terminated.  A new zero-terminator
   20133 ** is added to the dequoted string.
   20134 **
   20135 ** The return value is -1 if no dequoting occurs or the length of the
   20136 ** dequoted string, exclusive of the zero terminator, if dequoting does
   20137 ** occur.
   20138 **
   20139 ** 2002-Feb-14: This routine is extended to remove MS-Access style
   20140 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
   20141 ** "a-b-c".
   20142 */
   20143 SQLITE_PRIVATE int sqlite3Dequote(char *z){
   20144   char quote;
   20145   int i, j;
   20146   if( z==0 ) return -1;
   20147   quote = z[0];
   20148   switch( quote ){
   20149     case '\'':  break;
   20150     case '"':   break;
   20151     case '`':   break;                /* For MySQL compatibility */
   20152     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
   20153     default:    return -1;
   20154   }
   20155   for(i=1, j=0; ALWAYS(z[i]); i++){
   20156     if( z[i]==quote ){
   20157       if( z[i+1]==quote ){
   20158         z[j++] = quote;
   20159         i++;
   20160       }else{
   20161         break;
   20162       }
   20163     }else{
   20164       z[j++] = z[i];
   20165     }
   20166   }
   20167   z[j] = 0;
   20168   return j;
   20169 }
   20170 
   20171 /* Convenient short-hand */
   20172 #define UpperToLower sqlite3UpperToLower
   20173 
   20174 /*
   20175 ** Some systems have stricmp().  Others have strcasecmp().  Because
   20176 ** there is no consistency, we will define our own.
   20177 **
   20178 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
   20179 ** applications and extensions to compare the contents of two buffers
   20180 ** containing UTF-8 strings in a case-independent fashion, using the same
   20181 ** definition of case independence that SQLite uses internally when
   20182 ** comparing identifiers.
   20183 */
   20184 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
   20185   register unsigned char *a, *b;
   20186   a = (unsigned char *)zLeft;
   20187   b = (unsigned char *)zRight;
   20188   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   20189   return UpperToLower[*a] - UpperToLower[*b];
   20190 }
   20191 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
   20192   register unsigned char *a, *b;
   20193   a = (unsigned char *)zLeft;
   20194   b = (unsigned char *)zRight;
   20195   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
   20196   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
   20197 }
   20198 
   20199 /*
   20200 ** The string z[] is an text representation of a real number.
   20201 ** Convert this string to a double and write it into *pResult.
   20202 **
   20203 ** The string z[] is length bytes in length (bytes, not characters) and
   20204 ** uses the encoding enc.  The string is not necessarily zero-terminated.
   20205 **
   20206 ** Return TRUE if the result is a valid real number (or integer) and FALSE
   20207 ** if the string is empty or contains extraneous text.  Valid numbers
   20208 ** are in one of these formats:
   20209 **
   20210 **    [+-]digits[E[+-]digits]
   20211 **    [+-]digits.[digits][E[+-]digits]
   20212 **    [+-].digits[E[+-]digits]
   20213 **
   20214 ** Leading and trailing whitespace is ignored for the purpose of determining
   20215 ** validity.
   20216 **
   20217 ** If some prefix of the input string is a valid number, this routine
   20218 ** returns FALSE but it still converts the prefix and writes the result
   20219 ** into *pResult.
   20220 */
   20221 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
   20222 #ifndef SQLITE_OMIT_FLOATING_POINT
   20223   int incr = (enc==SQLITE_UTF8?1:2);
   20224   const char *zEnd = z + length;
   20225   /* sign * significand * (10 ^ (esign * exponent)) */
   20226   int sign = 1;    /* sign of significand */
   20227   i64 s = 0;       /* significand */
   20228   int d = 0;       /* adjust exponent for shifting decimal point */
   20229   int esign = 1;   /* sign of exponent */
   20230   int e = 0;       /* exponent */
   20231   int eValid = 1;  /* True exponent is either not used or is well-formed */
   20232   double result;
   20233   int nDigits = 0;
   20234 
   20235   *pResult = 0.0;   /* Default return value, in case of an error */
   20236 
   20237   if( enc==SQLITE_UTF16BE ) z++;
   20238 
   20239   /* skip leading spaces */
   20240   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   20241   if( z>=zEnd ) return 0;
   20242 
   20243   /* get sign of significand */
   20244   if( *z=='-' ){
   20245     sign = -1;
   20246     z+=incr;
   20247   }else if( *z=='+' ){
   20248     z+=incr;
   20249   }
   20250 
   20251   /* skip leading zeroes */
   20252   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
   20253 
   20254   /* copy max significant digits to significand */
   20255   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   20256     s = s*10 + (*z - '0');
   20257     z+=incr, nDigits++;
   20258   }
   20259 
   20260   /* skip non-significant significand digits
   20261   ** (increase exponent by d to shift decimal left) */
   20262   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
   20263   if( z>=zEnd ) goto do_atof_calc;
   20264 
   20265   /* if decimal point is present */
   20266   if( *z=='.' ){
   20267     z+=incr;
   20268     /* copy digits from after decimal to significand
   20269     ** (decrease exponent by d to shift decimal right) */
   20270     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
   20271       s = s*10 + (*z - '0');
   20272       z+=incr, nDigits++, d--;
   20273     }
   20274     /* skip non-significant digits */
   20275     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
   20276   }
   20277   if( z>=zEnd ) goto do_atof_calc;
   20278 
   20279   /* if exponent is present */
   20280   if( *z=='e' || *z=='E' ){
   20281     z+=incr;
   20282     eValid = 0;
   20283     if( z>=zEnd ) goto do_atof_calc;
   20284     /* get sign of exponent */
   20285     if( *z=='-' ){
   20286       esign = -1;
   20287       z+=incr;
   20288     }else if( *z=='+' ){
   20289       z+=incr;
   20290     }
   20291     /* copy digits to exponent */
   20292     while( z<zEnd && sqlite3Isdigit(*z) ){
   20293       e = e*10 + (*z - '0');
   20294       z+=incr;
   20295       eValid = 1;
   20296     }
   20297   }
   20298 
   20299   /* skip trailing spaces */
   20300   if( nDigits && eValid ){
   20301     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
   20302   }
   20303 
   20304 do_atof_calc:
   20305   /* adjust exponent by d, and update sign */
   20306   e = (e*esign) + d;
   20307   if( e<0 ) {
   20308     esign = -1;
   20309     e *= -1;
   20310   } else {
   20311     esign = 1;
   20312   }
   20313 
   20314   /* if 0 significand */
   20315   if( !s ) {
   20316     /* In the IEEE 754 standard, zero is signed.
   20317     ** Add the sign if we've seen at least one digit */
   20318     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
   20319   } else {
   20320     /* attempt to reduce exponent */
   20321     if( esign>0 ){
   20322       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
   20323     }else{
   20324       while( !(s%10) && e>0 ) e--,s/=10;
   20325     }
   20326 
   20327     /* adjust the sign of significand */
   20328     s = sign<0 ? -s : s;
   20329 
   20330     /* if exponent, scale significand as appropriate
   20331     ** and store in result. */
   20332     if( e ){
   20333       double scale = 1.0;
   20334       /* attempt to handle extremely small/large numbers better */
   20335       if( e>307 && e<342 ){
   20336         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
   20337         if( esign<0 ){
   20338           result = s / scale;
   20339           result /= 1.0e+308;
   20340         }else{
   20341           result = s * scale;
   20342           result *= 1.0e+308;
   20343         }
   20344       }else{
   20345         /* 1.0e+22 is the largest power of 10 than can be
   20346         ** represented exactly. */
   20347         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
   20348         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
   20349         if( esign<0 ){
   20350           result = s / scale;
   20351         }else{
   20352           result = s * scale;
   20353         }
   20354       }
   20355     } else {
   20356       result = (double)s;
   20357     }
   20358   }
   20359 
   20360   /* store the result */
   20361   *pResult = result;
   20362 
   20363   /* return true if number and no extra non-whitespace chracters after */
   20364   return z>=zEnd && nDigits>0 && eValid;
   20365 #else
   20366   return !sqlite3Atoi64(z, pResult, length, enc);
   20367 #endif /* SQLITE_OMIT_FLOATING_POINT */
   20368 }
   20369 
   20370 /*
   20371 ** Compare the 19-character string zNum against the text representation
   20372 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
   20373 ** if zNum is less than, equal to, or greater than the string.
   20374 ** Note that zNum must contain exactly 19 characters.
   20375 **
   20376 ** Unlike memcmp() this routine is guaranteed to return the difference
   20377 ** in the values of the last digit if the only difference is in the
   20378 ** last digit.  So, for example,
   20379 **
   20380 **      compare2pow63("9223372036854775800", 1)
   20381 **
   20382 ** will return -8.
   20383 */
   20384 static int compare2pow63(const char *zNum, int incr){
   20385   int c = 0;
   20386   int i;
   20387                     /* 012345678901234567 */
   20388   const char *pow63 = "922337203685477580";
   20389   for(i=0; c==0 && i<18; i++){
   20390     c = (zNum[i*incr]-pow63[i])*10;
   20391   }
   20392   if( c==0 ){
   20393     c = zNum[18*incr] - '8';
   20394     testcase( c==(-1) );
   20395     testcase( c==0 );
   20396     testcase( c==(+1) );
   20397   }
   20398   return c;
   20399 }
   20400 
   20401 
   20402 /*
   20403 ** Convert zNum to a 64-bit signed integer and write
   20404 ** the value of the integer into *pNum.
   20405 ** If zNum is exactly 9223372036854665808, return 2.
   20406 ** This is a special case as the context will determine
   20407 ** if it is too big (used as a negative).
   20408 ** If zNum is not an integer or is an integer that
   20409 ** is too large to be expressed with 64 bits,
   20410 ** then return 1.  Otherwise return 0.
   20411 **
   20412 ** length is the number of bytes in the string (bytes, not characters).
   20413 ** The string is not necessarily zero-terminated.  The encoding is
   20414 ** given by enc.
   20415 */
   20416 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
   20417   int incr = (enc==SQLITE_UTF8?1:2);
   20418   i64 v = 0;
   20419   int neg = 0; /* assume positive */
   20420   int i;
   20421   int c = 0;
   20422   const char *zStart;
   20423   const char *zEnd = zNum + length;
   20424   if( enc==SQLITE_UTF16BE ) zNum++;
   20425   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
   20426   if( zNum>=zEnd ) goto do_atoi_calc;
   20427   if( *zNum=='-' ){
   20428     neg = 1;
   20429     zNum+=incr;
   20430   }else if( *zNum=='+' ){
   20431     zNum+=incr;
   20432   }
   20433 do_atoi_calc:
   20434   zStart = zNum;
   20435   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
   20436   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
   20437     v = v*10 + c - '0';
   20438   }
   20439   *pNum = neg ? -v : v;
   20440   testcase( i==18 );
   20441   testcase( i==19 );
   20442   testcase( i==20 );
   20443   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
   20444     /* zNum is empty or contains non-numeric text or is longer
   20445     ** than 19 digits (thus guaranteeing that it is too large) */
   20446     return 1;
   20447   }else if( i<19*incr ){
   20448     /* Less than 19 digits, so we know that it fits in 64 bits */
   20449     return 0;
   20450   }else{
   20451     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
   20452     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
   20453     ** is 2^63. Return 1 if to large */
   20454     c=compare2pow63(zNum, incr);
   20455     if( c==0 && neg==0 ) return 2; /* too big, exactly 9223372036854665808 */
   20456     return c<neg ? 0 : 1;
   20457   }
   20458 }
   20459 
   20460 /*
   20461 ** If zNum represents an integer that will fit in 32-bits, then set
   20462 ** *pValue to that integer and return true.  Otherwise return false.
   20463 **
   20464 ** Any non-numeric characters that following zNum are ignored.
   20465 ** This is different from sqlite3Atoi64() which requires the
   20466 ** input number to be zero-terminated.
   20467 */
   20468 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
   20469   sqlite_int64 v = 0;
   20470   int i, c;
   20471   int neg = 0;
   20472   if( zNum[0]=='-' ){
   20473     neg = 1;
   20474     zNum++;
   20475   }else if( zNum[0]=='+' ){
   20476     zNum++;
   20477   }
   20478   while( zNum[0]=='0' ) zNum++;
   20479   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
   20480     v = v*10 + c;
   20481   }
   20482 
   20483   /* The longest decimal representation of a 32 bit integer is 10 digits:
   20484   **
   20485   **             1234567890
   20486   **     2^31 -> 2147483648
   20487   */
   20488   testcase( i==10 );
   20489   if( i>10 ){
   20490     return 0;
   20491   }
   20492   testcase( v-neg==2147483647 );
   20493   if( v-neg>2147483647 ){
   20494     return 0;
   20495   }
   20496   if( neg ){
   20497     v = -v;
   20498   }
   20499   *pValue = (int)v;
   20500   return 1;
   20501 }
   20502 
   20503 /*
   20504 ** Return a 32-bit integer value extracted from a string.  If the
   20505 ** string is not an integer, just return 0.
   20506 */
   20507 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
   20508   int x = 0;
   20509   if( z ) sqlite3GetInt32(z, &x);
   20510   return x;
   20511 }
   20512 
   20513 /*
   20514 ** The variable-length integer encoding is as follows:
   20515 **
   20516 ** KEY:
   20517 **         A = 0xxxxxxx    7 bits of data and one flag bit
   20518 **         B = 1xxxxxxx    7 bits of data and one flag bit
   20519 **         C = xxxxxxxx    8 bits of data
   20520 **
   20521 **  7 bits - A
   20522 ** 14 bits - BA
   20523 ** 21 bits - BBA
   20524 ** 28 bits - BBBA
   20525 ** 35 bits - BBBBA
   20526 ** 42 bits - BBBBBA
   20527 ** 49 bits - BBBBBBA
   20528 ** 56 bits - BBBBBBBA
   20529 ** 64 bits - BBBBBBBBC
   20530 */
   20531 
   20532 /*
   20533 ** Write a 64-bit variable-length integer to memory starting at p[0].
   20534 ** The length of data write will be between 1 and 9 bytes.  The number
   20535 ** of bytes written is returned.
   20536 **
   20537 ** A variable-length integer consists of the lower 7 bits of each byte
   20538 ** for all bytes that have the 8th bit set and one byte with the 8th
   20539 ** bit clear.  Except, if we get to the 9th byte, it stores the full
   20540 ** 8 bits and is the last byte.
   20541 */
   20542 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
   20543   int i, j, n;
   20544   u8 buf[10];
   20545   if( v & (((u64)0xff000000)<<32) ){
   20546     p[8] = (u8)v;
   20547     v >>= 8;
   20548     for(i=7; i>=0; i--){
   20549       p[i] = (u8)((v & 0x7f) | 0x80);
   20550       v >>= 7;
   20551     }
   20552     return 9;
   20553   }
   20554   n = 0;
   20555   do{
   20556     buf[n++] = (u8)((v & 0x7f) | 0x80);
   20557     v >>= 7;
   20558   }while( v!=0 );
   20559   buf[0] &= 0x7f;
   20560   assert( n<=9 );
   20561   for(i=0, j=n-1; j>=0; j--, i++){
   20562     p[i] = buf[j];
   20563   }
   20564   return n;
   20565 }
   20566 
   20567 /*
   20568 ** This routine is a faster version of sqlite3PutVarint() that only
   20569 ** works for 32-bit positive integers and which is optimized for
   20570 ** the common case of small integers.  A MACRO version, putVarint32,
   20571 ** is provided which inlines the single-byte case.  All code should use
   20572 ** the MACRO version as this function assumes the single-byte case has
   20573 ** already been handled.
   20574 */
   20575 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
   20576 #ifndef putVarint32
   20577   if( (v & ~0x7f)==0 ){
   20578     p[0] = v;
   20579     return 1;
   20580   }
   20581 #endif
   20582   if( (v & ~0x3fff)==0 ){
   20583     p[0] = (u8)((v>>7) | 0x80);
   20584     p[1] = (u8)(v & 0x7f);
   20585     return 2;
   20586   }
   20587   return sqlite3PutVarint(p, v);
   20588 }
   20589 
   20590 /*
   20591 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
   20592 ** are defined here rather than simply putting the constant expressions
   20593 ** inline in order to work around bugs in the RVT compiler.
   20594 **
   20595 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
   20596 **
   20597 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
   20598 */
   20599 #define SLOT_2_0     0x001fc07f
   20600 #define SLOT_4_2_0   0xf01fc07f
   20601 
   20602 
   20603 /*
   20604 ** Read a 64-bit variable-length integer from memory starting at p[0].
   20605 ** Return the number of bytes read.  The value is stored in *v.
   20606 */
   20607 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
   20608   u32 a,b,s;
   20609 
   20610   a = *p;
   20611   /* a: p0 (unmasked) */
   20612   if (!(a&0x80))
   20613   {
   20614     *v = a;
   20615     return 1;
   20616   }
   20617 
   20618   p++;
   20619   b = *p;
   20620   /* b: p1 (unmasked) */
   20621   if (!(b&0x80))
   20622   {
   20623     a &= 0x7f;
   20624     a = a<<7;
   20625     a |= b;
   20626     *v = a;
   20627     return 2;
   20628   }
   20629 
   20630   /* Verify that constants are precomputed correctly */
   20631   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
   20632   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
   20633 
   20634   p++;
   20635   a = a<<14;
   20636   a |= *p;
   20637   /* a: p0<<14 | p2 (unmasked) */
   20638   if (!(a&0x80))
   20639   {
   20640     a &= SLOT_2_0;
   20641     b &= 0x7f;
   20642     b = b<<7;
   20643     a |= b;
   20644     *v = a;
   20645     return 3;
   20646   }
   20647 
   20648   /* CSE1 from below */
   20649   a &= SLOT_2_0;
   20650   p++;
   20651   b = b<<14;
   20652   b |= *p;
   20653   /* b: p1<<14 | p3 (unmasked) */
   20654   if (!(b&0x80))
   20655   {
   20656     b &= SLOT_2_0;
   20657     /* moved CSE1 up */
   20658     /* a &= (0x7f<<14)|(0x7f); */
   20659     a = a<<7;
   20660     a |= b;
   20661     *v = a;
   20662     return 4;
   20663   }
   20664 
   20665   /* a: p0<<14 | p2 (masked) */
   20666   /* b: p1<<14 | p3 (unmasked) */
   20667   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   20668   /* moved CSE1 up */
   20669   /* a &= (0x7f<<14)|(0x7f); */
   20670   b &= SLOT_2_0;
   20671   s = a;
   20672   /* s: p0<<14 | p2 (masked) */
   20673 
   20674   p++;
   20675   a = a<<14;
   20676   a |= *p;
   20677   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   20678   if (!(a&0x80))
   20679   {
   20680     /* we can skip these cause they were (effectively) done above in calc'ing s */
   20681     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   20682     /* b &= (0x7f<<14)|(0x7f); */
   20683     b = b<<7;
   20684     a |= b;
   20685     s = s>>18;
   20686     *v = ((u64)s)<<32 | a;
   20687     return 5;
   20688   }
   20689 
   20690   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   20691   s = s<<7;
   20692   s |= b;
   20693   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
   20694 
   20695   p++;
   20696   b = b<<14;
   20697   b |= *p;
   20698   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
   20699   if (!(b&0x80))
   20700   {
   20701     /* we can skip this cause it was (effectively) done above in calc'ing s */
   20702     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
   20703     a &= SLOT_2_0;
   20704     a = a<<7;
   20705     a |= b;
   20706     s = s>>18;
   20707     *v = ((u64)s)<<32 | a;
   20708     return 6;
   20709   }
   20710 
   20711   p++;
   20712   a = a<<14;
   20713   a |= *p;
   20714   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
   20715   if (!(a&0x80))
   20716   {
   20717     a &= SLOT_4_2_0;
   20718     b &= SLOT_2_0;
   20719     b = b<<7;
   20720     a |= b;
   20721     s = s>>11;
   20722     *v = ((u64)s)<<32 | a;
   20723     return 7;
   20724   }
   20725 
   20726   /* CSE2 from below */
   20727   a &= SLOT_2_0;
   20728   p++;
   20729   b = b<<14;
   20730   b |= *p;
   20731   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
   20732   if (!(b&0x80))
   20733   {
   20734     b &= SLOT_4_2_0;
   20735     /* moved CSE2 up */
   20736     /* a &= (0x7f<<14)|(0x7f); */
   20737     a = a<<7;
   20738     a |= b;
   20739     s = s>>4;
   20740     *v = ((u64)s)<<32 | a;
   20741     return 8;
   20742   }
   20743 
   20744   p++;
   20745   a = a<<15;
   20746   a |= *p;
   20747   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
   20748 
   20749   /* moved CSE2 up */
   20750   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
   20751   b &= SLOT_2_0;
   20752   b = b<<8;
   20753   a |= b;
   20754 
   20755   s = s<<4;
   20756   b = p[-4];
   20757   b &= 0x7f;
   20758   b = b>>3;
   20759   s |= b;
   20760 
   20761   *v = ((u64)s)<<32 | a;
   20762 
   20763   return 9;
   20764 }
   20765 
   20766 /*
   20767 ** Read a 32-bit variable-length integer from memory starting at p[0].
   20768 ** Return the number of bytes read.  The value is stored in *v.
   20769 **
   20770 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
   20771 ** integer, then set *v to 0xffffffff.
   20772 **
   20773 ** A MACRO version, getVarint32, is provided which inlines the
   20774 ** single-byte case.  All code should use the MACRO version as
   20775 ** this function assumes the single-byte case has already been handled.
   20776 */
   20777 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
   20778   u32 a,b;
   20779 
   20780   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
   20781   ** by the getVarin32() macro */
   20782   a = *p;
   20783   /* a: p0 (unmasked) */
   20784 #ifndef getVarint32
   20785   if (!(a&0x80))
   20786   {
   20787     /* Values between 0 and 127 */
   20788     *v = a;
   20789     return 1;
   20790   }
   20791 #endif
   20792 
   20793   /* The 2-byte case */
   20794   p++;
   20795   b = *p;
   20796   /* b: p1 (unmasked) */
   20797   if (!(b&0x80))
   20798   {
   20799     /* Values between 128 and 16383 */
   20800     a &= 0x7f;
   20801     a = a<<7;
   20802     *v = a | b;
   20803     return 2;
   20804   }
   20805 
   20806   /* The 3-byte case */
   20807   p++;
   20808   a = a<<14;
   20809   a |= *p;
   20810   /* a: p0<<14 | p2 (unmasked) */
   20811   if (!(a&0x80))
   20812   {
   20813     /* Values between 16384 and 2097151 */
   20814     a &= (0x7f<<14)|(0x7f);
   20815     b &= 0x7f;
   20816     b = b<<7;
   20817     *v = a | b;
   20818     return 3;
   20819   }
   20820 
   20821   /* A 32-bit varint is used to store size information in btrees.
   20822   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
   20823   ** A 3-byte varint is sufficient, for example, to record the size
   20824   ** of a 1048569-byte BLOB or string.
   20825   **
   20826   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
   20827   ** rare larger cases can be handled by the slower 64-bit varint
   20828   ** routine.
   20829   */
   20830 #if 1
   20831   {
   20832     u64 v64;
   20833     u8 n;
   20834 
   20835     p -= 2;
   20836     n = sqlite3GetVarint(p, &v64);
   20837     assert( n>3 && n<=9 );
   20838     if( (v64 & SQLITE_MAX_U32)!=v64 ){
   20839       *v = 0xffffffff;
   20840     }else{
   20841       *v = (u32)v64;
   20842     }
   20843     return n;
   20844   }
   20845 
   20846 #else
   20847   /* For following code (kept for historical record only) shows an
   20848   ** unrolling for the 3- and 4-byte varint cases.  This code is
   20849   ** slightly faster, but it is also larger and much harder to test.
   20850   */
   20851   p++;
   20852   b = b<<14;
   20853   b |= *p;
   20854   /* b: p1<<14 | p3 (unmasked) */
   20855   if (!(b&0x80))
   20856   {
   20857     /* Values between 2097152 and 268435455 */
   20858     b &= (0x7f<<14)|(0x7f);
   20859     a &= (0x7f<<14)|(0x7f);
   20860     a = a<<7;
   20861     *v = a | b;
   20862     return 4;
   20863   }
   20864 
   20865   p++;
   20866   a = a<<14;
   20867   a |= *p;
   20868   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
   20869   if (!(a&0x80))
   20870   {
   20871     /* Values  between 268435456 and 34359738367 */
   20872     a &= SLOT_4_2_0;
   20873     b &= SLOT_4_2_0;
   20874     b = b<<7;
   20875     *v = a | b;
   20876     return 5;
   20877   }
   20878 
   20879   /* We can only reach this point when reading a corrupt database
   20880   ** file.  In that case we are not in any hurry.  Use the (relatively
   20881   ** slow) general-purpose sqlite3GetVarint() routine to extract the
   20882   ** value. */
   20883   {
   20884     u64 v64;
   20885     u8 n;
   20886 
   20887     p -= 4;
   20888     n = sqlite3GetVarint(p, &v64);
   20889     assert( n>5 && n<=9 );
   20890     *v = (u32)v64;
   20891     return n;
   20892   }
   20893 #endif
   20894 }
   20895 
   20896 /*
   20897 ** Return the number of bytes that will be needed to store the given
   20898 ** 64-bit integer.
   20899 */
   20900 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
   20901   int i = 0;
   20902   do{
   20903     i++;
   20904     v >>= 7;
   20905   }while( v!=0 && ALWAYS(i<9) );
   20906   return i;
   20907 }
   20908 
   20909 
   20910 /*
   20911 ** Read or write a four-byte big-endian integer value.
   20912 */
   20913 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
   20914   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
   20915 }
   20916 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
   20917   p[0] = (u8)(v>>24);
   20918   p[1] = (u8)(v>>16);
   20919   p[2] = (u8)(v>>8);
   20920   p[3] = (u8)v;
   20921 }
   20922 
   20923 
   20924 
   20925 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   20926 /*
   20927 ** Translate a single byte of Hex into an integer.
   20928 ** This routine only works if h really is a valid hexadecimal
   20929 ** character:  0..9a..fA..F
   20930 */
   20931 static u8 hexToInt(int h){
   20932   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
   20933 #ifdef SQLITE_ASCII
   20934   h += 9*(1&(h>>6));
   20935 #endif
   20936 #ifdef SQLITE_EBCDIC
   20937   h += 9*(1&~(h>>4));
   20938 #endif
   20939   return (u8)(h & 0xf);
   20940 }
   20941 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   20942 
   20943 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
   20944 /*
   20945 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
   20946 ** value.  Return a pointer to its binary value.  Space to hold the
   20947 ** binary value has been obtained from malloc and must be freed by
   20948 ** the calling routine.
   20949 */
   20950 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   20951   char *zBlob;
   20952   int i;
   20953 
   20954   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
   20955   n--;
   20956   if( zBlob ){
   20957     for(i=0; i<n; i+=2){
   20958       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
   20959     }
   20960     zBlob[i/2] = 0;
   20961   }
   20962   return zBlob;
   20963 }
   20964 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
   20965 
   20966 /*
   20967 ** Log an error that is an API call on a connection pointer that should
   20968 ** not have been used.  The "type" of connection pointer is given as the
   20969 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
   20970 */
   20971 static void logBadConnection(const char *zType){
   20972   sqlite3_log(SQLITE_MISUSE,
   20973      "API call with %s database connection pointer",
   20974      zType
   20975   );
   20976 }
   20977 
   20978 /*
   20979 ** Check to make sure we have a valid db pointer.  This test is not
   20980 ** foolproof but it does provide some measure of protection against
   20981 ** misuse of the interface such as passing in db pointers that are
   20982 ** NULL or which have been previously closed.  If this routine returns
   20983 ** 1 it means that the db pointer is valid and 0 if it should not be
   20984 ** dereferenced for any reason.  The calling function should invoke
   20985 ** SQLITE_MISUSE immediately.
   20986 **
   20987 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
   20988 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
   20989 ** open properly and is not fit for general use but which can be
   20990 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
   20991 */
   20992 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
   20993   u32 magic;
   20994   if( db==0 ){
   20995     logBadConnection("NULL");
   20996     return 0;
   20997   }
   20998   magic = db->magic;
   20999   if( magic!=SQLITE_MAGIC_OPEN ){
   21000     if( sqlite3SafetyCheckSickOrOk(db) ){
   21001       testcase( sqlite3GlobalConfig.xLog!=0 );
   21002       logBadConnection("unopened");
   21003     }
   21004     return 0;
   21005   }else{
   21006     return 1;
   21007   }
   21008 }
   21009 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
   21010   u32 magic;
   21011   magic = db->magic;
   21012   if( magic!=SQLITE_MAGIC_SICK &&
   21013       magic!=SQLITE_MAGIC_OPEN &&
   21014       magic!=SQLITE_MAGIC_BUSY ){
   21015     testcase( sqlite3GlobalConfig.xLog!=0 );
   21016     logBadConnection("invalid");
   21017     return 0;
   21018   }else{
   21019     return 1;
   21020   }
   21021 }
   21022 
   21023 /************** End of util.c ************************************************/
   21024 /************** Begin file hash.c ********************************************/
   21025 /*
   21026 ** 2001 September 22
   21027 **
   21028 ** The author disclaims copyright to this source code.  In place of
   21029 ** a legal notice, here is a blessing:
   21030 **
   21031 **    May you do good and not evil.
   21032 **    May you find forgiveness for yourself and forgive others.
   21033 **    May you share freely, never taking more than you give.
   21034 **
   21035 *************************************************************************
   21036 ** This is the implementation of generic hash-tables
   21037 ** used in SQLite.
   21038 */
   21039 
   21040 /* Turn bulk memory into a hash table object by initializing the
   21041 ** fields of the Hash structure.
   21042 **
   21043 ** "pNew" is a pointer to the hash table that is to be initialized.
   21044 */
   21045 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
   21046   assert( pNew!=0 );
   21047   pNew->first = 0;
   21048   pNew->count = 0;
   21049   pNew->htsize = 0;
   21050   pNew->ht = 0;
   21051 }
   21052 
   21053 /* Remove all entries from a hash table.  Reclaim all memory.
   21054 ** Call this routine to delete a hash table or to reset a hash table
   21055 ** to the empty state.
   21056 */
   21057 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
   21058   HashElem *elem;         /* For looping over all elements of the table */
   21059 
   21060   assert( pH!=0 );
   21061   elem = pH->first;
   21062   pH->first = 0;
   21063   sqlite3_free(pH->ht);
   21064   pH->ht = 0;
   21065   pH->htsize = 0;
   21066   while( elem ){
   21067     HashElem *next_elem = elem->next;
   21068     sqlite3_free(elem);
   21069     elem = next_elem;
   21070   }
   21071   pH->count = 0;
   21072 }
   21073 
   21074 /*
   21075 ** The hashing function.
   21076 */
   21077 static unsigned int strHash(const char *z, int nKey){
   21078   int h = 0;
   21079   assert( nKey>=0 );
   21080   while( nKey > 0  ){
   21081     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
   21082     nKey--;
   21083   }
   21084   return h;
   21085 }
   21086 
   21087 
   21088 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
   21089 ** insert pNew into the pEntry hash bucket.
   21090 */
   21091 static void insertElement(
   21092   Hash *pH,              /* The complete hash table */
   21093   struct _ht *pEntry,    /* The entry into which pNew is inserted */
   21094   HashElem *pNew         /* The element to be inserted */
   21095 ){
   21096   HashElem *pHead;       /* First element already in pEntry */
   21097   if( pEntry ){
   21098     pHead = pEntry->count ? pEntry->chain : 0;
   21099     pEntry->count++;
   21100     pEntry->chain = pNew;
   21101   }else{
   21102     pHead = 0;
   21103   }
   21104   if( pHead ){
   21105     pNew->next = pHead;
   21106     pNew->prev = pHead->prev;
   21107     if( pHead->prev ){ pHead->prev->next = pNew; }
   21108     else             { pH->first = pNew; }
   21109     pHead->prev = pNew;
   21110   }else{
   21111     pNew->next = pH->first;
   21112     if( pH->first ){ pH->first->prev = pNew; }
   21113     pNew->prev = 0;
   21114     pH->first = pNew;
   21115   }
   21116 }
   21117 
   21118 
   21119 /* Resize the hash table so that it cantains "new_size" buckets.
   21120 **
   21121 ** The hash table might fail to resize if sqlite3_malloc() fails or
   21122 ** if the new size is the same as the prior size.
   21123 ** Return TRUE if the resize occurs and false if not.
   21124 */
   21125 static int rehash(Hash *pH, unsigned int new_size){
   21126   struct _ht *new_ht;            /* The new hash table */
   21127   HashElem *elem, *next_elem;    /* For looping over existing elements */
   21128 
   21129 #if SQLITE_MALLOC_SOFT_LIMIT>0
   21130   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
   21131     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
   21132   }
   21133   if( new_size==pH->htsize ) return 0;
   21134 #endif
   21135 
   21136   /* The inability to allocates space for a larger hash table is
   21137   ** a performance hit but it is not a fatal error.  So mark the
   21138   ** allocation as a benign.
   21139   */
   21140   sqlite3BeginBenignMalloc();
   21141   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
   21142   sqlite3EndBenignMalloc();
   21143 
   21144   if( new_ht==0 ) return 0;
   21145   sqlite3_free(pH->ht);
   21146   pH->ht = new_ht;
   21147   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
   21148   memset(new_ht, 0, new_size*sizeof(struct _ht));
   21149   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   21150     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
   21151     next_elem = elem->next;
   21152     insertElement(pH, &new_ht[h], elem);
   21153   }
   21154   return 1;
   21155 }
   21156 
   21157 /* This function (for internal use only) locates an element in an
   21158 ** hash table that matches the given key.  The hash for this key has
   21159 ** already been computed and is passed as the 4th parameter.
   21160 */
   21161 static HashElem *findElementGivenHash(
   21162   const Hash *pH,     /* The pH to be searched */
   21163   const char *pKey,   /* The key we are searching for */
   21164   int nKey,           /* Bytes in key (not counting zero terminator) */
   21165   unsigned int h      /* The hash for this key. */
   21166 ){
   21167   HashElem *elem;                /* Used to loop thru the element list */
   21168   int count;                     /* Number of elements left to test */
   21169 
   21170   if( pH->ht ){
   21171     struct _ht *pEntry = &pH->ht[h];
   21172     elem = pEntry->chain;
   21173     count = pEntry->count;
   21174   }else{
   21175     elem = pH->first;
   21176     count = pH->count;
   21177   }
   21178   while( count-- && ALWAYS(elem) ){
   21179     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
   21180       return elem;
   21181     }
   21182     elem = elem->next;
   21183   }
   21184   return 0;
   21185 }
   21186 
   21187 /* Remove a single entry from the hash table given a pointer to that
   21188 ** element and a hash on the element's key.
   21189 */
   21190 static void removeElementGivenHash(
   21191   Hash *pH,         /* The pH containing "elem" */
   21192   HashElem* elem,   /* The element to be removed from the pH */
   21193   unsigned int h    /* Hash value for the element */
   21194 ){
   21195   struct _ht *pEntry;
   21196   if( elem->prev ){
   21197     elem->prev->next = elem->next;
   21198   }else{
   21199     pH->first = elem->next;
   21200   }
   21201   if( elem->next ){
   21202     elem->next->prev = elem->prev;
   21203   }
   21204   if( pH->ht ){
   21205     pEntry = &pH->ht[h];
   21206     if( pEntry->chain==elem ){
   21207       pEntry->chain = elem->next;
   21208     }
   21209     pEntry->count--;
   21210     assert( pEntry->count>=0 );
   21211   }
   21212   sqlite3_free( elem );
   21213   pH->count--;
   21214   if( pH->count<=0 ){
   21215     assert( pH->first==0 );
   21216     assert( pH->count==0 );
   21217     sqlite3HashClear(pH);
   21218   }
   21219 }
   21220 
   21221 /* Attempt to locate an element of the hash table pH with a key
   21222 ** that matches pKey,nKey.  Return the data for this element if it is
   21223 ** found, or NULL if there is no match.
   21224 */
   21225 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
   21226   HashElem *elem;    /* The element that matches key */
   21227   unsigned int h;    /* A hash on key */
   21228 
   21229   assert( pH!=0 );
   21230   assert( pKey!=0 );
   21231   assert( nKey>=0 );
   21232   if( pH->ht ){
   21233     h = strHash(pKey, nKey) % pH->htsize;
   21234   }else{
   21235     h = 0;
   21236   }
   21237   elem = findElementGivenHash(pH, pKey, nKey, h);
   21238   return elem ? elem->data : 0;
   21239 }
   21240 
   21241 /* Insert an element into the hash table pH.  The key is pKey,nKey
   21242 ** and the data is "data".
   21243 **
   21244 ** If no element exists with a matching key, then a new
   21245 ** element is created and NULL is returned.
   21246 **
   21247 ** If another element already exists with the same key, then the
   21248 ** new data replaces the old data and the old data is returned.
   21249 ** The key is not copied in this instance.  If a malloc fails, then
   21250 ** the new data is returned and the hash table is unchanged.
   21251 **
   21252 ** If the "data" parameter to this function is NULL, then the
   21253 ** element corresponding to "key" is removed from the hash table.
   21254 */
   21255 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
   21256   unsigned int h;       /* the hash of the key modulo hash table size */
   21257   HashElem *elem;       /* Used to loop thru the element list */
   21258   HashElem *new_elem;   /* New element added to the pH */
   21259 
   21260   assert( pH!=0 );
   21261   assert( pKey!=0 );
   21262   assert( nKey>=0 );
   21263   if( pH->htsize ){
   21264     h = strHash(pKey, nKey) % pH->htsize;
   21265   }else{
   21266     h = 0;
   21267   }
   21268   elem = findElementGivenHash(pH,pKey,nKey,h);
   21269   if( elem ){
   21270     void *old_data = elem->data;
   21271     if( data==0 ){
   21272       removeElementGivenHash(pH,elem,h);
   21273     }else{
   21274       elem->data = data;
   21275       elem->pKey = pKey;
   21276       assert(nKey==elem->nKey);
   21277     }
   21278     return old_data;
   21279   }
   21280   if( data==0 ) return 0;
   21281   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
   21282   if( new_elem==0 ) return data;
   21283   new_elem->pKey = pKey;
   21284   new_elem->nKey = nKey;
   21285   new_elem->data = data;
   21286   pH->count++;
   21287   if( pH->count>=10 && pH->count > 2*pH->htsize ){
   21288     if( rehash(pH, pH->count*2) ){
   21289       assert( pH->htsize>0 );
   21290       h = strHash(pKey, nKey) % pH->htsize;
   21291     }
   21292   }
   21293   if( pH->ht ){
   21294     insertElement(pH, &pH->ht[h], new_elem);
   21295   }else{
   21296     insertElement(pH, 0, new_elem);
   21297   }
   21298   return 0;
   21299 }
   21300 
   21301 /************** End of hash.c ************************************************/
   21302 /************** Begin file opcodes.c *****************************************/
   21303 /* Automatically generated.  Do not edit */
   21304 /* See the mkopcodec.awk script for details. */
   21305 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   21306 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
   21307  static const char *const azName[] = { "?",
   21308      /*   1 */ "Goto",
   21309      /*   2 */ "Gosub",
   21310      /*   3 */ "Return",
   21311      /*   4 */ "Yield",
   21312      /*   5 */ "HaltIfNull",
   21313      /*   6 */ "Halt",
   21314      /*   7 */ "Integer",
   21315      /*   8 */ "Int64",
   21316      /*   9 */ "String",
   21317      /*  10 */ "Null",
   21318      /*  11 */ "Blob",
   21319      /*  12 */ "Variable",
   21320      /*  13 */ "Move",
   21321      /*  14 */ "Copy",
   21322      /*  15 */ "SCopy",
   21323      /*  16 */ "ResultRow",
   21324      /*  17 */ "CollSeq",
   21325      /*  18 */ "Function",
   21326      /*  19 */ "Not",
   21327      /*  20 */ "AddImm",
   21328      /*  21 */ "MustBeInt",
   21329      /*  22 */ "RealAffinity",
   21330      /*  23 */ "Permutation",
   21331      /*  24 */ "Compare",
   21332      /*  25 */ "Jump",
   21333      /*  26 */ "If",
   21334      /*  27 */ "IfNot",
   21335      /*  28 */ "Column",
   21336      /*  29 */ "Affinity",
   21337      /*  30 */ "MakeRecord",
   21338      /*  31 */ "Count",
   21339      /*  32 */ "Savepoint",
   21340      /*  33 */ "AutoCommit",
   21341      /*  34 */ "Transaction",
   21342      /*  35 */ "ReadCookie",
   21343      /*  36 */ "SetCookie",
   21344      /*  37 */ "VerifyCookie",
   21345      /*  38 */ "OpenRead",
   21346      /*  39 */ "OpenWrite",
   21347      /*  40 */ "OpenAutoindex",
   21348      /*  41 */ "OpenEphemeral",
   21349      /*  42 */ "OpenPseudo",
   21350      /*  43 */ "Close",
   21351      /*  44 */ "SeekLt",
   21352      /*  45 */ "SeekLe",
   21353      /*  46 */ "SeekGe",
   21354      /*  47 */ "SeekGt",
   21355      /*  48 */ "Seek",
   21356      /*  49 */ "NotFound",
   21357      /*  50 */ "Found",
   21358      /*  51 */ "IsUnique",
   21359      /*  52 */ "NotExists",
   21360      /*  53 */ "Sequence",
   21361      /*  54 */ "NewRowid",
   21362      /*  55 */ "Insert",
   21363      /*  56 */ "InsertInt",
   21364      /*  57 */ "Delete",
   21365      /*  58 */ "ResetCount",
   21366      /*  59 */ "RowKey",
   21367      /*  60 */ "RowData",
   21368      /*  61 */ "Rowid",
   21369      /*  62 */ "NullRow",
   21370      /*  63 */ "Last",
   21371      /*  64 */ "Sort",
   21372      /*  65 */ "Rewind",
   21373      /*  66 */ "Prev",
   21374      /*  67 */ "Next",
   21375      /*  68 */ "Or",
   21376      /*  69 */ "And",
   21377      /*  70 */ "IdxInsert",
   21378      /*  71 */ "IdxDelete",
   21379      /*  72 */ "IdxRowid",
   21380      /*  73 */ "IsNull",
   21381      /*  74 */ "NotNull",
   21382      /*  75 */ "Ne",
   21383      /*  76 */ "Eq",
   21384      /*  77 */ "Gt",
   21385      /*  78 */ "Le",
   21386      /*  79 */ "Lt",
   21387      /*  80 */ "Ge",
   21388      /*  81 */ "IdxLT",
   21389      /*  82 */ "BitAnd",
   21390      /*  83 */ "BitOr",
   21391      /*  84 */ "ShiftLeft",
   21392      /*  85 */ "ShiftRight",
   21393      /*  86 */ "Add",
   21394      /*  87 */ "Subtract",
   21395      /*  88 */ "Multiply",
   21396      /*  89 */ "Divide",
   21397      /*  90 */ "Remainder",
   21398      /*  91 */ "Concat",
   21399      /*  92 */ "IdxGE",
   21400      /*  93 */ "BitNot",
   21401      /*  94 */ "String8",
   21402      /*  95 */ "Destroy",
   21403      /*  96 */ "Clear",
   21404      /*  97 */ "CreateIndex",
   21405      /*  98 */ "CreateTable",
   21406      /*  99 */ "ParseSchema",
   21407      /* 100 */ "LoadAnalysis",
   21408      /* 101 */ "DropTable",
   21409      /* 102 */ "DropIndex",
   21410      /* 103 */ "DropTrigger",
   21411      /* 104 */ "IntegrityCk",
   21412      /* 105 */ "RowSetAdd",
   21413      /* 106 */ "RowSetRead",
   21414      /* 107 */ "RowSetTest",
   21415      /* 108 */ "Program",
   21416      /* 109 */ "Param",
   21417      /* 110 */ "FkCounter",
   21418      /* 111 */ "FkIfZero",
   21419      /* 112 */ "MemMax",
   21420      /* 113 */ "IfPos",
   21421      /* 114 */ "IfNeg",
   21422      /* 115 */ "IfZero",
   21423      /* 116 */ "AggStep",
   21424      /* 117 */ "AggFinal",
   21425      /* 118 */ "Checkpoint",
   21426      /* 119 */ "JournalMode",
   21427      /* 120 */ "Vacuum",
   21428      /* 121 */ "IncrVacuum",
   21429      /* 122 */ "Expire",
   21430      /* 123 */ "TableLock",
   21431      /* 124 */ "VBegin",
   21432      /* 125 */ "VCreate",
   21433      /* 126 */ "VDestroy",
   21434      /* 127 */ "VOpen",
   21435      /* 128 */ "VFilter",
   21436      /* 129 */ "VColumn",
   21437      /* 130 */ "Real",
   21438      /* 131 */ "VNext",
   21439      /* 132 */ "VRename",
   21440      /* 133 */ "VUpdate",
   21441      /* 134 */ "Pagecount",
   21442      /* 135 */ "MaxPgcnt",
   21443      /* 136 */ "Trace",
   21444      /* 137 */ "Noop",
   21445      /* 138 */ "Explain",
   21446      /* 139 */ "NotUsed_139",
   21447      /* 140 */ "NotUsed_140",
   21448      /* 141 */ "ToText",
   21449      /* 142 */ "ToBlob",
   21450      /* 143 */ "ToNumeric",
   21451      /* 144 */ "ToInt",
   21452      /* 145 */ "ToReal",
   21453   };
   21454   return azName[i];
   21455 }
   21456 #endif
   21457 
   21458 /************** End of opcodes.c *********************************************/
   21459 /************** Begin file os_os2.c ******************************************/
   21460 /*
   21461 ** 2006 Feb 14
   21462 **
   21463 ** The author disclaims copyright to this source code.  In place of
   21464 ** a legal notice, here is a blessing:
   21465 **
   21466 **    May you do good and not evil.
   21467 **    May you find forgiveness for yourself and forgive others.
   21468 **    May you share freely, never taking more than you give.
   21469 **
   21470 ******************************************************************************
   21471 **
   21472 ** This file contains code that is specific to OS/2.
   21473 */
   21474 
   21475 
   21476 #if SQLITE_OS_OS2
   21477 
   21478 /*
   21479 ** A Note About Memory Allocation:
   21480 **
   21481 ** This driver uses malloc()/free() directly rather than going through
   21482 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
   21483 ** are designed for use on embedded systems where memory is scarce and
   21484 ** malloc failures happen frequently.  OS/2 does not typically run on
   21485 ** embedded systems, and when it does the developers normally have bigger
   21486 ** problems to worry about than running out of memory.  So there is not
   21487 ** a compelling need to use the wrappers.
   21488 **
   21489 ** But there is a good reason to not use the wrappers.  If we use the
   21490 ** wrappers then we will get simulated malloc() failures within this
   21491 ** driver.  And that causes all kinds of problems for our tests.  We
   21492 ** could enhance SQLite to deal with simulated malloc failures within
   21493 ** the OS driver, but the code to deal with those failure would not
   21494 ** be exercised on Linux (which does not need to malloc() in the driver)
   21495 ** and so we would have difficulty writing coverage tests for that
   21496 ** code.  Better to leave the code out, we think.
   21497 **
   21498 ** The point of this discussion is as follows:  When creating a new
   21499 ** OS layer for an embedded system, if you use this file as an example,
   21500 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
   21501 ** desktops but not so well in embedded systems.
   21502 */
   21503 
   21504 /*
   21505 ** Macros used to determine whether or not to use threads.
   21506 */
   21507 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
   21508 # define SQLITE_OS2_THREADS 1
   21509 #endif
   21510 
   21511 /*
   21512 ** Include code that is common to all os_*.c files
   21513 */
   21514 /************** Include os_common.h in the middle of os_os2.c ****************/
   21515 /************** Begin file os_common.h ***************************************/
   21516 /*
   21517 ** 2004 May 22
   21518 **
   21519 ** The author disclaims copyright to this source code.  In place of
   21520 ** a legal notice, here is a blessing:
   21521 **
   21522 **    May you do good and not evil.
   21523 **    May you find forgiveness for yourself and forgive others.
   21524 **    May you share freely, never taking more than you give.
   21525 **
   21526 ******************************************************************************
   21527 **
   21528 ** This file contains macros and a little bit of code that is common to
   21529 ** all of the platform-specific files (os_*.c) and is #included into those
   21530 ** files.
   21531 **
   21532 ** This file should be #included by the os_*.c files only.  It is not a
   21533 ** general purpose header file.
   21534 */
   21535 #ifndef _OS_COMMON_H_
   21536 #define _OS_COMMON_H_
   21537 
   21538 /*
   21539 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   21540 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   21541 ** switch.  The following code should catch this problem at compile-time.
   21542 */
   21543 #ifdef MEMORY_DEBUG
   21544 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   21545 #endif
   21546 
   21547 #ifdef SQLITE_DEBUG
   21548 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   21549 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   21550 #else
   21551 #define OSTRACE(X)
   21552 #endif
   21553 
   21554 /*
   21555 ** Macros for performance tracing.  Normally turned off.  Only works
   21556 ** on i486 hardware.
   21557 */
   21558 #ifdef SQLITE_PERFORMANCE_TRACE
   21559 
   21560 /*
   21561 ** hwtime.h contains inline assembler code for implementing
   21562 ** high-performance timing routines.
   21563 */
   21564 /************** Include hwtime.h in the middle of os_common.h ****************/
   21565 /************** Begin file hwtime.h ******************************************/
   21566 /*
   21567 ** 2008 May 27
   21568 **
   21569 ** The author disclaims copyright to this source code.  In place of
   21570 ** a legal notice, here is a blessing:
   21571 **
   21572 **    May you do good and not evil.
   21573 **    May you find forgiveness for yourself and forgive others.
   21574 **    May you share freely, never taking more than you give.
   21575 **
   21576 ******************************************************************************
   21577 **
   21578 ** This file contains inline asm code for retrieving "high-performance"
   21579 ** counters for x86 class CPUs.
   21580 */
   21581 #ifndef _HWTIME_H_
   21582 #define _HWTIME_H_
   21583 
   21584 /*
   21585 ** The following routine only works on pentium-class (or newer) processors.
   21586 ** It uses the RDTSC opcode to read the cycle count value out of the
   21587 ** processor and returns that value.  This can be used for high-res
   21588 ** profiling.
   21589 */
   21590 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   21591       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   21592 
   21593   #if defined(__GNUC__)
   21594 
   21595   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21596      unsigned int lo, hi;
   21597      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   21598      return (sqlite_uint64)hi << 32 | lo;
   21599   }
   21600 
   21601   #elif defined(_MSC_VER)
   21602 
   21603   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   21604      __asm {
   21605         rdtsc
   21606         ret       ; return value at EDX:EAX
   21607      }
   21608   }
   21609 
   21610   #endif
   21611 
   21612 #elif (defined(__GNUC__) && defined(__x86_64__))
   21613 
   21614   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21615       unsigned long val;
   21616       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   21617       return val;
   21618   }
   21619 
   21620 #elif (defined(__GNUC__) && defined(__ppc__))
   21621 
   21622   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   21623       unsigned long long retval;
   21624       unsigned long junk;
   21625       __asm__ __volatile__ ("\n\
   21626           1:      mftbu   %1\n\
   21627                   mftb    %L0\n\
   21628                   mftbu   %0\n\
   21629                   cmpw    %0,%1\n\
   21630                   bne     1b"
   21631                   : "=r" (retval), "=r" (junk));
   21632       return retval;
   21633   }
   21634 
   21635 #else
   21636 
   21637   #error Need implementation of sqlite3Hwtime() for your platform.
   21638 
   21639   /*
   21640   ** To compile without implementing sqlite3Hwtime() for your platform,
   21641   ** you can remove the above #error and use the following
   21642   ** stub function.  You will lose timing support for many
   21643   ** of the debugging and testing utilities, but it should at
   21644   ** least compile and run.
   21645   */
   21646 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   21647 
   21648 #endif
   21649 
   21650 #endif /* !defined(_HWTIME_H_) */
   21651 
   21652 /************** End of hwtime.h **********************************************/
   21653 /************** Continuing where we left off in os_common.h ******************/
   21654 
   21655 static sqlite_uint64 g_start;
   21656 static sqlite_uint64 g_elapsed;
   21657 #define TIMER_START       g_start=sqlite3Hwtime()
   21658 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   21659 #define TIMER_ELAPSED     g_elapsed
   21660 #else
   21661 #define TIMER_START
   21662 #define TIMER_END
   21663 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   21664 #endif
   21665 
   21666 /*
   21667 ** If we compile with the SQLITE_TEST macro set, then the following block
   21668 ** of code will give us the ability to simulate a disk I/O error.  This
   21669 ** is used for testing the I/O recovery logic.
   21670 */
   21671 #ifdef SQLITE_TEST
   21672 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   21673 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   21674 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   21675 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   21676 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   21677 SQLITE_API int sqlite3_diskfull_pending = 0;
   21678 SQLITE_API int sqlite3_diskfull = 0;
   21679 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   21680 #define SimulateIOError(CODE)  \
   21681   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   21682        || sqlite3_io_error_pending-- == 1 )  \
   21683               { local_ioerr(); CODE; }
   21684 static void local_ioerr(){
   21685   IOTRACE(("IOERR\n"));
   21686   sqlite3_io_error_hit++;
   21687   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   21688 }
   21689 #define SimulateDiskfullError(CODE) \
   21690    if( sqlite3_diskfull_pending ){ \
   21691      if( sqlite3_diskfull_pending == 1 ){ \
   21692        local_ioerr(); \
   21693        sqlite3_diskfull = 1; \
   21694        sqlite3_io_error_hit = 1; \
   21695        CODE; \
   21696      }else{ \
   21697        sqlite3_diskfull_pending--; \
   21698      } \
   21699    }
   21700 #else
   21701 #define SimulateIOErrorBenign(X)
   21702 #define SimulateIOError(A)
   21703 #define SimulateDiskfullError(A)
   21704 #endif
   21705 
   21706 /*
   21707 ** When testing, keep a count of the number of open files.
   21708 */
   21709 #ifdef SQLITE_TEST
   21710 SQLITE_API int sqlite3_open_file_count = 0;
   21711 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   21712 #else
   21713 #define OpenCounter(X)
   21714 #endif
   21715 
   21716 #endif /* !defined(_OS_COMMON_H_) */
   21717 
   21718 /************** End of os_common.h *******************************************/
   21719 /************** Continuing where we left off in os_os2.c *********************/
   21720 
   21721 /*
   21722 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
   21723 ** protability layer.
   21724 */
   21725 typedef struct os2File os2File;
   21726 struct os2File {
   21727   const sqlite3_io_methods *pMethod;  /* Always the first entry */
   21728   HFILE h;                  /* Handle for accessing the file */
   21729   char* pathToDel;          /* Name of file to delete on close, NULL if not */
   21730   unsigned char locktype;   /* Type of lock currently held on this file */
   21731 };
   21732 
   21733 #define LOCK_TIMEOUT 10L /* the default locking timeout */
   21734 
   21735 /*****************************************************************************
   21736 ** The next group of routines implement the I/O methods specified
   21737 ** by the sqlite3_io_methods object.
   21738 ******************************************************************************/
   21739 
   21740 /*
   21741 ** Close a file.
   21742 */
   21743 static int os2Close( sqlite3_file *id ){
   21744   APIRET rc = NO_ERROR;
   21745   os2File *pFile;
   21746   if( id && (pFile = (os2File*)id) != 0 ){
   21747     OSTRACE(( "CLOSE %d\n", pFile->h ));
   21748     rc = DosClose( pFile->h );
   21749     pFile->locktype = NO_LOCK;
   21750     if( pFile->pathToDel != NULL ){
   21751       rc = DosForceDelete( (PSZ)pFile->pathToDel );
   21752       free( pFile->pathToDel );
   21753       pFile->pathToDel = NULL;
   21754     }
   21755     id = 0;
   21756     OpenCounter( -1 );
   21757   }
   21758 
   21759   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   21760 }
   21761 
   21762 /*
   21763 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   21764 ** bytes were read successfully and SQLITE_IOERR if anything goes
   21765 ** wrong.
   21766 */
   21767 static int os2Read(
   21768   sqlite3_file *id,               /* File to read from */
   21769   void *pBuf,                     /* Write content into this buffer */
   21770   int amt,                        /* Number of bytes to read */
   21771   sqlite3_int64 offset            /* Begin reading at this offset */
   21772 ){
   21773   ULONG fileLocation = 0L;
   21774   ULONG got;
   21775   os2File *pFile = (os2File*)id;
   21776   assert( id!=0 );
   21777   SimulateIOError( return SQLITE_IOERR_READ );
   21778   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
   21779   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   21780     return SQLITE_IOERR;
   21781   }
   21782   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
   21783     return SQLITE_IOERR_READ;
   21784   }
   21785   if( got == (ULONG)amt )
   21786     return SQLITE_OK;
   21787   else {
   21788     /* Unread portions of the input buffer must be zero-filled */
   21789     memset(&((char*)pBuf)[got], 0, amt-got);
   21790     return SQLITE_IOERR_SHORT_READ;
   21791   }
   21792 }
   21793 
   21794 /*
   21795 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   21796 ** or some other error code on failure.
   21797 */
   21798 static int os2Write(
   21799   sqlite3_file *id,               /* File to write into */
   21800   const void *pBuf,               /* The bytes to be written */
   21801   int amt,                        /* Number of bytes to write */
   21802   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   21803 ){
   21804   ULONG fileLocation = 0L;
   21805   APIRET rc = NO_ERROR;
   21806   ULONG wrote;
   21807   os2File *pFile = (os2File*)id;
   21808   assert( id!=0 );
   21809   SimulateIOError( return SQLITE_IOERR_WRITE );
   21810   SimulateDiskfullError( return SQLITE_FULL );
   21811   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
   21812   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
   21813     return SQLITE_IOERR;
   21814   }
   21815   assert( amt>0 );
   21816   while( amt > 0 &&
   21817          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
   21818          wrote > 0
   21819   ){
   21820     amt -= wrote;
   21821     pBuf = &((char*)pBuf)[wrote];
   21822   }
   21823 
   21824   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
   21825 }
   21826 
   21827 /*
   21828 ** Truncate an open file to a specified size
   21829 */
   21830 static int os2Truncate( sqlite3_file *id, i64 nByte ){
   21831   APIRET rc = NO_ERROR;
   21832   os2File *pFile = (os2File*)id;
   21833   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
   21834   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   21835   rc = DosSetFileSize( pFile->h, nByte );
   21836   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
   21837 }
   21838 
   21839 #ifdef SQLITE_TEST
   21840 /*
   21841 ** Count the number of fullsyncs and normal syncs.  This is used to test
   21842 ** that syncs and fullsyncs are occuring at the right times.
   21843 */
   21844 SQLITE_API int sqlite3_sync_count = 0;
   21845 SQLITE_API int sqlite3_fullsync_count = 0;
   21846 #endif
   21847 
   21848 /*
   21849 ** Make sure all writes to a particular file are committed to disk.
   21850 */
   21851 static int os2Sync( sqlite3_file *id, int flags ){
   21852   os2File *pFile = (os2File*)id;
   21853   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
   21854 #ifdef SQLITE_TEST
   21855   if( flags & SQLITE_SYNC_FULL){
   21856     sqlite3_fullsync_count++;
   21857   }
   21858   sqlite3_sync_count++;
   21859 #endif
   21860   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   21861   ** no-op
   21862   */
   21863 #ifdef SQLITE_NO_SYNC
   21864   UNUSED_PARAMETER(pFile);
   21865   return SQLITE_OK;
   21866 #else
   21867   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   21868 #endif
   21869 }
   21870 
   21871 /*
   21872 ** Determine the current size of a file in bytes
   21873 */
   21874 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
   21875   APIRET rc = NO_ERROR;
   21876   FILESTATUS3 fsts3FileInfo;
   21877   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
   21878   assert( id!=0 );
   21879   SimulateIOError( return SQLITE_IOERR_FSTAT );
   21880   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
   21881   if( rc == NO_ERROR ){
   21882     *pSize = fsts3FileInfo.cbFile;
   21883     return SQLITE_OK;
   21884   }else{
   21885     return SQLITE_IOERR_FSTAT;
   21886   }
   21887 }
   21888 
   21889 /*
   21890 ** Acquire a reader lock.
   21891 */
   21892 static int getReadLock( os2File *pFile ){
   21893   FILELOCK  LockArea,
   21894             UnlockArea;
   21895   APIRET res;
   21896   memset(&LockArea, 0, sizeof(LockArea));
   21897   memset(&UnlockArea, 0, sizeof(UnlockArea));
   21898   LockArea.lOffset = SHARED_FIRST;
   21899   LockArea.lRange = SHARED_SIZE;
   21900   UnlockArea.lOffset = 0L;
   21901   UnlockArea.lRange = 0L;
   21902   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   21903   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
   21904   return res;
   21905 }
   21906 
   21907 /*
   21908 ** Undo a readlock
   21909 */
   21910 static int unlockReadLock( os2File *id ){
   21911   FILELOCK  LockArea,
   21912             UnlockArea;
   21913   APIRET res;
   21914   memset(&LockArea, 0, sizeof(LockArea));
   21915   memset(&UnlockArea, 0, sizeof(UnlockArea));
   21916   LockArea.lOffset = 0L;
   21917   LockArea.lRange = 0L;
   21918   UnlockArea.lOffset = SHARED_FIRST;
   21919   UnlockArea.lRange = SHARED_SIZE;
   21920   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
   21921   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
   21922   return res;
   21923 }
   21924 
   21925 /*
   21926 ** Lock the file with the lock specified by parameter locktype - one
   21927 ** of the following:
   21928 **
   21929 **     (1) SHARED_LOCK
   21930 **     (2) RESERVED_LOCK
   21931 **     (3) PENDING_LOCK
   21932 **     (4) EXCLUSIVE_LOCK
   21933 **
   21934 ** Sometimes when requesting one lock state, additional lock states
   21935 ** are inserted in between.  The locking might fail on one of the later
   21936 ** transitions leaving the lock state different from what it started but
   21937 ** still short of its goal.  The following chart shows the allowed
   21938 ** transitions and the inserted intermediate states:
   21939 **
   21940 **    UNLOCKED -> SHARED
   21941 **    SHARED -> RESERVED
   21942 **    SHARED -> (PENDING) -> EXCLUSIVE
   21943 **    RESERVED -> (PENDING) -> EXCLUSIVE
   21944 **    PENDING -> EXCLUSIVE
   21945 **
   21946 ** This routine will only increase a lock.  The os2Unlock() routine
   21947 ** erases all locks at once and returns us immediately to locking level 0.
   21948 ** It is not possible to lower the locking level one step at a time.  You
   21949 ** must go straight to locking level 0.
   21950 */
   21951 static int os2Lock( sqlite3_file *id, int locktype ){
   21952   int rc = SQLITE_OK;       /* Return code from subroutines */
   21953   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
   21954   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   21955   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   21956   FILELOCK  LockArea,
   21957             UnlockArea;
   21958   os2File *pFile = (os2File*)id;
   21959   memset(&LockArea, 0, sizeof(LockArea));
   21960   memset(&UnlockArea, 0, sizeof(UnlockArea));
   21961   assert( pFile!=0 );
   21962   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
   21963 
   21964   /* If there is already a lock of this type or more restrictive on the
   21965   ** os2File, do nothing. Don't use the end_lock: exit path, as
   21966   ** sqlite3_mutex_enter() hasn't been called yet.
   21967   */
   21968   if( pFile->locktype>=locktype ){
   21969     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
   21970     return SQLITE_OK;
   21971   }
   21972 
   21973   /* Make sure the locking sequence is correct
   21974   */
   21975   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   21976   assert( locktype!=PENDING_LOCK );
   21977   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   21978 
   21979   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   21980   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   21981   ** the PENDING_LOCK byte is temporary.
   21982   */
   21983   newLocktype = pFile->locktype;
   21984   if( pFile->locktype==NO_LOCK
   21985       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
   21986   ){
   21987     LockArea.lOffset = PENDING_BYTE;
   21988     LockArea.lRange = 1L;
   21989     UnlockArea.lOffset = 0L;
   21990     UnlockArea.lRange = 0L;
   21991 
   21992     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
   21993     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
   21994     if( res == NO_ERROR ){
   21995       gotPendingLock = 1;
   21996       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
   21997     }
   21998   }
   21999 
   22000   /* Acquire a shared lock
   22001   */
   22002   if( locktype==SHARED_LOCK && res == NO_ERROR ){
   22003     assert( pFile->locktype==NO_LOCK );
   22004     res = getReadLock(pFile);
   22005     if( res == NO_ERROR ){
   22006       newLocktype = SHARED_LOCK;
   22007     }
   22008     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
   22009   }
   22010 
   22011   /* Acquire a RESERVED lock
   22012   */
   22013   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
   22014     assert( pFile->locktype==SHARED_LOCK );
   22015     LockArea.lOffset = RESERVED_BYTE;
   22016     LockArea.lRange = 1L;
   22017     UnlockArea.lOffset = 0L;
   22018     UnlockArea.lRange = 0L;
   22019     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22020     if( res == NO_ERROR ){
   22021       newLocktype = RESERVED_LOCK;
   22022     }
   22023     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
   22024   }
   22025 
   22026   /* Acquire a PENDING lock
   22027   */
   22028   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   22029     newLocktype = PENDING_LOCK;
   22030     gotPendingLock = 0;
   22031     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
   22032                pFile->h ));
   22033   }
   22034 
   22035   /* Acquire an EXCLUSIVE lock
   22036   */
   22037   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
   22038     assert( pFile->locktype>=SHARED_LOCK );
   22039     res = unlockReadLock(pFile);
   22040     OSTRACE(( "unreadlock = %d\n", res ));
   22041     LockArea.lOffset = SHARED_FIRST;
   22042     LockArea.lRange = SHARED_SIZE;
   22043     UnlockArea.lOffset = 0L;
   22044     UnlockArea.lRange = 0L;
   22045     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22046     if( res == NO_ERROR ){
   22047       newLocktype = EXCLUSIVE_LOCK;
   22048     }else{
   22049       OSTRACE(( "OS/2 error-code = %d\n", res ));
   22050       getReadLock(pFile);
   22051     }
   22052     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
   22053   }
   22054 
   22055   /* If we are holding a PENDING lock that ought to be released, then
   22056   ** release it now.
   22057   */
   22058   if( gotPendingLock && locktype==SHARED_LOCK ){
   22059     int r;
   22060     LockArea.lOffset = 0L;
   22061     LockArea.lRange = 0L;
   22062     UnlockArea.lOffset = PENDING_BYTE;
   22063     UnlockArea.lRange = 1L;
   22064     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22065     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
   22066   }
   22067 
   22068   /* Update the state of the lock has held in the file descriptor then
   22069   ** return the appropriate result code.
   22070   */
   22071   if( res == NO_ERROR ){
   22072     rc = SQLITE_OK;
   22073   }else{
   22074     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   22075               locktype, newLocktype ));
   22076     rc = SQLITE_BUSY;
   22077   }
   22078   pFile->locktype = newLocktype;
   22079   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
   22080   return rc;
   22081 }
   22082 
   22083 /*
   22084 ** This routine checks if there is a RESERVED lock held on the specified
   22085 ** file by this or any other process. If such a lock is held, return
   22086 ** non-zero, otherwise zero.
   22087 */
   22088 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
   22089   int r = 0;
   22090   os2File *pFile = (os2File*)id;
   22091   assert( pFile!=0 );
   22092   if( pFile->locktype>=RESERVED_LOCK ){
   22093     r = 1;
   22094     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
   22095   }else{
   22096     FILELOCK  LockArea,
   22097               UnlockArea;
   22098     APIRET rc = NO_ERROR;
   22099     memset(&LockArea, 0, sizeof(LockArea));
   22100     memset(&UnlockArea, 0, sizeof(UnlockArea));
   22101     LockArea.lOffset = RESERVED_BYTE;
   22102     LockArea.lRange = 1L;
   22103     UnlockArea.lOffset = 0L;
   22104     UnlockArea.lRange = 0L;
   22105     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22106     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
   22107     if( rc == NO_ERROR ){
   22108       APIRET rcu = NO_ERROR; /* return code for unlocking */
   22109       LockArea.lOffset = 0L;
   22110       LockArea.lRange = 0L;
   22111       UnlockArea.lOffset = RESERVED_BYTE;
   22112       UnlockArea.lRange = 1L;
   22113       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22114       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
   22115     }
   22116     r = !(rc == NO_ERROR);
   22117     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
   22118   }
   22119   *pOut = r;
   22120   return SQLITE_OK;
   22121 }
   22122 
   22123 /*
   22124 ** Lower the locking level on file descriptor id to locktype.  locktype
   22125 ** must be either NO_LOCK or SHARED_LOCK.
   22126 **
   22127 ** If the locking level of the file descriptor is already at or below
   22128 ** the requested locking level, this routine is a no-op.
   22129 **
   22130 ** It is not possible for this routine to fail if the second argument
   22131 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   22132 ** might return SQLITE_IOERR;
   22133 */
   22134 static int os2Unlock( sqlite3_file *id, int locktype ){
   22135   int type;
   22136   os2File *pFile = (os2File*)id;
   22137   APIRET rc = SQLITE_OK;
   22138   APIRET res = NO_ERROR;
   22139   FILELOCK  LockArea,
   22140             UnlockArea;
   22141   memset(&LockArea, 0, sizeof(LockArea));
   22142   memset(&UnlockArea, 0, sizeof(UnlockArea));
   22143   assert( pFile!=0 );
   22144   assert( locktype<=SHARED_LOCK );
   22145   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
   22146   type = pFile->locktype;
   22147   if( type>=EXCLUSIVE_LOCK ){
   22148     LockArea.lOffset = 0L;
   22149     LockArea.lRange = 0L;
   22150     UnlockArea.lOffset = SHARED_FIRST;
   22151     UnlockArea.lRange = SHARED_SIZE;
   22152     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22153     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
   22154     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
   22155       /* This should never happen.  We should always be able to
   22156       ** reacquire the read lock */
   22157       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
   22158       rc = SQLITE_IOERR_UNLOCK;
   22159     }
   22160   }
   22161   if( type>=RESERVED_LOCK ){
   22162     LockArea.lOffset = 0L;
   22163     LockArea.lRange = 0L;
   22164     UnlockArea.lOffset = RESERVED_BYTE;
   22165     UnlockArea.lRange = 1L;
   22166     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22167     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
   22168   }
   22169   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   22170     res = unlockReadLock(pFile);
   22171     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
   22172               pFile->h, type, locktype, res ));
   22173   }
   22174   if( type>=PENDING_LOCK ){
   22175     LockArea.lOffset = 0L;
   22176     LockArea.lRange = 0L;
   22177     UnlockArea.lOffset = PENDING_BYTE;
   22178     UnlockArea.lRange = 1L;
   22179     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
   22180     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
   22181   }
   22182   pFile->locktype = locktype;
   22183   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
   22184   return rc;
   22185 }
   22186 
   22187 /*
   22188 ** Control and query of the open file handle.
   22189 */
   22190 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
   22191   switch( op ){
   22192     case SQLITE_FCNTL_LOCKSTATE: {
   22193       *(int*)pArg = ((os2File*)id)->locktype;
   22194       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
   22195                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
   22196       return SQLITE_OK;
   22197     }
   22198   }
   22199   return SQLITE_ERROR;
   22200 }
   22201 
   22202 /*
   22203 ** Return the sector size in bytes of the underlying block device for
   22204 ** the specified file. This is almost always 512 bytes, but may be
   22205 ** larger for some devices.
   22206 **
   22207 ** SQLite code assumes this function cannot fail. It also assumes that
   22208 ** if two files are created in the same file-system directory (i.e.
   22209 ** a database and its journal file) that the sector size will be the
   22210 ** same for both.
   22211 */
   22212 static int os2SectorSize(sqlite3_file *id){
   22213   return SQLITE_DEFAULT_SECTOR_SIZE;
   22214 }
   22215 
   22216 /*
   22217 ** Return a vector of device characteristics.
   22218 */
   22219 static int os2DeviceCharacteristics(sqlite3_file *id){
   22220   return 0;
   22221 }
   22222 
   22223 
   22224 /*
   22225 ** Character set conversion objects used by conversion routines.
   22226 */
   22227 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
   22228 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
   22229 
   22230 /*
   22231 ** Helper function to initialize the conversion objects from and to UTF-8.
   22232 */
   22233 static void initUconvObjects( void ){
   22234   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
   22235     ucUtf8 = NULL;
   22236   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
   22237     uclCp = NULL;
   22238 }
   22239 
   22240 /*
   22241 ** Helper function to free the conversion objects from and to UTF-8.
   22242 */
   22243 static void freeUconvObjects( void ){
   22244   if ( ucUtf8 )
   22245     UniFreeUconvObject( ucUtf8 );
   22246   if ( uclCp )
   22247     UniFreeUconvObject( uclCp );
   22248   ucUtf8 = NULL;
   22249   uclCp = NULL;
   22250 }
   22251 
   22252 /*
   22253 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
   22254 ** The two-step process: first convert the incoming UTF-8 string
   22255 ** into UCS-2 and then from UCS-2 to the current codepage.
   22256 ** The returned char pointer has to be freed.
   22257 */
   22258 static char *convertUtf8PathToCp( const char *in ){
   22259   UniChar tempPath[CCHMAXPATH];
   22260   char *out = (char *)calloc( CCHMAXPATH, 1 );
   22261 
   22262   if( !out )
   22263     return NULL;
   22264 
   22265   if( !ucUtf8 || !uclCp )
   22266     initUconvObjects();
   22267 
   22268   /* determine string for the conversion of UTF-8 which is CP1208 */
   22269   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   22270     return out; /* if conversion fails, return the empty string */
   22271 
   22272   /* conversion for current codepage which can be used for paths */
   22273   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
   22274 
   22275   return out;
   22276 }
   22277 
   22278 /*
   22279 ** Helper function to convert filenames from local codepage to UTF-8.
   22280 ** The two-step process: first convert the incoming codepage-specific
   22281 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
   22282 ** The returned char pointer has to be freed.
   22283 **
   22284 ** This function is non-static to be able to use this in shell.c and
   22285 ** similar applications that take command line arguments.
   22286 */
   22287 char *convertCpPathToUtf8( const char *in ){
   22288   UniChar tempPath[CCHMAXPATH];
   22289   char *out = (char *)calloc( CCHMAXPATH, 1 );
   22290 
   22291   if( !out )
   22292     return NULL;
   22293 
   22294   if( !ucUtf8 || !uclCp )
   22295     initUconvObjects();
   22296 
   22297   /* conversion for current codepage which can be used for paths */
   22298   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
   22299     return out; /* if conversion fails, return the empty string */
   22300 
   22301   /* determine string for the conversion of UTF-8 which is CP1208 */
   22302   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
   22303 
   22304   return out;
   22305 }
   22306 
   22307 /*
   22308 ** This vector defines all the methods that can operate on an
   22309 ** sqlite3_file for os2.
   22310 */
   22311 static const sqlite3_io_methods os2IoMethod = {
   22312   1,                        /* iVersion */
   22313   os2Close,
   22314   os2Read,
   22315   os2Write,
   22316   os2Truncate,
   22317   os2Sync,
   22318   os2FileSize,
   22319   os2Lock,
   22320   os2Unlock,
   22321   os2CheckReservedLock,
   22322   os2FileControl,
   22323   os2SectorSize,
   22324   os2DeviceCharacteristics
   22325 };
   22326 
   22327 /***************************************************************************
   22328 ** Here ends the I/O methods that form the sqlite3_io_methods object.
   22329 **
   22330 ** The next block of code implements the VFS methods.
   22331 ****************************************************************************/
   22332 
   22333 /*
   22334 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   22335 ** hold at pVfs->mxPathname characters.
   22336 */
   22337 static int getTempname(int nBuf, char *zBuf ){
   22338   static const unsigned char zChars[] =
   22339     "abcdefghijklmnopqrstuvwxyz"
   22340     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   22341     "0123456789";
   22342   int i, j;
   22343   char zTempPathBuf[3];
   22344   PSZ zTempPath = (PSZ)&zTempPathBuf;
   22345   if( sqlite3_temp_directory ){
   22346     zTempPath = sqlite3_temp_directory;
   22347   }else{
   22348     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
   22349       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
   22350         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
   22351            ULONG ulDriveNum = 0, ulDriveMap = 0;
   22352            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
   22353            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
   22354         }
   22355       }
   22356     }
   22357   }
   22358   /* Strip off a trailing slashes or backslashes, otherwise we would get *
   22359    * multiple (back)slashes which causes DosOpen() to fail.              *
   22360    * Trailing spaces are not allowed, either.                            */
   22361   j = sqlite3Strlen30(zTempPath);
   22362   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
   22363                     || zTempPath[j-1] == ' ' ) ){
   22364     j--;
   22365   }
   22366   zTempPath[j] = '\0';
   22367   if( !sqlite3_temp_directory ){
   22368     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
   22369     sqlite3_snprintf( nBuf-30, zBuf,
   22370                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
   22371     free( zTempPathUTF );
   22372   }else{
   22373     sqlite3_snprintf( nBuf-30, zBuf,
   22374                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
   22375   }
   22376   j = sqlite3Strlen30( zBuf );
   22377   sqlite3_randomness( 20, &zBuf[j] );
   22378   for( i = 0; i < 20; i++, j++ ){
   22379     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   22380   }
   22381   zBuf[j] = 0;
   22382   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
   22383   return SQLITE_OK;
   22384 }
   22385 
   22386 
   22387 /*
   22388 ** Turn a relative pathname into a full pathname.  Write the full
   22389 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
   22390 ** bytes in size.
   22391 */
   22392 static int os2FullPathname(
   22393   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
   22394   const char *zRelative,      /* Possibly relative input path */
   22395   int nFull,                  /* Size of output buffer in bytes */
   22396   char *zFull                 /* Output buffer */
   22397 ){
   22398   char *zRelativeCp = convertUtf8PathToCp( zRelative );
   22399   char zFullCp[CCHMAXPATH] = "\0";
   22400   char *zFullUTF;
   22401   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
   22402                                 CCHMAXPATH );
   22403   free( zRelativeCp );
   22404   zFullUTF = convertCpPathToUtf8( zFullCp );
   22405   sqlite3_snprintf( nFull, zFull, zFullUTF );
   22406   free( zFullUTF );
   22407   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
   22408 }
   22409 
   22410 
   22411 /*
   22412 ** Open a file.
   22413 */
   22414 static int os2Open(
   22415   sqlite3_vfs *pVfs,            /* Not used */
   22416   const char *zName,            /* Name of the file */
   22417   sqlite3_file *id,             /* Write the SQLite file handle here */
   22418   int flags,                    /* Open mode flags */
   22419   int *pOutFlags                /* Status return flags */
   22420 ){
   22421   HFILE h;
   22422   ULONG ulFileAttribute = FILE_NORMAL;
   22423   ULONG ulOpenFlags = 0;
   22424   ULONG ulOpenMode = 0;
   22425   os2File *pFile = (os2File*)id;
   22426   APIRET rc = NO_ERROR;
   22427   ULONG ulAction;
   22428   char *zNameCp;
   22429   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
   22430 
   22431   /* If the second argument to this function is NULL, generate a
   22432   ** temporary file name to use
   22433   */
   22434   if( !zName ){
   22435     int rc = getTempname(CCHMAXPATH+1, zTmpname);
   22436     if( rc!=SQLITE_OK ){
   22437       return rc;
   22438     }
   22439     zName = zTmpname;
   22440   }
   22441 
   22442 
   22443   memset( pFile, 0, sizeof(*pFile) );
   22444 
   22445   OSTRACE(( "OPEN want %d\n", flags ));
   22446 
   22447   if( flags & SQLITE_OPEN_READWRITE ){
   22448     ulOpenMode |= OPEN_ACCESS_READWRITE;
   22449     OSTRACE(( "OPEN read/write\n" ));
   22450   }else{
   22451     ulOpenMode |= OPEN_ACCESS_READONLY;
   22452     OSTRACE(( "OPEN read only\n" ));
   22453   }
   22454 
   22455   if( flags & SQLITE_OPEN_CREATE ){
   22456     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
   22457     OSTRACE(( "OPEN open new/create\n" ));
   22458   }else{
   22459     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
   22460     OSTRACE(( "OPEN open existing\n" ));
   22461   }
   22462 
   22463   if( flags & SQLITE_OPEN_MAIN_DB ){
   22464     ulOpenMode |= OPEN_SHARE_DENYNONE;
   22465     OSTRACE(( "OPEN share read/write\n" ));
   22466   }else{
   22467     ulOpenMode |= OPEN_SHARE_DENYWRITE;
   22468     OSTRACE(( "OPEN share read only\n" ));
   22469   }
   22470 
   22471   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   22472     char pathUtf8[CCHMAXPATH];
   22473 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
   22474     ulFileAttribute = FILE_HIDDEN;
   22475 #endif
   22476     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
   22477     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
   22478     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
   22479   }else{
   22480     pFile->pathToDel = NULL;
   22481     OSTRACE(( "OPEN normal file attribute\n" ));
   22482   }
   22483 
   22484   /* always open in random access mode for possibly better speed */
   22485   ulOpenMode |= OPEN_FLAGS_RANDOM;
   22486   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
   22487   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
   22488 
   22489   zNameCp = convertUtf8PathToCp( zName );
   22490   rc = DosOpen( (PSZ)zNameCp,
   22491                 &h,
   22492                 &ulAction,
   22493                 0L,
   22494                 ulFileAttribute,
   22495                 ulOpenFlags,
   22496                 ulOpenMode,
   22497                 (PEAOP2)NULL );
   22498   free( zNameCp );
   22499   if( rc != NO_ERROR ){
   22500     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
   22501               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
   22502     if( pFile->pathToDel )
   22503       free( pFile->pathToDel );
   22504     pFile->pathToDel = NULL;
   22505     if( flags & SQLITE_OPEN_READWRITE ){
   22506       OSTRACE(( "OPEN %d Invalid handle\n",
   22507                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
   22508       return os2Open( pVfs, zName, id,
   22509                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
   22510                       pOutFlags );
   22511     }else{
   22512       return SQLITE_CANTOPEN;
   22513     }
   22514   }
   22515 
   22516   if( pOutFlags ){
   22517     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
   22518   }
   22519 
   22520   pFile->pMethod = &os2IoMethod;
   22521   pFile->h = h;
   22522   OpenCounter(+1);
   22523   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
   22524   return SQLITE_OK;
   22525 }
   22526 
   22527 /*
   22528 ** Delete the named file.
   22529 */
   22530 static int os2Delete(
   22531   sqlite3_vfs *pVfs,                     /* Not used on os2 */
   22532   const char *zFilename,                 /* Name of file to delete */
   22533   int syncDir                            /* Not used on os2 */
   22534 ){
   22535   APIRET rc = NO_ERROR;
   22536   char *zFilenameCp = convertUtf8PathToCp( zFilename );
   22537   SimulateIOError( return SQLITE_IOERR_DELETE );
   22538   rc = DosDelete( (PSZ)zFilenameCp );
   22539   free( zFilenameCp );
   22540   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
   22541   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
   22542 }
   22543 
   22544 /*
   22545 ** Check the existance and status of a file.
   22546 */
   22547 static int os2Access(
   22548   sqlite3_vfs *pVfs,        /* Not used on os2 */
   22549   const char *zFilename,    /* Name of file to check */
   22550   int flags,                /* Type of test to make on this file */
   22551   int *pOut                 /* Write results here */
   22552 ){
   22553   FILESTATUS3 fsts3ConfigInfo;
   22554   APIRET rc = NO_ERROR;
   22555   char *zFilenameCp = convertUtf8PathToCp( zFilename );
   22556 
   22557   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
   22558   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
   22559                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
   22560   free( zFilenameCp );
   22561   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
   22562             fsts3ConfigInfo.attrFile, flags, rc ));
   22563   switch( flags ){
   22564     case SQLITE_ACCESS_READ:
   22565     case SQLITE_ACCESS_EXISTS:
   22566       rc = (rc == NO_ERROR);
   22567       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
   22568       break;
   22569     case SQLITE_ACCESS_READWRITE:
   22570       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
   22571       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
   22572       break;
   22573     default:
   22574       assert( !"Invalid flags argument" );
   22575   }
   22576   *pOut = rc;
   22577   return SQLITE_OK;
   22578 }
   22579 
   22580 
   22581 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   22582 /*
   22583 ** Interfaces for opening a shared library, finding entry points
   22584 ** within the shared library, and closing the shared library.
   22585 */
   22586 /*
   22587 ** Interfaces for opening a shared library, finding entry points
   22588 ** within the shared library, and closing the shared library.
   22589 */
   22590 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   22591   UCHAR loadErr[256];
   22592   HMODULE hmod;
   22593   APIRET rc;
   22594   char *zFilenameCp = convertUtf8PathToCp(zFilename);
   22595   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
   22596   free(zFilenameCp);
   22597   return rc != NO_ERROR ? 0 : (void*)hmod;
   22598 }
   22599 /*
   22600 ** A no-op since the error code is returned on the DosLoadModule call.
   22601 ** os2Dlopen returns zero if DosLoadModule is not successful.
   22602 */
   22603 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   22604 /* no-op */
   22605 }
   22606 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
   22607   PFN pfn;
   22608   APIRET rc;
   22609   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
   22610   if( rc != NO_ERROR ){
   22611     /* if the symbol itself was not found, search again for the same
   22612      * symbol with an extra underscore, that might be needed depending
   22613      * on the calling convention */
   22614     char _zSymbol[256] = "_";
   22615     strncat(_zSymbol, zSymbol, 255);
   22616     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
   22617   }
   22618   return rc != NO_ERROR ? 0 : (void*)pfn;
   22619 }
   22620 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
   22621   DosFreeModule((HMODULE)pHandle);
   22622 }
   22623 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   22624   #define os2DlOpen 0
   22625   #define os2DlError 0
   22626   #define os2DlSym 0
   22627   #define os2DlClose 0
   22628 #endif
   22629 
   22630 
   22631 /*
   22632 ** Write up to nBuf bytes of randomness into zBuf.
   22633 */
   22634 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
   22635   int n = 0;
   22636 #if defined(SQLITE_TEST)
   22637   n = nBuf;
   22638   memset(zBuf, 0, nBuf);
   22639 #else
   22640   int sizeofULong = sizeof(ULONG);
   22641   if( (int)sizeof(DATETIME) <= nBuf - n ){
   22642     DATETIME x;
   22643     DosGetDateTime(&x);
   22644     memcpy(&zBuf[n], &x, sizeof(x));
   22645     n += sizeof(x);
   22646   }
   22647 
   22648   if( sizeofULong <= nBuf - n ){
   22649     PPIB ppib;
   22650     DosGetInfoBlocks(NULL, &ppib);
   22651     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
   22652     n += sizeofULong;
   22653   }
   22654 
   22655   if( sizeofULong <= nBuf - n ){
   22656     PTIB ptib;
   22657     DosGetInfoBlocks(&ptib, NULL);
   22658     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
   22659     n += sizeofULong;
   22660   }
   22661 
   22662   /* if we still haven't filled the buffer yet the following will */
   22663   /* grab everything once instead of making several calls for a single item */
   22664   if( sizeofULong <= nBuf - n ){
   22665     ULONG ulSysInfo[QSV_MAX];
   22666     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
   22667 
   22668     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
   22669     n += sizeofULong;
   22670 
   22671     if( sizeofULong <= nBuf - n ){
   22672       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
   22673       n += sizeofULong;
   22674     }
   22675     if( sizeofULong <= nBuf - n ){
   22676       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
   22677       n += sizeofULong;
   22678     }
   22679     if( sizeofULong <= nBuf - n ){
   22680       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
   22681       n += sizeofULong;
   22682     }
   22683     if( sizeofULong <= nBuf - n ){
   22684       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
   22685       n += sizeofULong;
   22686     }
   22687   }
   22688 #endif
   22689 
   22690   return n;
   22691 }
   22692 
   22693 /*
   22694 ** Sleep for a little while.  Return the amount of time slept.
   22695 ** The argument is the number of microseconds we want to sleep.
   22696 ** The return value is the number of microseconds of sleep actually
   22697 ** requested from the underlying operating system, a number which
   22698 ** might be greater than or equal to the argument, but not less
   22699 ** than the argument.
   22700 */
   22701 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
   22702   DosSleep( (microsec/1000) );
   22703   return microsec;
   22704 }
   22705 
   22706 /*
   22707 ** The following variable, if set to a non-zero value, becomes the result
   22708 ** returned from sqlite3OsCurrentTime().  This is used for testing.
   22709 */
   22710 #ifdef SQLITE_TEST
   22711 SQLITE_API int sqlite3_current_time = 0;
   22712 #endif
   22713 
   22714 /*
   22715 ** Find the current time (in Universal Coordinated Time).  Write the
   22716 ** current time and date as a Julian Day number into *prNow and
   22717 ** return 0.  Return 1 if the time and date cannot be found.
   22718 */
   22719 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
   22720   double now;
   22721   SHORT minute; /* needs to be able to cope with negative timezone offset */
   22722   USHORT second, hour,
   22723          day, month, year;
   22724   DATETIME dt;
   22725   DosGetDateTime( &dt );
   22726   second = (USHORT)dt.seconds;
   22727   minute = (SHORT)dt.minutes + dt.timezone;
   22728   hour = (USHORT)dt.hours;
   22729   day = (USHORT)dt.day;
   22730   month = (USHORT)dt.month;
   22731   year = (USHORT)dt.year;
   22732 
   22733   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
   22734      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
   22735   /* Calculate the Julian days */
   22736   now = day - 32076 +
   22737     1461*(year + 4800 + (month - 14)/12)/4 +
   22738     367*(month - 2 - (month - 14)/12*12)/12 -
   22739     3*((year + 4900 + (month - 14)/12)/100)/4;
   22740 
   22741   /* Add the fractional hours, mins and seconds */
   22742   now += (hour + 12.0)/24.0;
   22743   now += minute/1440.0;
   22744   now += second/86400.0;
   22745   *prNow = now;
   22746 #ifdef SQLITE_TEST
   22747   if( sqlite3_current_time ){
   22748     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
   22749   }
   22750 #endif
   22751   return 0;
   22752 }
   22753 
   22754 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   22755   return 0;
   22756 }
   22757 
   22758 /*
   22759 ** Initialize and deinitialize the operating system interface.
   22760 */
   22761 SQLITE_API int sqlite3_os_init(void){
   22762   static sqlite3_vfs os2Vfs = {
   22763     1,                 /* iVersion */
   22764     sizeof(os2File),   /* szOsFile */
   22765     CCHMAXPATH,        /* mxPathname */
   22766     0,                 /* pNext */
   22767     "os2",             /* zName */
   22768     0,                 /* pAppData */
   22769 
   22770     os2Open,           /* xOpen */
   22771     os2Delete,         /* xDelete */
   22772     os2Access,         /* xAccess */
   22773     os2FullPathname,   /* xFullPathname */
   22774     os2DlOpen,         /* xDlOpen */
   22775     os2DlError,        /* xDlError */
   22776     os2DlSym,          /* xDlSym */
   22777     os2DlClose,        /* xDlClose */
   22778     os2Randomness,     /* xRandomness */
   22779     os2Sleep,          /* xSleep */
   22780     os2CurrentTime,    /* xCurrentTime */
   22781     os2GetLastError,   /* xGetLastError */
   22782   };
   22783   sqlite3_vfs_register(&os2Vfs, 1);
   22784   initUconvObjects();
   22785   return SQLITE_OK;
   22786 }
   22787 SQLITE_API int sqlite3_os_end(void){
   22788   freeUconvObjects();
   22789   return SQLITE_OK;
   22790 }
   22791 
   22792 #endif /* SQLITE_OS_OS2 */
   22793 
   22794 /************** End of os_os2.c **********************************************/
   22795 /************** Begin file os_unix.c *****************************************/
   22796 /*
   22797 ** 2004 May 22
   22798 **
   22799 ** The author disclaims copyright to this source code.  In place of
   22800 ** a legal notice, here is a blessing:
   22801 **
   22802 **    May you do good and not evil.
   22803 **    May you find forgiveness for yourself and forgive others.
   22804 **    May you share freely, never taking more than you give.
   22805 **
   22806 ******************************************************************************
   22807 **
   22808 ** This file contains the VFS implementation for unix-like operating systems
   22809 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
   22810 **
   22811 ** There are actually several different VFS implementations in this file.
   22812 ** The differences are in the way that file locking is done.  The default
   22813 ** implementation uses Posix Advisory Locks.  Alternative implementations
   22814 ** use flock(), dot-files, various proprietary locking schemas, or simply
   22815 ** skip locking all together.
   22816 **
   22817 ** This source file is organized into divisions where the logic for various
   22818 ** subfunctions is contained within the appropriate division.  PLEASE
   22819 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
   22820 ** in the correct division and should be clearly labeled.
   22821 **
   22822 ** The layout of divisions is as follows:
   22823 **
   22824 **   *  General-purpose declarations and utility functions.
   22825 **   *  Unique file ID logic used by VxWorks.
   22826 **   *  Various locking primitive implementations (all except proxy locking):
   22827 **      + for Posix Advisory Locks
   22828 **      + for no-op locks
   22829 **      + for dot-file locks
   22830 **      + for flock() locking
   22831 **      + for named semaphore locks (VxWorks only)
   22832 **      + for AFP filesystem locks (MacOSX only)
   22833 **   *  sqlite3_file methods not associated with locking.
   22834 **   *  Definitions of sqlite3_io_methods objects for all locking
   22835 **      methods plus "finder" functions for each locking method.
   22836 **   *  sqlite3_vfs method implementations.
   22837 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
   22838 **   *  Definitions of sqlite3_vfs objects for all locking methods
   22839 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
   22840 */
   22841 #if SQLITE_OS_UNIX              /* This file is used on unix only */
   22842 
   22843 /*
   22844 ** There are various methods for file locking used for concurrency
   22845 ** control:
   22846 **
   22847 **   1. POSIX locking (the default),
   22848 **   2. No locking,
   22849 **   3. Dot-file locking,
   22850 **   4. flock() locking,
   22851 **   5. AFP locking (OSX only),
   22852 **   6. Named POSIX semaphores (VXWorks only),
   22853 **   7. proxy locking. (OSX only)
   22854 **
   22855 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
   22856 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
   22857 ** selection of the appropriate locking style based on the filesystem
   22858 ** where the database is located.
   22859 */
   22860 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   22861 #  if defined(__APPLE__)
   22862 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   22863 #  else
   22864 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   22865 #  endif
   22866 #endif
   22867 
   22868 /*
   22869 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
   22870 ** vxworks, or 0 otherwise.
   22871 */
   22872 #ifndef OS_VXWORKS
   22873 #  if defined(__RTP__) || defined(_WRS_KERNEL)
   22874 #    define OS_VXWORKS 1
   22875 #  else
   22876 #    define OS_VXWORKS 0
   22877 #  endif
   22878 #endif
   22879 
   22880 /*
   22881 ** These #defines should enable >2GB file support on Posix if the
   22882 ** underlying operating system supports it.  If the OS lacks
   22883 ** large file support, these should be no-ops.
   22884 **
   22885 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
   22886 ** on the compiler command line.  This is necessary if you are compiling
   22887 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
   22888 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
   22889 ** without this option, LFS is enable.  But LFS does not exist in the kernel
   22890 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
   22891 ** portability you should omit LFS.
   22892 **
   22893 ** The previous paragraph was written in 2005.  (This paragraph is written
   22894 ** on 2008-11-28.) These days, all Linux kernels support large files, so
   22895 ** you should probably leave LFS enabled.  But some embedded platforms might
   22896 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
   22897 */
   22898 #ifndef SQLITE_DISABLE_LFS
   22899 # define _LARGE_FILE       1
   22900 # ifndef _FILE_OFFSET_BITS
   22901 #   define _FILE_OFFSET_BITS 64
   22902 # endif
   22903 # define _LARGEFILE_SOURCE 1
   22904 #endif
   22905 
   22906 /*
   22907 ** standard include files.
   22908 */
   22909 #include <sys/types.h>
   22910 #include <sys/stat.h>
   22911 #include <fcntl.h>
   22912 #include <unistd.h>
   22913 #include <sys/time.h>
   22914 #include <errno.h>
   22915 #include <sys/mman.h>
   22916 
   22917 #if SQLITE_ENABLE_LOCKING_STYLE
   22918 # include <sys/ioctl.h>
   22919 # if OS_VXWORKS
   22920 #  include <semaphore.h>
   22921 #  include <limits.h>
   22922 # else
   22923 #  include <sys/file.h>
   22924 #  include <sys/param.h>
   22925 # endif
   22926 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   22927 
   22928 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
   22929 # include <sys/mount.h>
   22930 #endif
   22931 
   22932 /*
   22933 ** Allowed values of unixFile.fsFlags
   22934 */
   22935 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
   22936 
   22937 /*
   22938 ** If we are to be thread-safe, include the pthreads header and define
   22939 ** the SQLITE_UNIX_THREADS macro.
   22940 */
   22941 #if SQLITE_THREADSAFE
   22942 # define SQLITE_UNIX_THREADS 1
   22943 #endif
   22944 
   22945 /*
   22946 ** Default permissions when creating a new file
   22947 */
   22948 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
   22949 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
   22950 #endif
   22951 
   22952 /*
   22953  ** Default permissions when creating auto proxy dir
   22954  */
   22955 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   22956 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
   22957 #endif
   22958 
   22959 /*
   22960 ** Maximum supported path-length.
   22961 */
   22962 #define MAX_PATHNAME 512
   22963 
   22964 /*
   22965 ** Only set the lastErrno if the error code is a real error and not
   22966 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
   22967 */
   22968 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
   22969 
   22970 /* Forward references */
   22971 typedef struct unixShm unixShm;               /* Connection shared memory */
   22972 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
   22973 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
   22974 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
   22975 
   22976 /*
   22977 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
   22978 ** cannot be closed immediately. In these cases, instances of the following
   22979 ** structure are used to store the file descriptor while waiting for an
   22980 ** opportunity to either close or reuse it.
   22981 */
   22982 struct UnixUnusedFd {
   22983   int fd;                   /* File descriptor to close */
   22984   int flags;                /* Flags this file descriptor was opened with */
   22985   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
   22986 };
   22987 
   22988 /*
   22989 ** The unixFile structure is subclass of sqlite3_file specific to the unix
   22990 ** VFS implementations.
   22991 */
   22992 typedef struct unixFile unixFile;
   22993 struct unixFile {
   22994   sqlite3_io_methods const *pMethod;  /* Always the first entry */
   22995   unixInodeInfo *pInode;              /* Info about locks on this inode */
   22996   int h;                              /* The file descriptor */
   22997   int dirfd;                          /* File descriptor for the directory */
   22998   unsigned char eFileLock;            /* The type of lock held on this fd */
   22999   int lastErrno;                      /* The unix errno from last I/O error */
   23000   void *lockingContext;               /* Locking style specific state */
   23001   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
   23002   int fileFlags;                      /* Miscellanous flags */
   23003   const char *zPath;                  /* Name of the file */
   23004   unixShm *pShm;                      /* Shared memory segment information */
   23005   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
   23006 #if SQLITE_ENABLE_LOCKING_STYLE
   23007   int openFlags;                      /* The flags specified at open() */
   23008 #endif
   23009 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
   23010   unsigned fsFlags;                   /* cached details from statfs() */
   23011 #endif
   23012 #if OS_VXWORKS
   23013   int isDelete;                       /* Delete on close if true */
   23014   struct vxworksFileId *pId;          /* Unique file ID */
   23015 #endif
   23016 #ifndef NDEBUG
   23017   /* The next group of variables are used to track whether or not the
   23018   ** transaction counter in bytes 24-27 of database files are updated
   23019   ** whenever any part of the database changes.  An assertion fault will
   23020   ** occur if a file is updated without also updating the transaction
   23021   ** counter.  This test is made to avoid new problems similar to the
   23022   ** one described by ticket #3584.
   23023   */
   23024   unsigned char transCntrChng;   /* True if the transaction counter changed */
   23025   unsigned char dbUpdate;        /* True if any part of database file changed */
   23026   unsigned char inNormalWrite;   /* True if in a normal write operation */
   23027 #endif
   23028 #ifdef SQLITE_TEST
   23029   /* In test mode, increase the size of this structure a bit so that
   23030   ** it is larger than the struct CrashFile defined in test6.c.
   23031   */
   23032   char aPadding[32];
   23033 #endif
   23034 };
   23035 
   23036 /*
   23037 ** The following macros define bits in unixFile.fileFlags
   23038 */
   23039 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
   23040 
   23041 /*
   23042 ** Include code that is common to all os_*.c files
   23043 */
   23044 /************** Include os_common.h in the middle of os_unix.c ***************/
   23045 /************** Begin file os_common.h ***************************************/
   23046 /*
   23047 ** 2004 May 22
   23048 **
   23049 ** The author disclaims copyright to this source code.  In place of
   23050 ** a legal notice, here is a blessing:
   23051 **
   23052 **    May you do good and not evil.
   23053 **    May you find forgiveness for yourself and forgive others.
   23054 **    May you share freely, never taking more than you give.
   23055 **
   23056 ******************************************************************************
   23057 **
   23058 ** This file contains macros and a little bit of code that is common to
   23059 ** all of the platform-specific files (os_*.c) and is #included into those
   23060 ** files.
   23061 **
   23062 ** This file should be #included by the os_*.c files only.  It is not a
   23063 ** general purpose header file.
   23064 */
   23065 #ifndef _OS_COMMON_H_
   23066 #define _OS_COMMON_H_
   23067 
   23068 /*
   23069 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   23070 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   23071 ** switch.  The following code should catch this problem at compile-time.
   23072 */
   23073 #ifdef MEMORY_DEBUG
   23074 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   23075 #endif
   23076 
   23077 #ifdef SQLITE_DEBUG
   23078 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   23079 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   23080 #else
   23081 #define OSTRACE(X)
   23082 #endif
   23083 
   23084 /*
   23085 ** Macros for performance tracing.  Normally turned off.  Only works
   23086 ** on i486 hardware.
   23087 */
   23088 #ifdef SQLITE_PERFORMANCE_TRACE
   23089 
   23090 /*
   23091 ** hwtime.h contains inline assembler code for implementing
   23092 ** high-performance timing routines.
   23093 */
   23094 /************** Include hwtime.h in the middle of os_common.h ****************/
   23095 /************** Begin file hwtime.h ******************************************/
   23096 /*
   23097 ** 2008 May 27
   23098 **
   23099 ** The author disclaims copyright to this source code.  In place of
   23100 ** a legal notice, here is a blessing:
   23101 **
   23102 **    May you do good and not evil.
   23103 **    May you find forgiveness for yourself and forgive others.
   23104 **    May you share freely, never taking more than you give.
   23105 **
   23106 ******************************************************************************
   23107 **
   23108 ** This file contains inline asm code for retrieving "high-performance"
   23109 ** counters for x86 class CPUs.
   23110 */
   23111 #ifndef _HWTIME_H_
   23112 #define _HWTIME_H_
   23113 
   23114 /*
   23115 ** The following routine only works on pentium-class (or newer) processors.
   23116 ** It uses the RDTSC opcode to read the cycle count value out of the
   23117 ** processor and returns that value.  This can be used for high-res
   23118 ** profiling.
   23119 */
   23120 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   23121       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   23122 
   23123   #if defined(__GNUC__)
   23124 
   23125   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   23126      unsigned int lo, hi;
   23127      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   23128      return (sqlite_uint64)hi << 32 | lo;
   23129   }
   23130 
   23131   #elif defined(_MSC_VER)
   23132 
   23133   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   23134      __asm {
   23135         rdtsc
   23136         ret       ; return value at EDX:EAX
   23137      }
   23138   }
   23139 
   23140   #endif
   23141 
   23142 #elif (defined(__GNUC__) && defined(__x86_64__))
   23143 
   23144   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   23145       unsigned long val;
   23146       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   23147       return val;
   23148   }
   23149 
   23150 #elif (defined(__GNUC__) && defined(__ppc__))
   23151 
   23152   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   23153       unsigned long long retval;
   23154       unsigned long junk;
   23155       __asm__ __volatile__ ("\n\
   23156           1:      mftbu   %1\n\
   23157                   mftb    %L0\n\
   23158                   mftbu   %0\n\
   23159                   cmpw    %0,%1\n\
   23160                   bne     1b"
   23161                   : "=r" (retval), "=r" (junk));
   23162       return retval;
   23163   }
   23164 
   23165 #else
   23166 
   23167   #error Need implementation of sqlite3Hwtime() for your platform.
   23168 
   23169   /*
   23170   ** To compile without implementing sqlite3Hwtime() for your platform,
   23171   ** you can remove the above #error and use the following
   23172   ** stub function.  You will lose timing support for many
   23173   ** of the debugging and testing utilities, but it should at
   23174   ** least compile and run.
   23175   */
   23176 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   23177 
   23178 #endif
   23179 
   23180 #endif /* !defined(_HWTIME_H_) */
   23181 
   23182 /************** End of hwtime.h **********************************************/
   23183 /************** Continuing where we left off in os_common.h ******************/
   23184 
   23185 static sqlite_uint64 g_start;
   23186 static sqlite_uint64 g_elapsed;
   23187 #define TIMER_START       g_start=sqlite3Hwtime()
   23188 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   23189 #define TIMER_ELAPSED     g_elapsed
   23190 #else
   23191 #define TIMER_START
   23192 #define TIMER_END
   23193 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   23194 #endif
   23195 
   23196 /*
   23197 ** If we compile with the SQLITE_TEST macro set, then the following block
   23198 ** of code will give us the ability to simulate a disk I/O error.  This
   23199 ** is used for testing the I/O recovery logic.
   23200 */
   23201 #ifdef SQLITE_TEST
   23202 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   23203 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   23204 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   23205 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   23206 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   23207 SQLITE_API int sqlite3_diskfull_pending = 0;
   23208 SQLITE_API int sqlite3_diskfull = 0;
   23209 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   23210 #define SimulateIOError(CODE)  \
   23211   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   23212        || sqlite3_io_error_pending-- == 1 )  \
   23213               { local_ioerr(); CODE; }
   23214 static void local_ioerr(){
   23215   IOTRACE(("IOERR\n"));
   23216   sqlite3_io_error_hit++;
   23217   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   23218 }
   23219 #define SimulateDiskfullError(CODE) \
   23220    if( sqlite3_diskfull_pending ){ \
   23221      if( sqlite3_diskfull_pending == 1 ){ \
   23222        local_ioerr(); \
   23223        sqlite3_diskfull = 1; \
   23224        sqlite3_io_error_hit = 1; \
   23225        CODE; \
   23226      }else{ \
   23227        sqlite3_diskfull_pending--; \
   23228      } \
   23229    }
   23230 #else
   23231 #define SimulateIOErrorBenign(X)
   23232 #define SimulateIOError(A)
   23233 #define SimulateDiskfullError(A)
   23234 #endif
   23235 
   23236 /*
   23237 ** When testing, keep a count of the number of open files.
   23238 */
   23239 #ifdef SQLITE_TEST
   23240 SQLITE_API int sqlite3_open_file_count = 0;
   23241 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   23242 #else
   23243 #define OpenCounter(X)
   23244 #endif
   23245 
   23246 #endif /* !defined(_OS_COMMON_H_) */
   23247 
   23248 /************** End of os_common.h *******************************************/
   23249 /************** Continuing where we left off in os_unix.c ********************/
   23250 
   23251 /*
   23252 ** Define various macros that are missing from some systems.
   23253 */
   23254 #ifndef O_LARGEFILE
   23255 # define O_LARGEFILE 0
   23256 #endif
   23257 #ifdef SQLITE_DISABLE_LFS
   23258 # undef O_LARGEFILE
   23259 # define O_LARGEFILE 0
   23260 #endif
   23261 #ifndef O_NOFOLLOW
   23262 # define O_NOFOLLOW 0
   23263 #endif
   23264 #ifndef O_BINARY
   23265 # define O_BINARY 0
   23266 #endif
   23267 
   23268 /*
   23269 ** The DJGPP compiler environment looks mostly like Unix, but it
   23270 ** lacks the fcntl() system call.  So redefine fcntl() to be something
   23271 ** that always succeeds.  This means that locking does not occur under
   23272 ** DJGPP.  But it is DOS - what did you expect?
   23273 */
   23274 #ifdef __DJGPP__
   23275 # define fcntl(A,B,C) 0
   23276 #endif
   23277 
   23278 /*
   23279 ** The threadid macro resolves to the thread-id or to 0.  Used for
   23280 ** testing and debugging only.
   23281 */
   23282 #if SQLITE_THREADSAFE
   23283 #define threadid pthread_self()
   23284 #else
   23285 #define threadid 0
   23286 #endif
   23287 
   23288 
   23289 /*
   23290 ** Helper functions to obtain and relinquish the global mutex. The
   23291 ** global mutex is used to protect the unixInodeInfo and
   23292 ** vxworksFileId objects used by this file, all of which may be
   23293 ** shared by multiple threads.
   23294 **
   23295 ** Function unixMutexHeld() is used to assert() that the global mutex
   23296 ** is held when required. This function is only used as part of assert()
   23297 ** statements. e.g.
   23298 **
   23299 **   unixEnterMutex()
   23300 **     assert( unixMutexHeld() );
   23301 **   unixEnterLeave()
   23302 */
   23303 static void unixEnterMutex(void){
   23304   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23305 }
   23306 static void unixLeaveMutex(void){
   23307   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23308 }
   23309 #ifdef SQLITE_DEBUG
   23310 static int unixMutexHeld(void) {
   23311   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   23312 }
   23313 #endif
   23314 
   23315 
   23316 #ifdef SQLITE_DEBUG
   23317 /*
   23318 ** Helper function for printing out trace information from debugging
   23319 ** binaries. This returns the string represetation of the supplied
   23320 ** integer lock-type.
   23321 */
   23322 static const char *azFileLock(int eFileLock){
   23323   switch( eFileLock ){
   23324     case NO_LOCK: return "NONE";
   23325     case SHARED_LOCK: return "SHARED";
   23326     case RESERVED_LOCK: return "RESERVED";
   23327     case PENDING_LOCK: return "PENDING";
   23328     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
   23329   }
   23330   return "ERROR";
   23331 }
   23332 #endif
   23333 
   23334 #ifdef SQLITE_LOCK_TRACE
   23335 /*
   23336 ** Print out information about all locking operations.
   23337 **
   23338 ** This routine is used for troubleshooting locks on multithreaded
   23339 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
   23340 ** command-line option on the compiler.  This code is normally
   23341 ** turned off.
   23342 */
   23343 static int lockTrace(int fd, int op, struct flock *p){
   23344   char *zOpName, *zType;
   23345   int s;
   23346   int savedErrno;
   23347   if( op==F_GETLK ){
   23348     zOpName = "GETLK";
   23349   }else if( op==F_SETLK ){
   23350     zOpName = "SETLK";
   23351   }else{
   23352     s = fcntl(fd, op, p);
   23353     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
   23354     return s;
   23355   }
   23356   if( p->l_type==F_RDLCK ){
   23357     zType = "RDLCK";
   23358   }else if( p->l_type==F_WRLCK ){
   23359     zType = "WRLCK";
   23360   }else if( p->l_type==F_UNLCK ){
   23361     zType = "UNLCK";
   23362   }else{
   23363     assert( 0 );
   23364   }
   23365   assert( p->l_whence==SEEK_SET );
   23366   s = fcntl(fd, op, p);
   23367   savedErrno = errno;
   23368   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
   23369      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
   23370      (int)p->l_pid, s);
   23371   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
   23372     struct flock l2;
   23373     l2 = *p;
   23374     fcntl(fd, F_GETLK, &l2);
   23375     if( l2.l_type==F_RDLCK ){
   23376       zType = "RDLCK";
   23377     }else if( l2.l_type==F_WRLCK ){
   23378       zType = "WRLCK";
   23379     }else if( l2.l_type==F_UNLCK ){
   23380       zType = "UNLCK";
   23381     }else{
   23382       assert( 0 );
   23383     }
   23384     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
   23385        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
   23386   }
   23387   errno = savedErrno;
   23388   return s;
   23389 }
   23390 #define fcntl lockTrace
   23391 #endif /* SQLITE_LOCK_TRACE */
   23392 
   23393 
   23394 /*
   23395 ** Retry ftruncate() calls that fail due to EINTR
   23396 */
   23397 #ifdef EINTR
   23398 static int robust_ftruncate(int h, sqlite3_int64 sz){
   23399   int rc;
   23400   do{ rc = ftruncate(h,sz); }while( rc<0 && errno==EINTR );
   23401   return rc;
   23402 }
   23403 #else
   23404 # define robust_ftruncate(a,b) ftruncate(a,b)
   23405 #endif
   23406 
   23407 
   23408 /*
   23409 ** This routine translates a standard POSIX errno code into something
   23410 ** useful to the clients of the sqlite3 functions.  Specifically, it is
   23411 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
   23412 ** and a variety of "please close the file descriptor NOW" errors into
   23413 ** SQLITE_IOERR
   23414 **
   23415 ** Errors during initialization of locks, or file system support for locks,
   23416 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
   23417 */
   23418 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
   23419   switch (posixError) {
   23420   case 0:
   23421     return SQLITE_OK;
   23422 
   23423   case EAGAIN:
   23424   case ETIMEDOUT:
   23425   case EBUSY:
   23426   case EINTR:
   23427   case ENOLCK:
   23428     /* random NFS retry error, unless during file system support
   23429      * introspection, in which it actually means what it says */
   23430     return SQLITE_BUSY;
   23431 
   23432   case EACCES:
   23433     /* EACCES is like EAGAIN during locking operations, but not any other time*/
   23434     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
   23435 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
   23436 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
   23437 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
   23438       return SQLITE_BUSY;
   23439     }
   23440     /* else fall through */
   23441   case EPERM:
   23442     return SQLITE_PERM;
   23443 
   23444   case EDEADLK:
   23445     return SQLITE_IOERR_BLOCKED;
   23446 
   23447 #if EOPNOTSUPP!=ENOTSUP
   23448   case EOPNOTSUPP:
   23449     /* something went terribly awry, unless during file system support
   23450      * introspection, in which it actually means what it says */
   23451 #endif
   23452 #ifdef ENOTSUP
   23453   case ENOTSUP:
   23454     /* invalid fd, unless during file system support introspection, in which
   23455      * it actually means what it says */
   23456 #endif
   23457   case EIO:
   23458   case EBADF:
   23459   case EINVAL:
   23460   case ENOTCONN:
   23461   case ENODEV:
   23462   case ENXIO:
   23463   case ENOENT:
   23464   case ESTALE:
   23465   case ENOSYS:
   23466     /* these should force the client to close the file and reconnect */
   23467 
   23468   default:
   23469     return sqliteIOErr;
   23470   }
   23471 }
   23472 
   23473 
   23474 
   23475 /******************************************************************************
   23476 ****************** Begin Unique File ID Utility Used By VxWorks ***************
   23477 **
   23478 ** On most versions of unix, we can get a unique ID for a file by concatenating
   23479 ** the device number and the inode number.  But this does not work on VxWorks.
   23480 ** On VxWorks, a unique file id must be based on the canonical filename.
   23481 **
   23482 ** A pointer to an instance of the following structure can be used as a
   23483 ** unique file ID in VxWorks.  Each instance of this structure contains
   23484 ** a copy of the canonical filename.  There is also a reference count.
   23485 ** The structure is reclaimed when the number of pointers to it drops to
   23486 ** zero.
   23487 **
   23488 ** There are never very many files open at one time and lookups are not
   23489 ** a performance-critical path, so it is sufficient to put these
   23490 ** structures on a linked list.
   23491 */
   23492 struct vxworksFileId {
   23493   struct vxworksFileId *pNext;  /* Next in a list of them all */
   23494   int nRef;                     /* Number of references to this one */
   23495   int nName;                    /* Length of the zCanonicalName[] string */
   23496   char *zCanonicalName;         /* Canonical filename */
   23497 };
   23498 
   23499 #if OS_VXWORKS
   23500 /*
   23501 ** All unique filenames are held on a linked list headed by this
   23502 ** variable:
   23503 */
   23504 static struct vxworksFileId *vxworksFileList = 0;
   23505 
   23506 /*
   23507 ** Simplify a filename into its canonical form
   23508 ** by making the following changes:
   23509 **
   23510 **  * removing any trailing and duplicate /
   23511 **  * convert /./ into just /
   23512 **  * convert /A/../ where A is any simple name into just /
   23513 **
   23514 ** Changes are made in-place.  Return the new name length.
   23515 **
   23516 ** The original filename is in z[0..n-1].  Return the number of
   23517 ** characters in the simplified name.
   23518 */
   23519 static int vxworksSimplifyName(char *z, int n){
   23520   int i, j;
   23521   while( n>1 && z[n-1]=='/' ){ n--; }
   23522   for(i=j=0; i<n; i++){
   23523     if( z[i]=='/' ){
   23524       if( z[i+1]=='/' ) continue;
   23525       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
   23526         i += 1;
   23527         continue;
   23528       }
   23529       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
   23530         while( j>0 && z[j-1]!='/' ){ j--; }
   23531         if( j>0 ){ j--; }
   23532         i += 2;
   23533         continue;
   23534       }
   23535     }
   23536     z[j++] = z[i];
   23537   }
   23538   z[j] = 0;
   23539   return j;
   23540 }
   23541 
   23542 /*
   23543 ** Find a unique file ID for the given absolute pathname.  Return
   23544 ** a pointer to the vxworksFileId object.  This pointer is the unique
   23545 ** file ID.
   23546 **
   23547 ** The nRef field of the vxworksFileId object is incremented before
   23548 ** the object is returned.  A new vxworksFileId object is created
   23549 ** and added to the global list if necessary.
   23550 **
   23551 ** If a memory allocation error occurs, return NULL.
   23552 */
   23553 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   23554   struct vxworksFileId *pNew;         /* search key and new file ID */
   23555   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
   23556   int n;                              /* Length of zAbsoluteName string */
   23557 
   23558   assert( zAbsoluteName[0]=='/' );
   23559   n = (int)strlen(zAbsoluteName);
   23560   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
   23561   if( pNew==0 ) return 0;
   23562   pNew->zCanonicalName = (char*)&pNew[1];
   23563   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
   23564   n = vxworksSimplifyName(pNew->zCanonicalName, n);
   23565 
   23566   /* Search for an existing entry that matching the canonical name.
   23567   ** If found, increment the reference count and return a pointer to
   23568   ** the existing file ID.
   23569   */
   23570   unixEnterMutex();
   23571   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
   23572     if( pCandidate->nName==n
   23573      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
   23574     ){
   23575        sqlite3_free(pNew);
   23576        pCandidate->nRef++;
   23577        unixLeaveMutex();
   23578        return pCandidate;
   23579     }
   23580   }
   23581 
   23582   /* No match was found.  We will make a new file ID */
   23583   pNew->nRef = 1;
   23584   pNew->nName = n;
   23585   pNew->pNext = vxworksFileList;
   23586   vxworksFileList = pNew;
   23587   unixLeaveMutex();
   23588   return pNew;
   23589 }
   23590 
   23591 /*
   23592 ** Decrement the reference count on a vxworksFileId object.  Free
   23593 ** the object when the reference count reaches zero.
   23594 */
   23595 static void vxworksReleaseFileId(struct vxworksFileId *pId){
   23596   unixEnterMutex();
   23597   assert( pId->nRef>0 );
   23598   pId->nRef--;
   23599   if( pId->nRef==0 ){
   23600     struct vxworksFileId **pp;
   23601     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
   23602     assert( *pp==pId );
   23603     *pp = pId->pNext;
   23604     sqlite3_free(pId);
   23605   }
   23606   unixLeaveMutex();
   23607 }
   23608 #endif /* OS_VXWORKS */
   23609 /*************** End of Unique File ID Utility Used By VxWorks ****************
   23610 ******************************************************************************/
   23611 
   23612 
   23613 /******************************************************************************
   23614 *************************** Posix Advisory Locking ****************************
   23615 **
   23616 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
   23617 ** section 6.5.2.2 lines 483 through 490 specify that when a process
   23618 ** sets or clears a lock, that operation overrides any prior locks set
   23619 ** by the same process.  It does not explicitly say so, but this implies
   23620 ** that it overrides locks set by the same process using a different
   23621 ** file descriptor.  Consider this test case:
   23622 **
   23623 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
   23624 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
   23625 **
   23626 ** Suppose ./file1 and ./file2 are really the same file (because
   23627 ** one is a hard or symbolic link to the other) then if you set
   23628 ** an exclusive lock on fd1, then try to get an exclusive lock
   23629 ** on fd2, it works.  I would have expected the second lock to
   23630 ** fail since there was already a lock on the file due to fd1.
   23631 ** But not so.  Since both locks came from the same process, the
   23632 ** second overrides the first, even though they were on different
   23633 ** file descriptors opened on different file names.
   23634 **
   23635 ** This means that we cannot use POSIX locks to synchronize file access
   23636 ** among competing threads of the same process.  POSIX locks will work fine
   23637 ** to synchronize access for threads in separate processes, but not
   23638 ** threads within the same process.
   23639 **
   23640 ** To work around the problem, SQLite has to manage file locks internally
   23641 ** on its own.  Whenever a new database is opened, we have to find the
   23642 ** specific inode of the database file (the inode is determined by the
   23643 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
   23644 ** and check for locks already existing on that inode.  When locks are
   23645 ** created or removed, we have to look at our own internal record of the
   23646 ** locks to see if another thread has previously set a lock on that same
   23647 ** inode.
   23648 **
   23649 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
   23650 ** For VxWorks, we have to use the alternative unique ID system based on
   23651 ** canonical filename and implemented in the previous division.)
   23652 **
   23653 ** The sqlite3_file structure for POSIX is no longer just an integer file
   23654 ** descriptor.  It is now a structure that holds the integer file
   23655 ** descriptor and a pointer to a structure that describes the internal
   23656 ** locks on the corresponding inode.  There is one locking structure
   23657 ** per inode, so if the same inode is opened twice, both unixFile structures
   23658 ** point to the same locking structure.  The locking structure keeps
   23659 ** a reference count (so we will know when to delete it) and a "cnt"
   23660 ** field that tells us its internal lock status.  cnt==0 means the
   23661 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
   23662 ** cnt>0 means there are cnt shared locks on the file.
   23663 **
   23664 ** Any attempt to lock or unlock a file first checks the locking
   23665 ** structure.  The fcntl() system call is only invoked to set a
   23666 ** POSIX lock if the internal lock structure transitions between
   23667 ** a locked and an unlocked state.
   23668 **
   23669 ** But wait:  there are yet more problems with POSIX advisory locks.
   23670 **
   23671 ** If you close a file descriptor that points to a file that has locks,
   23672 ** all locks on that file that are owned by the current process are
   23673 ** released.  To work around this problem, each unixInodeInfo object
   23674 ** maintains a count of the number of pending locks on tha inode.
   23675 ** When an attempt is made to close an unixFile, if there are
   23676 ** other unixFile open on the same inode that are holding locks, the call
   23677 ** to close() the file descriptor is deferred until all of the locks clear.
   23678 ** The unixInodeInfo structure keeps a list of file descriptors that need to
   23679 ** be closed and that list is walked (and cleared) when the last lock
   23680 ** clears.
   23681 **
   23682 ** Yet another problem:  LinuxThreads do not play well with posix locks.
   23683 **
   23684 ** Many older versions of linux use the LinuxThreads library which is
   23685 ** not posix compliant.  Under LinuxThreads, a lock created by thread
   23686 ** A cannot be modified or overridden by a different thread B.
   23687 ** Only thread A can modify the lock.  Locking behavior is correct
   23688 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
   23689 ** on linux - with NPTL a lock created by thread A can override locks
   23690 ** in thread B.  But there is no way to know at compile-time which
   23691 ** threading library is being used.  So there is no way to know at
   23692 ** compile-time whether or not thread A can override locks on thread B.
   23693 ** One has to do a run-time check to discover the behavior of the
   23694 ** current process.
   23695 **
   23696 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
   23697 ** was dropped beginning with version 3.7.0.  SQLite will still work with
   23698 ** LinuxThreads provided that (1) there is no more than one connection
   23699 ** per database file in the same process and (2) database connections
   23700 ** do not move across threads.
   23701 */
   23702 
   23703 /*
   23704 ** An instance of the following structure serves as the key used
   23705 ** to locate a particular unixInodeInfo object.
   23706 */
   23707 struct unixFileId {
   23708   dev_t dev;                  /* Device number */
   23709 #if OS_VXWORKS
   23710   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
   23711 #else
   23712   ino_t ino;                  /* Inode number */
   23713 #endif
   23714 };
   23715 
   23716 /*
   23717 ** An instance of the following structure is allocated for each open
   23718 ** inode.  Or, on LinuxThreads, there is one of these structures for
   23719 ** each inode opened by each thread.
   23720 **
   23721 ** A single inode can have multiple file descriptors, so each unixFile
   23722 ** structure contains a pointer to an instance of this object and this
   23723 ** object keeps a count of the number of unixFile pointing to it.
   23724 */
   23725 struct unixInodeInfo {
   23726   struct unixFileId fileId;       /* The lookup key */
   23727   int nShared;                    /* Number of SHARED locks held */
   23728   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
   23729   int nRef;                       /* Number of pointers to this structure */
   23730   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
   23731   int nLock;                      /* Number of outstanding file locks */
   23732   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
   23733   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
   23734   unixInodeInfo *pPrev;           /*    .... doubly linked */
   23735 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
   23736   unsigned long long sharedByte;  /* for AFP simulated shared lock */
   23737 #endif
   23738 #if OS_VXWORKS
   23739   sem_t *pSem;                    /* Named POSIX semaphore */
   23740   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
   23741 #endif
   23742 };
   23743 
   23744 /*
   23745 ** A lists of all unixInodeInfo objects.
   23746 */
   23747 static unixInodeInfo *inodeList = 0;
   23748 
   23749 /*
   23750 **
   23751 ** This function - unixLogError_x(), is only ever called via the macro
   23752 ** unixLogError().
   23753 **
   23754 ** It is invoked after an error occurs in an OS function and errno has been
   23755 ** set. It logs a message using sqlite3_log() containing the current value of
   23756 ** errno and, if possible, the human-readable equivalent from strerror() or
   23757 ** strerror_r().
   23758 **
   23759 ** The first argument passed to the macro should be the error code that
   23760 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
   23761 ** The two subsequent arguments should be the name of the OS function that
   23762 ** failed (e.g. "unlink", "open") and the the associated file-system path,
   23763 ** if any.
   23764 */
   23765 #define unixLogError(a,b,c)     unixLogError_x(a,b,c,__LINE__)
   23766 static int unixLogError_x(
   23767   int errcode,                    /* SQLite error code */
   23768   const char *zFunc,              /* Name of OS function that failed */
   23769   const char *zPath,              /* File path associated with error */
   23770   int iLine                       /* Source line number where error occurred */
   23771 ){
   23772   char *zErr;                     /* Message from strerror() or equivalent */
   23773 
   23774   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   23775   ** the strerror() function to obtain the human-readable error message
   23776   ** equivalent to errno. Otherwise, use strerror_r().
   23777   */
   23778 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   23779   char aErr[80];
   23780   memset(aErr, 0, sizeof(aErr));
   23781   zErr = aErr;
   23782 
   23783   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   23784   ** assume that the system provides the the GNU version of strerror_r() that
   23785   ** returns a pointer to a buffer containing the error message. That pointer
   23786   ** may point to aErr[], or it may point to some static storage somewhere.
   23787   ** Otherwise, assume that the system provides the POSIX version of
   23788   ** strerror_r(), which always writes an error message into aErr[].
   23789   **
   23790   ** If the code incorrectly assumes that it is the POSIX version that is
   23791   ** available, the error message will often be an empty string. Not a
   23792   ** huge problem. Incorrectly concluding that the GNU version is available
   23793   ** could lead to a segfault though.
   23794   */
   23795 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
   23796   zErr =
   23797 # endif
   23798   strerror_r(errno, aErr, sizeof(aErr)-1);
   23799 
   23800 #elif SQLITE_THREADSAFE
   23801   /* This is a threadsafe build, but strerror_r() is not available. */
   23802   zErr = "";
   23803 #else
   23804   /* Non-threadsafe build, use strerror(). */
   23805   zErr = strerror(errno);
   23806 #endif
   23807 
   23808   assert( errcode!=SQLITE_OK );
   23809   sqlite3_log(errcode,
   23810       "os_unix.c: %s() at line %d - \"%s\" errno=%d path=%s",
   23811       zFunc, iLine, zErr, errno, (zPath ? zPath : "n/a")
   23812   );
   23813 
   23814   return errcode;
   23815 }
   23816 
   23817 
   23818 /*
   23819 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
   23820 ** If all such file descriptors are closed without error, the list is
   23821 ** cleared and SQLITE_OK returned.
   23822 **
   23823 ** Otherwise, if an error occurs, then successfully closed file descriptor
   23824 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
   23825 ** not deleted and SQLITE_IOERR_CLOSE returned.
   23826 */
   23827 static int closePendingFds(unixFile *pFile){
   23828   int rc = SQLITE_OK;
   23829   unixInodeInfo *pInode = pFile->pInode;
   23830   UnixUnusedFd *pError = 0;
   23831   UnixUnusedFd *p;
   23832   UnixUnusedFd *pNext;
   23833   for(p=pInode->pUnused; p; p=pNext){
   23834     pNext = p->pNext;
   23835     if( close(p->fd) ){
   23836       pFile->lastErrno = errno;
   23837       rc = unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
   23838       p->pNext = pError;
   23839       pError = p;
   23840     }else{
   23841       sqlite3_free(p);
   23842     }
   23843   }
   23844   pInode->pUnused = pError;
   23845   return rc;
   23846 }
   23847 
   23848 /*
   23849 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
   23850 **
   23851 ** The mutex entered using the unixEnterMutex() function must be held
   23852 ** when this function is called.
   23853 */
   23854 static void releaseInodeInfo(unixFile *pFile){
   23855   unixInodeInfo *pInode = pFile->pInode;
   23856   assert( unixMutexHeld() );
   23857   if( pInode ){
   23858     pInode->nRef--;
   23859     if( pInode->nRef==0 ){
   23860       assert( pInode->pShmNode==0 );
   23861       closePendingFds(pFile);
   23862       if( pInode->pPrev ){
   23863         assert( pInode->pPrev->pNext==pInode );
   23864         pInode->pPrev->pNext = pInode->pNext;
   23865       }else{
   23866         assert( inodeList==pInode );
   23867         inodeList = pInode->pNext;
   23868       }
   23869       if( pInode->pNext ){
   23870         assert( pInode->pNext->pPrev==pInode );
   23871         pInode->pNext->pPrev = pInode->pPrev;
   23872       }
   23873       sqlite3_free(pInode);
   23874     }
   23875   }
   23876 }
   23877 
   23878 /*
   23879 ** Given a file descriptor, locate the unixInodeInfo object that
   23880 ** describes that file descriptor.  Create a new one if necessary.  The
   23881 ** return value might be uninitialized if an error occurs.
   23882 **
   23883 ** The mutex entered using the unixEnterMutex() function must be held
   23884 ** when this function is called.
   23885 **
   23886 ** Return an appropriate error code.
   23887 */
   23888 static int findInodeInfo(
   23889   unixFile *pFile,               /* Unix file with file desc used in the key */
   23890   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
   23891 ){
   23892   int rc;                        /* System call return code */
   23893   int fd;                        /* The file descriptor for pFile */
   23894   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
   23895   struct stat statbuf;           /* Low-level file information */
   23896   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
   23897 
   23898   assert( unixMutexHeld() );
   23899 
   23900   /* Get low-level information about the file that we can used to
   23901   ** create a unique name for the file.
   23902   */
   23903   fd = pFile->h;
   23904   rc = fstat(fd, &statbuf);
   23905   if( rc!=0 ){
   23906     pFile->lastErrno = errno;
   23907 #ifdef EOVERFLOW
   23908     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
   23909 #endif
   23910     return SQLITE_IOERR;
   23911   }
   23912 
   23913 #ifdef __APPLE__
   23914   /* On OS X on an msdos filesystem, the inode number is reported
   23915   ** incorrectly for zero-size files.  See ticket #3260.  To work
   23916   ** around this problem (we consider it a bug in OS X, not SQLite)
   23917   ** we always increase the file size to 1 by writing a single byte
   23918   ** prior to accessing the inode number.  The one byte written is
   23919   ** an ASCII 'S' character which also happens to be the first byte
   23920   ** in the header of every SQLite database.  In this way, if there
   23921   ** is a race condition such that another thread has already populated
   23922   ** the first page of the database, no damage is done.
   23923   */
   23924   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
   23925     do{ rc = write(fd, "S", 1); }while( rc<0 && errno==EINTR );
   23926     if( rc!=1 ){
   23927       pFile->lastErrno = errno;
   23928       return SQLITE_IOERR;
   23929     }
   23930     rc = fstat(fd, &statbuf);
   23931     if( rc!=0 ){
   23932       pFile->lastErrno = errno;
   23933       return SQLITE_IOERR;
   23934     }
   23935   }
   23936 #endif
   23937 
   23938   memset(&fileId, 0, sizeof(fileId));
   23939   fileId.dev = statbuf.st_dev;
   23940 #if OS_VXWORKS
   23941   fileId.pId = pFile->pId;
   23942 #else
   23943   fileId.ino = statbuf.st_ino;
   23944 #endif
   23945   pInode = inodeList;
   23946   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
   23947     pInode = pInode->pNext;
   23948   }
   23949   if( pInode==0 ){
   23950     pInode = sqlite3_malloc( sizeof(*pInode) );
   23951     if( pInode==0 ){
   23952       return SQLITE_NOMEM;
   23953     }
   23954     memset(pInode, 0, sizeof(*pInode));
   23955     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
   23956     pInode->nRef = 1;
   23957     pInode->pNext = inodeList;
   23958     pInode->pPrev = 0;
   23959     if( inodeList ) inodeList->pPrev = pInode;
   23960     inodeList = pInode;
   23961   }else{
   23962     pInode->nRef++;
   23963   }
   23964   *ppInode = pInode;
   23965   return SQLITE_OK;
   23966 }
   23967 
   23968 
   23969 /*
   23970 ** This routine checks if there is a RESERVED lock held on the specified
   23971 ** file by this or any other process. If such a lock is held, set *pResOut
   23972 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   23973 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   23974 */
   23975 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   23976   int rc = SQLITE_OK;
   23977   int reserved = 0;
   23978   unixFile *pFile = (unixFile*)id;
   23979 
   23980   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   23981 
   23982   assert( pFile );
   23983   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   23984 
   23985   /* Check if a thread in this process holds such a lock */
   23986   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   23987     reserved = 1;
   23988   }
   23989 
   23990   /* Otherwise see if some other process holds it.
   23991   */
   23992 #ifndef __DJGPP__
   23993   if( !reserved ){
   23994     struct flock lock;
   23995     lock.l_whence = SEEK_SET;
   23996     lock.l_start = RESERVED_BYTE;
   23997     lock.l_len = 1;
   23998     lock.l_type = F_WRLCK;
   23999     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
   24000       int tErrno = errno;
   24001       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   24002       pFile->lastErrno = tErrno;
   24003     } else if( lock.l_type!=F_UNLCK ){
   24004       reserved = 1;
   24005     }
   24006   }
   24007 #endif
   24008 
   24009   unixLeaveMutex();
   24010   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
   24011 
   24012   *pResOut = reserved;
   24013   return rc;
   24014 }
   24015 
   24016 /*
   24017 ** Lock the file with the lock specified by parameter eFileLock - one
   24018 ** of the following:
   24019 **
   24020 **     (1) SHARED_LOCK
   24021 **     (2) RESERVED_LOCK
   24022 **     (3) PENDING_LOCK
   24023 **     (4) EXCLUSIVE_LOCK
   24024 **
   24025 ** Sometimes when requesting one lock state, additional lock states
   24026 ** are inserted in between.  The locking might fail on one of the later
   24027 ** transitions leaving the lock state different from what it started but
   24028 ** still short of its goal.  The following chart shows the allowed
   24029 ** transitions and the inserted intermediate states:
   24030 **
   24031 **    UNLOCKED -> SHARED
   24032 **    SHARED -> RESERVED
   24033 **    SHARED -> (PENDING) -> EXCLUSIVE
   24034 **    RESERVED -> (PENDING) -> EXCLUSIVE
   24035 **    PENDING -> EXCLUSIVE
   24036 **
   24037 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   24038 ** routine to lower a locking level.
   24039 */
   24040 static int unixLock(sqlite3_file *id, int eFileLock){
   24041   /* The following describes the implementation of the various locks and
   24042   ** lock transitions in terms of the POSIX advisory shared and exclusive
   24043   ** lock primitives (called read-locks and write-locks below, to avoid
   24044   ** confusion with SQLite lock names). The algorithms are complicated
   24045   ** slightly in order to be compatible with windows systems simultaneously
   24046   ** accessing the same database file, in case that is ever required.
   24047   **
   24048   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
   24049   ** byte', each single bytes at well known offsets, and the 'shared byte
   24050   ** range', a range of 510 bytes at a well known offset.
   24051   **
   24052   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
   24053   ** byte'.  If this is successful, a random byte from the 'shared byte
   24054   ** range' is read-locked and the lock on the 'pending byte' released.
   24055   **
   24056   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   24057   ** A RESERVED lock is implemented by grabbing a write-lock on the
   24058   ** 'reserved byte'.
   24059   **
   24060   ** A process may only obtain a PENDING lock after it has obtained a
   24061   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
   24062   ** on the 'pending byte'. This ensures that no new SHARED locks can be
   24063   ** obtained, but existing SHARED locks are allowed to persist. A process
   24064   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
   24065   ** This property is used by the algorithm for rolling back a journal file
   24066   ** after a crash.
   24067   **
   24068   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
   24069   ** implemented by obtaining a write-lock on the entire 'shared byte
   24070   ** range'. Since all other locks require a read-lock on one of the bytes
   24071   ** within this range, this ensures that no other locks are held on the
   24072   ** database.
   24073   **
   24074   ** The reason a single byte cannot be used instead of the 'shared byte
   24075   ** range' is that some versions of windows do not support read-locks. By
   24076   ** locking a random byte from a range, concurrent SHARED locks may exist
   24077   ** even if the locking primitive used is always a write-lock.
   24078   */
   24079   int rc = SQLITE_OK;
   24080   unixFile *pFile = (unixFile*)id;
   24081   unixInodeInfo *pInode = pFile->pInode;
   24082   struct flock lock;
   24083   int s = 0;
   24084   int tErrno = 0;
   24085 
   24086   assert( pFile );
   24087   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
   24088       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   24089       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   24090 
   24091   /* If there is already a lock of this type or more restrictive on the
   24092   ** unixFile, do nothing. Don't use the end_lock: exit path, as
   24093   ** unixEnterMutex() hasn't been called yet.
   24094   */
   24095   if( pFile->eFileLock>=eFileLock ){
   24096     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
   24097             azFileLock(eFileLock)));
   24098     return SQLITE_OK;
   24099   }
   24100 
   24101   /* Make sure the locking sequence is correct.
   24102   **  (1) We never move from unlocked to anything higher than shared lock.
   24103   **  (2) SQLite never explicitly requests a pendig lock.
   24104   **  (3) A shared lock is always held when a reserve lock is requested.
   24105   */
   24106   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   24107   assert( eFileLock!=PENDING_LOCK );
   24108   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   24109 
   24110   /* This mutex is needed because pFile->pInode is shared across threads
   24111   */
   24112   unixEnterMutex();
   24113   pInode = pFile->pInode;
   24114 
   24115   /* If some thread using this PID has a lock via a different unixFile*
   24116   ** handle that precludes the requested lock, return BUSY.
   24117   */
   24118   if( (pFile->eFileLock!=pInode->eFileLock &&
   24119           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   24120   ){
   24121     rc = SQLITE_BUSY;
   24122     goto end_lock;
   24123   }
   24124 
   24125   /* If a SHARED lock is requested, and some thread using this PID already
   24126   ** has a SHARED or RESERVED lock, then increment reference counts and
   24127   ** return SQLITE_OK.
   24128   */
   24129   if( eFileLock==SHARED_LOCK &&
   24130       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   24131     assert( eFileLock==SHARED_LOCK );
   24132     assert( pFile->eFileLock==0 );
   24133     assert( pInode->nShared>0 );
   24134     pFile->eFileLock = SHARED_LOCK;
   24135     pInode->nShared++;
   24136     pInode->nLock++;
   24137     goto end_lock;
   24138   }
   24139 
   24140 
   24141   /* A PENDING lock is needed before acquiring a SHARED lock and before
   24142   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   24143   ** be released.
   24144   */
   24145   lock.l_len = 1L;
   24146   lock.l_whence = SEEK_SET;
   24147   if( eFileLock==SHARED_LOCK
   24148       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   24149   ){
   24150     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
   24151     lock.l_start = PENDING_BYTE;
   24152     s = fcntl(pFile->h, F_SETLK, &lock);
   24153     if( s==(-1) ){
   24154       tErrno = errno;
   24155       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24156       if( IS_LOCK_ERROR(rc) ){
   24157         pFile->lastErrno = tErrno;
   24158       }
   24159       goto end_lock;
   24160     }
   24161   }
   24162 
   24163 
   24164   /* If control gets to this point, then actually go ahead and make
   24165   ** operating system calls for the specified lock.
   24166   */
   24167   if( eFileLock==SHARED_LOCK ){
   24168     assert( pInode->nShared==0 );
   24169     assert( pInode->eFileLock==0 );
   24170 
   24171     /* Now get the read-lock */
   24172     lock.l_start = SHARED_FIRST;
   24173     lock.l_len = SHARED_SIZE;
   24174     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
   24175       tErrno = errno;
   24176     }
   24177     /* Drop the temporary PENDING lock */
   24178     lock.l_start = PENDING_BYTE;
   24179     lock.l_len = 1L;
   24180     lock.l_type = F_UNLCK;
   24181     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
   24182       if( s != -1 ){
   24183         /* This could happen with a network mount */
   24184         tErrno = errno;
   24185         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24186         if( IS_LOCK_ERROR(rc) ){
   24187           pFile->lastErrno = tErrno;
   24188         }
   24189         goto end_lock;
   24190       }
   24191     }
   24192     if( s==(-1) ){
   24193       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24194       if( IS_LOCK_ERROR(rc) ){
   24195         pFile->lastErrno = tErrno;
   24196       }
   24197     }else{
   24198       pFile->eFileLock = SHARED_LOCK;
   24199       pInode->nLock++;
   24200       pInode->nShared = 1;
   24201     }
   24202   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   24203     /* We are trying for an exclusive lock but another thread in this
   24204     ** same process is still holding a shared lock. */
   24205     rc = SQLITE_BUSY;
   24206   }else{
   24207     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   24208     ** assumed that there is a SHARED or greater lock on the file
   24209     ** already.
   24210     */
   24211     assert( 0!=pFile->eFileLock );
   24212     lock.l_type = F_WRLCK;
   24213     switch( eFileLock ){
   24214       case RESERVED_LOCK:
   24215         lock.l_start = RESERVED_BYTE;
   24216         break;
   24217       case EXCLUSIVE_LOCK:
   24218         lock.l_start = SHARED_FIRST;
   24219         lock.l_len = SHARED_SIZE;
   24220         break;
   24221       default:
   24222         assert(0);
   24223     }
   24224     s = fcntl(pFile->h, F_SETLK, &lock);
   24225     if( s==(-1) ){
   24226       tErrno = errno;
   24227       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24228       if( IS_LOCK_ERROR(rc) ){
   24229         pFile->lastErrno = tErrno;
   24230       }
   24231     }
   24232   }
   24233 
   24234 
   24235 #ifndef NDEBUG
   24236   /* Set up the transaction-counter change checking flags when
   24237   ** transitioning from a SHARED to a RESERVED lock.  The change
   24238   ** from SHARED to RESERVED marks the beginning of a normal
   24239   ** write operation (not a hot journal rollback).
   24240   */
   24241   if( rc==SQLITE_OK
   24242    && pFile->eFileLock<=SHARED_LOCK
   24243    && eFileLock==RESERVED_LOCK
   24244   ){
   24245     pFile->transCntrChng = 0;
   24246     pFile->dbUpdate = 0;
   24247     pFile->inNormalWrite = 1;
   24248   }
   24249 #endif
   24250 
   24251 
   24252   if( rc==SQLITE_OK ){
   24253     pFile->eFileLock = eFileLock;
   24254     pInode->eFileLock = eFileLock;
   24255   }else if( eFileLock==EXCLUSIVE_LOCK ){
   24256     pFile->eFileLock = PENDING_LOCK;
   24257     pInode->eFileLock = PENDING_LOCK;
   24258   }
   24259 
   24260 end_lock:
   24261   unixLeaveMutex();
   24262   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
   24263       rc==SQLITE_OK ? "ok" : "failed"));
   24264   return rc;
   24265 }
   24266 
   24267 /*
   24268 ** Add the file descriptor used by file handle pFile to the corresponding
   24269 ** pUnused list.
   24270 */
   24271 static void setPendingFd(unixFile *pFile){
   24272   unixInodeInfo *pInode = pFile->pInode;
   24273   UnixUnusedFd *p = pFile->pUnused;
   24274   p->pNext = pInode->pUnused;
   24275   pInode->pUnused = p;
   24276   pFile->h = -1;
   24277   pFile->pUnused = 0;
   24278 }
   24279 
   24280 /*
   24281 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   24282 ** must be either NO_LOCK or SHARED_LOCK.
   24283 **
   24284 ** If the locking level of the file descriptor is already at or below
   24285 ** the requested locking level, this routine is a no-op.
   24286 **
   24287 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
   24288 ** the byte range is divided into 2 parts and the first part is unlocked then
   24289 ** set to a read lock, then the other part is simply unlocked.  This works
   24290 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
   24291 ** remove the write lock on a region when a read lock is set.
   24292 */
   24293 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
   24294   unixFile *pFile = (unixFile*)id;
   24295   unixInodeInfo *pInode;
   24296   struct flock lock;
   24297   int rc = SQLITE_OK;
   24298   int h;
   24299   int tErrno;                      /* Error code from system call errors */
   24300 
   24301   assert( pFile );
   24302   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
   24303       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   24304       getpid()));
   24305 
   24306   assert( eFileLock<=SHARED_LOCK );
   24307   if( pFile->eFileLock<=eFileLock ){
   24308     return SQLITE_OK;
   24309   }
   24310   unixEnterMutex();
   24311   h = pFile->h;
   24312   pInode = pFile->pInode;
   24313   assert( pInode->nShared!=0 );
   24314   if( pFile->eFileLock>SHARED_LOCK ){
   24315     assert( pInode->eFileLock==pFile->eFileLock );
   24316     SimulateIOErrorBenign(1);
   24317     SimulateIOError( h=(-1) )
   24318     SimulateIOErrorBenign(0);
   24319 
   24320 #ifndef NDEBUG
   24321     /* When reducing a lock such that other processes can start
   24322     ** reading the database file again, make sure that the
   24323     ** transaction counter was updated if any part of the database
   24324     ** file changed.  If the transaction counter is not updated,
   24325     ** other connections to the same file might not realize that
   24326     ** the file has changed and hence might not know to flush their
   24327     ** cache.  The use of a stale cache can lead to database corruption.
   24328     */
   24329 #if 0
   24330     assert( pFile->inNormalWrite==0
   24331          || pFile->dbUpdate==0
   24332          || pFile->transCntrChng==1 );
   24333 #endif
   24334     pFile->inNormalWrite = 0;
   24335 #endif
   24336 
   24337     /* downgrading to a shared lock on NFS involves clearing the write lock
   24338     ** before establishing the readlock - to avoid a race condition we downgrade
   24339     ** the lock in 2 blocks, so that part of the range will be covered by a
   24340     ** write lock until the rest is covered by a read lock:
   24341     **  1:   [WWWWW]
   24342     **  2:   [....W]
   24343     **  3:   [RRRRW]
   24344     **  4:   [RRRR.]
   24345     */
   24346     if( eFileLock==SHARED_LOCK ){
   24347       if( handleNFSUnlock ){
   24348         off_t divSize = SHARED_SIZE - 1;
   24349 
   24350         lock.l_type = F_UNLCK;
   24351         lock.l_whence = SEEK_SET;
   24352         lock.l_start = SHARED_FIRST;
   24353         lock.l_len = divSize;
   24354         if( fcntl(h, F_SETLK, &lock)==(-1) ){
   24355           tErrno = errno;
   24356           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24357           if( IS_LOCK_ERROR(rc) ){
   24358             pFile->lastErrno = tErrno;
   24359           }
   24360           goto end_unlock;
   24361         }
   24362         lock.l_type = F_RDLCK;
   24363         lock.l_whence = SEEK_SET;
   24364         lock.l_start = SHARED_FIRST;
   24365         lock.l_len = divSize;
   24366         if( fcntl(h, F_SETLK, &lock)==(-1) ){
   24367           tErrno = errno;
   24368           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   24369           if( IS_LOCK_ERROR(rc) ){
   24370             pFile->lastErrno = tErrno;
   24371           }
   24372           goto end_unlock;
   24373         }
   24374         lock.l_type = F_UNLCK;
   24375         lock.l_whence = SEEK_SET;
   24376         lock.l_start = SHARED_FIRST+divSize;
   24377         lock.l_len = SHARED_SIZE-divSize;
   24378         if( fcntl(h, F_SETLK, &lock)==(-1) ){
   24379           tErrno = errno;
   24380           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24381           if( IS_LOCK_ERROR(rc) ){
   24382             pFile->lastErrno = tErrno;
   24383           }
   24384           goto end_unlock;
   24385         }
   24386       }else{
   24387         lock.l_type = F_RDLCK;
   24388         lock.l_whence = SEEK_SET;
   24389         lock.l_start = SHARED_FIRST;
   24390         lock.l_len = SHARED_SIZE;
   24391         if( fcntl(h, F_SETLK, &lock)==(-1) ){
   24392           tErrno = errno;
   24393           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
   24394           if( IS_LOCK_ERROR(rc) ){
   24395             pFile->lastErrno = tErrno;
   24396           }
   24397           goto end_unlock;
   24398         }
   24399       }
   24400     }
   24401     lock.l_type = F_UNLCK;
   24402     lock.l_whence = SEEK_SET;
   24403     lock.l_start = PENDING_BYTE;
   24404     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
   24405     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
   24406       pInode->eFileLock = SHARED_LOCK;
   24407     }else{
   24408       tErrno = errno;
   24409       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24410       if( IS_LOCK_ERROR(rc) ){
   24411         pFile->lastErrno = tErrno;
   24412       }
   24413       goto end_unlock;
   24414     }
   24415   }
   24416   if( eFileLock==NO_LOCK ){
   24417     /* Decrement the shared lock counter.  Release the lock using an
   24418     ** OS call only when all threads in this same process have released
   24419     ** the lock.
   24420     */
   24421     pInode->nShared--;
   24422     if( pInode->nShared==0 ){
   24423       lock.l_type = F_UNLCK;
   24424       lock.l_whence = SEEK_SET;
   24425       lock.l_start = lock.l_len = 0L;
   24426       SimulateIOErrorBenign(1);
   24427       SimulateIOError( h=(-1) )
   24428       SimulateIOErrorBenign(0);
   24429       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
   24430         pInode->eFileLock = NO_LOCK;
   24431       }else{
   24432         tErrno = errno;
   24433         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24434         if( IS_LOCK_ERROR(rc) ){
   24435           pFile->lastErrno = tErrno;
   24436         }
   24437         pInode->eFileLock = NO_LOCK;
   24438         pFile->eFileLock = NO_LOCK;
   24439       }
   24440     }
   24441 
   24442     /* Decrement the count of locks against this same file.  When the
   24443     ** count reaches zero, close any other file descriptors whose close
   24444     ** was deferred because of outstanding locks.
   24445     */
   24446     pInode->nLock--;
   24447     assert( pInode->nLock>=0 );
   24448     if( pInode->nLock==0 ){
   24449       int rc2 = closePendingFds(pFile);
   24450       if( rc==SQLITE_OK ){
   24451         rc = rc2;
   24452       }
   24453     }
   24454   }
   24455 
   24456 end_unlock:
   24457   unixLeaveMutex();
   24458   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   24459   return rc;
   24460 }
   24461 
   24462 /*
   24463 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   24464 ** must be either NO_LOCK or SHARED_LOCK.
   24465 **
   24466 ** If the locking level of the file descriptor is already at or below
   24467 ** the requested locking level, this routine is a no-op.
   24468 */
   24469 static int unixUnlock(sqlite3_file *id, int eFileLock){
   24470   return _posixUnlock(id, eFileLock, 0);
   24471 }
   24472 
   24473 /*
   24474 ** This function performs the parts of the "close file" operation
   24475 ** common to all locking schemes. It closes the directory and file
   24476 ** handles, if they are valid, and sets all fields of the unixFile
   24477 ** structure to 0.
   24478 **
   24479 ** It is *not* necessary to hold the mutex when this routine is called,
   24480 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
   24481 ** vxworksReleaseFileId() routine.
   24482 */
   24483 static int closeUnixFile(sqlite3_file *id){
   24484   unixFile *pFile = (unixFile*)id;
   24485   if( pFile ){
   24486     if( pFile->dirfd>=0 ){
   24487       int err = close(pFile->dirfd);
   24488       if( err ){
   24489         pFile->lastErrno = errno;
   24490         return unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
   24491       }else{
   24492         pFile->dirfd=-1;
   24493       }
   24494     }
   24495     if( pFile->h>=0 ){
   24496       int err = close(pFile->h);
   24497       if( err ){
   24498         pFile->lastErrno = errno;
   24499         return unixLogError(SQLITE_IOERR_CLOSE, "close", pFile->zPath);
   24500       }
   24501     }
   24502 #if OS_VXWORKS
   24503     if( pFile->pId ){
   24504       if( pFile->isDelete ){
   24505         unlink(pFile->pId->zCanonicalName);
   24506       }
   24507       vxworksReleaseFileId(pFile->pId);
   24508       pFile->pId = 0;
   24509     }
   24510 #endif
   24511     OSTRACE(("CLOSE   %-3d\n", pFile->h));
   24512     OpenCounter(-1);
   24513     sqlite3_free(pFile->pUnused);
   24514     memset(pFile, 0, sizeof(unixFile));
   24515   }
   24516   return SQLITE_OK;
   24517 }
   24518 
   24519 /*
   24520 ** Close a file.
   24521 */
   24522 static int unixClose(sqlite3_file *id){
   24523   int rc = SQLITE_OK;
   24524   if( id ){
   24525     unixFile *pFile = (unixFile *)id;
   24526     unixUnlock(id, NO_LOCK);
   24527     unixEnterMutex();
   24528     if( pFile->pInode && pFile->pInode->nLock ){
   24529       /* If there are outstanding locks, do not actually close the file just
   24530       ** yet because that would clear those locks.  Instead, add the file
   24531       ** descriptor to pInode->pUnused list.  It will be automatically closed
   24532       ** when the last lock is cleared.
   24533       */
   24534       setPendingFd(pFile);
   24535     }
   24536     releaseInodeInfo(pFile);
   24537     rc = closeUnixFile(id);
   24538     unixLeaveMutex();
   24539   }
   24540   return rc;
   24541 }
   24542 
   24543 /************** End of the posix advisory lock implementation *****************
   24544 ******************************************************************************/
   24545 
   24546 /******************************************************************************
   24547 ****************************** No-op Locking **********************************
   24548 **
   24549 ** Of the various locking implementations available, this is by far the
   24550 ** simplest:  locking is ignored.  No attempt is made to lock the database
   24551 ** file for reading or writing.
   24552 **
   24553 ** This locking mode is appropriate for use on read-only databases
   24554 ** (ex: databases that are burned into CD-ROM, for example.)  It can
   24555 ** also be used if the application employs some external mechanism to
   24556 ** prevent simultaneous access of the same database by two or more
   24557 ** database connections.  But there is a serious risk of database
   24558 ** corruption if this locking mode is used in situations where multiple
   24559 ** database connections are accessing the same database file at the same
   24560 ** time and one or more of those connections are writing.
   24561 */
   24562 
   24563 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
   24564   UNUSED_PARAMETER(NotUsed);
   24565   *pResOut = 0;
   24566   return SQLITE_OK;
   24567 }
   24568 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
   24569   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   24570   return SQLITE_OK;
   24571 }
   24572 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
   24573   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   24574   return SQLITE_OK;
   24575 }
   24576 
   24577 /*
   24578 ** Close the file.
   24579 */
   24580 static int nolockClose(sqlite3_file *id) {
   24581   return closeUnixFile(id);
   24582 }
   24583 
   24584 /******************* End of the no-op lock implementation *********************
   24585 ******************************************************************************/
   24586 
   24587 /******************************************************************************
   24588 ************************* Begin dot-file Locking ******************************
   24589 **
   24590 ** The dotfile locking implementation uses the existance of separate lock
   24591 ** files in order to control access to the database.  This works on just
   24592 ** about every filesystem imaginable.  But there are serious downsides:
   24593 **
   24594 **    (1)  There is zero concurrency.  A single reader blocks all other
   24595 **         connections from reading or writing the database.
   24596 **
   24597 **    (2)  An application crash or power loss can leave stale lock files
   24598 **         sitting around that need to be cleared manually.
   24599 **
   24600 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
   24601 ** other locking strategy is available.
   24602 **
   24603 ** Dotfile locking works by creating a file in the same directory as the
   24604 ** database and with the same name but with a ".lock" extension added.
   24605 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
   24606 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
   24607 */
   24608 
   24609 /*
   24610 ** The file suffix added to the data base filename in order to create the
   24611 ** lock file.
   24612 */
   24613 #define DOTLOCK_SUFFIX ".lock"
   24614 
   24615 /*
   24616 ** This routine checks if there is a RESERVED lock held on the specified
   24617 ** file by this or any other process. If such a lock is held, set *pResOut
   24618 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   24619 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   24620 **
   24621 ** In dotfile locking, either a lock exists or it does not.  So in this
   24622 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
   24623 ** is held on the file and false if the file is unlocked.
   24624 */
   24625 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   24626   int rc = SQLITE_OK;
   24627   int reserved = 0;
   24628   unixFile *pFile = (unixFile*)id;
   24629 
   24630   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   24631 
   24632   assert( pFile );
   24633 
   24634   /* Check if a thread in this process holds such a lock */
   24635   if( pFile->eFileLock>SHARED_LOCK ){
   24636     /* Either this connection or some other connection in the same process
   24637     ** holds a lock on the file.  No need to check further. */
   24638     reserved = 1;
   24639   }else{
   24640     /* The lock is held if and only if the lockfile exists */
   24641     const char *zLockFile = (const char*)pFile->lockingContext;
   24642     reserved = access(zLockFile, 0)==0;
   24643   }
   24644   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
   24645   *pResOut = reserved;
   24646   return rc;
   24647 }
   24648 
   24649 /*
   24650 ** Lock the file with the lock specified by parameter eFileLock - one
   24651 ** of the following:
   24652 **
   24653 **     (1) SHARED_LOCK
   24654 **     (2) RESERVED_LOCK
   24655 **     (3) PENDING_LOCK
   24656 **     (4) EXCLUSIVE_LOCK
   24657 **
   24658 ** Sometimes when requesting one lock state, additional lock states
   24659 ** are inserted in between.  The locking might fail on one of the later
   24660 ** transitions leaving the lock state different from what it started but
   24661 ** still short of its goal.  The following chart shows the allowed
   24662 ** transitions and the inserted intermediate states:
   24663 **
   24664 **    UNLOCKED -> SHARED
   24665 **    SHARED -> RESERVED
   24666 **    SHARED -> (PENDING) -> EXCLUSIVE
   24667 **    RESERVED -> (PENDING) -> EXCLUSIVE
   24668 **    PENDING -> EXCLUSIVE
   24669 **
   24670 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   24671 ** routine to lower a locking level.
   24672 **
   24673 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
   24674 ** But we track the other locking levels internally.
   24675 */
   24676 static int dotlockLock(sqlite3_file *id, int eFileLock) {
   24677   unixFile *pFile = (unixFile*)id;
   24678   int fd;
   24679   char *zLockFile = (char *)pFile->lockingContext;
   24680   int rc = SQLITE_OK;
   24681 
   24682 
   24683   /* If we have any lock, then the lock file already exists.  All we have
   24684   ** to do is adjust our internal record of the lock level.
   24685   */
   24686   if( pFile->eFileLock > NO_LOCK ){
   24687     pFile->eFileLock = eFileLock;
   24688 #if !OS_VXWORKS
   24689     /* Always update the timestamp on the old file */
   24690     utimes(zLockFile, NULL);
   24691 #endif
   24692     return SQLITE_OK;
   24693   }
   24694 
   24695   /* grab an exclusive lock */
   24696   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
   24697   if( fd<0 ){
   24698     /* failed to open/create the file, someone else may have stolen the lock */
   24699     int tErrno = errno;
   24700     if( EEXIST == tErrno ){
   24701       rc = SQLITE_BUSY;
   24702     } else {
   24703       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24704       if( IS_LOCK_ERROR(rc) ){
   24705         pFile->lastErrno = tErrno;
   24706       }
   24707     }
   24708     return rc;
   24709   }
   24710   if( close(fd) ){
   24711     pFile->lastErrno = errno;
   24712     rc = SQLITE_IOERR_CLOSE;
   24713   }
   24714 
   24715   /* got it, set the type and return ok */
   24716   pFile->eFileLock = eFileLock;
   24717   return rc;
   24718 }
   24719 
   24720 /*
   24721 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   24722 ** must be either NO_LOCK or SHARED_LOCK.
   24723 **
   24724 ** If the locking level of the file descriptor is already at or below
   24725 ** the requested locking level, this routine is a no-op.
   24726 **
   24727 ** When the locking level reaches NO_LOCK, delete the lock file.
   24728 */
   24729 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   24730   unixFile *pFile = (unixFile*)id;
   24731   char *zLockFile = (char *)pFile->lockingContext;
   24732 
   24733   assert( pFile );
   24734   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
   24735 	   pFile->eFileLock, getpid()));
   24736   assert( eFileLock<=SHARED_LOCK );
   24737 
   24738   /* no-op if possible */
   24739   if( pFile->eFileLock==eFileLock ){
   24740     return SQLITE_OK;
   24741   }
   24742 
   24743   /* To downgrade to shared, simply update our internal notion of the
   24744   ** lock state.  No need to mess with the file on disk.
   24745   */
   24746   if( eFileLock==SHARED_LOCK ){
   24747     pFile->eFileLock = SHARED_LOCK;
   24748     return SQLITE_OK;
   24749   }
   24750 
   24751   /* To fully unlock the database, delete the lock file */
   24752   assert( eFileLock==NO_LOCK );
   24753   if( unlink(zLockFile) ){
   24754     int rc = 0;
   24755     int tErrno = errno;
   24756     if( ENOENT != tErrno ){
   24757       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24758     }
   24759     if( IS_LOCK_ERROR(rc) ){
   24760       pFile->lastErrno = tErrno;
   24761     }
   24762     return rc;
   24763   }
   24764   pFile->eFileLock = NO_LOCK;
   24765   return SQLITE_OK;
   24766 }
   24767 
   24768 /*
   24769 ** Close a file.  Make sure the lock has been released before closing.
   24770 */
   24771 static int dotlockClose(sqlite3_file *id) {
   24772   int rc;
   24773   if( id ){
   24774     unixFile *pFile = (unixFile*)id;
   24775     dotlockUnlock(id, NO_LOCK);
   24776     sqlite3_free(pFile->lockingContext);
   24777   }
   24778   rc = closeUnixFile(id);
   24779   return rc;
   24780 }
   24781 /****************** End of the dot-file lock implementation *******************
   24782 ******************************************************************************/
   24783 
   24784 /******************************************************************************
   24785 ************************** Begin flock Locking ********************************
   24786 **
   24787 ** Use the flock() system call to do file locking.
   24788 **
   24789 ** flock() locking is like dot-file locking in that the various
   24790 ** fine-grain locking levels supported by SQLite are collapsed into
   24791 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
   24792 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
   24793 ** still works when you do this, but concurrency is reduced since
   24794 ** only a single process can be reading the database at a time.
   24795 **
   24796 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
   24797 ** compiling for VXWORKS.
   24798 */
   24799 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   24800 
   24801 /*
   24802 ** Retry flock() calls that fail with EINTR
   24803 */
   24804 #ifdef EINTR
   24805 static int robust_flock(int fd, int op){
   24806   int rc;
   24807   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
   24808   return rc;
   24809 }
   24810 #else
   24811 # define robust_flock(a,b) flock(a,b)
   24812 #endif
   24813 
   24814 
   24815 /*
   24816 ** This routine checks if there is a RESERVED lock held on the specified
   24817 ** file by this or any other process. If such a lock is held, set *pResOut
   24818 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   24819 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   24820 */
   24821 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   24822   int rc = SQLITE_OK;
   24823   int reserved = 0;
   24824   unixFile *pFile = (unixFile*)id;
   24825 
   24826   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   24827 
   24828   assert( pFile );
   24829 
   24830   /* Check if a thread in this process holds such a lock */
   24831   if( pFile->eFileLock>SHARED_LOCK ){
   24832     reserved = 1;
   24833   }
   24834 
   24835   /* Otherwise see if some other process holds it. */
   24836   if( !reserved ){
   24837     /* attempt to get the lock */
   24838     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
   24839     if( !lrc ){
   24840       /* got the lock, unlock it */
   24841       lrc = robust_flock(pFile->h, LOCK_UN);
   24842       if ( lrc ) {
   24843         int tErrno = errno;
   24844         /* unlock failed with an error */
   24845         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24846         if( IS_LOCK_ERROR(lrc) ){
   24847           pFile->lastErrno = tErrno;
   24848           rc = lrc;
   24849         }
   24850       }
   24851     } else {
   24852       int tErrno = errno;
   24853       reserved = 1;
   24854       /* someone else might have it reserved */
   24855       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24856       if( IS_LOCK_ERROR(lrc) ){
   24857         pFile->lastErrno = tErrno;
   24858         rc = lrc;
   24859       }
   24860     }
   24861   }
   24862   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
   24863 
   24864 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   24865   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   24866     rc = SQLITE_OK;
   24867     reserved=1;
   24868   }
   24869 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   24870   *pResOut = reserved;
   24871   return rc;
   24872 }
   24873 
   24874 /*
   24875 ** Lock the file with the lock specified by parameter eFileLock - one
   24876 ** of the following:
   24877 **
   24878 **     (1) SHARED_LOCK
   24879 **     (2) RESERVED_LOCK
   24880 **     (3) PENDING_LOCK
   24881 **     (4) EXCLUSIVE_LOCK
   24882 **
   24883 ** Sometimes when requesting one lock state, additional lock states
   24884 ** are inserted in between.  The locking might fail on one of the later
   24885 ** transitions leaving the lock state different from what it started but
   24886 ** still short of its goal.  The following chart shows the allowed
   24887 ** transitions and the inserted intermediate states:
   24888 **
   24889 **    UNLOCKED -> SHARED
   24890 **    SHARED -> RESERVED
   24891 **    SHARED -> (PENDING) -> EXCLUSIVE
   24892 **    RESERVED -> (PENDING) -> EXCLUSIVE
   24893 **    PENDING -> EXCLUSIVE
   24894 **
   24895 ** flock() only really support EXCLUSIVE locks.  We track intermediate
   24896 ** lock states in the sqlite3_file structure, but all locks SHARED or
   24897 ** above are really EXCLUSIVE locks and exclude all other processes from
   24898 ** access the file.
   24899 **
   24900 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   24901 ** routine to lower a locking level.
   24902 */
   24903 static int flockLock(sqlite3_file *id, int eFileLock) {
   24904   int rc = SQLITE_OK;
   24905   unixFile *pFile = (unixFile*)id;
   24906 
   24907   assert( pFile );
   24908 
   24909   /* if we already have a lock, it is exclusive.
   24910   ** Just adjust level and punt on outta here. */
   24911   if (pFile->eFileLock > NO_LOCK) {
   24912     pFile->eFileLock = eFileLock;
   24913     return SQLITE_OK;
   24914   }
   24915 
   24916   /* grab an exclusive lock */
   24917 
   24918   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
   24919     int tErrno = errno;
   24920     /* didn't get, must be busy */
   24921     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
   24922     if( IS_LOCK_ERROR(rc) ){
   24923       pFile->lastErrno = tErrno;
   24924     }
   24925   } else {
   24926     /* got it, set the type and return ok */
   24927     pFile->eFileLock = eFileLock;
   24928   }
   24929   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
   24930            rc==SQLITE_OK ? "ok" : "failed"));
   24931 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   24932   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
   24933     rc = SQLITE_BUSY;
   24934   }
   24935 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   24936   return rc;
   24937 }
   24938 
   24939 
   24940 /*
   24941 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   24942 ** must be either NO_LOCK or SHARED_LOCK.
   24943 **
   24944 ** If the locking level of the file descriptor is already at or below
   24945 ** the requested locking level, this routine is a no-op.
   24946 */
   24947 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   24948   unixFile *pFile = (unixFile*)id;
   24949 
   24950   assert( pFile );
   24951   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
   24952            pFile->eFileLock, getpid()));
   24953   assert( eFileLock<=SHARED_LOCK );
   24954 
   24955   /* no-op if possible */
   24956   if( pFile->eFileLock==eFileLock ){
   24957     return SQLITE_OK;
   24958   }
   24959 
   24960   /* shared can just be set because we always have an exclusive */
   24961   if (eFileLock==SHARED_LOCK) {
   24962     pFile->eFileLock = eFileLock;
   24963     return SQLITE_OK;
   24964   }
   24965 
   24966   /* no, really, unlock. */
   24967   int rc = robust_flock(pFile->h, LOCK_UN);
   24968   if (rc) {
   24969     int r, tErrno = errno;
   24970     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   24971     if( IS_LOCK_ERROR(r) ){
   24972       pFile->lastErrno = tErrno;
   24973     }
   24974 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   24975     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
   24976       r = SQLITE_BUSY;
   24977     }
   24978 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
   24979 
   24980     return r;
   24981   } else {
   24982     pFile->eFileLock = NO_LOCK;
   24983     return SQLITE_OK;
   24984   }
   24985 }
   24986 
   24987 /*
   24988 ** Close a file.
   24989 */
   24990 static int flockClose(sqlite3_file *id) {
   24991   if( id ){
   24992     flockUnlock(id, NO_LOCK);
   24993   }
   24994   return closeUnixFile(id);
   24995 }
   24996 
   24997 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
   24998 
   24999 /******************* End of the flock lock implementation *********************
   25000 ******************************************************************************/
   25001 
   25002 /******************************************************************************
   25003 ************************ Begin Named Semaphore Locking ************************
   25004 **
   25005 ** Named semaphore locking is only supported on VxWorks.
   25006 **
   25007 ** Semaphore locking is like dot-lock and flock in that it really only
   25008 ** supports EXCLUSIVE locking.  Only a single process can read or write
   25009 ** the database file at a time.  This reduces potential concurrency, but
   25010 ** makes the lock implementation much easier.
   25011 */
   25012 #if OS_VXWORKS
   25013 
   25014 /*
   25015 ** This routine checks if there is a RESERVED lock held on the specified
   25016 ** file by this or any other process. If such a lock is held, set *pResOut
   25017 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   25018 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   25019 */
   25020 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
   25021   int rc = SQLITE_OK;
   25022   int reserved = 0;
   25023   unixFile *pFile = (unixFile*)id;
   25024 
   25025   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   25026 
   25027   assert( pFile );
   25028 
   25029   /* Check if a thread in this process holds such a lock */
   25030   if( pFile->eFileLock>SHARED_LOCK ){
   25031     reserved = 1;
   25032   }
   25033 
   25034   /* Otherwise see if some other process holds it. */
   25035   if( !reserved ){
   25036     sem_t *pSem = pFile->pInode->pSem;
   25037     struct stat statBuf;
   25038 
   25039     if( sem_trywait(pSem)==-1 ){
   25040       int tErrno = errno;
   25041       if( EAGAIN != tErrno ){
   25042         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
   25043         pFile->lastErrno = tErrno;
   25044       } else {
   25045         /* someone else has the lock when we are in NO_LOCK */
   25046         reserved = (pFile->eFileLock < SHARED_LOCK);
   25047       }
   25048     }else{
   25049       /* we could have it if we want it */
   25050       sem_post(pSem);
   25051     }
   25052   }
   25053   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
   25054 
   25055   *pResOut = reserved;
   25056   return rc;
   25057 }
   25058 
   25059 /*
   25060 ** Lock the file with the lock specified by parameter eFileLock - one
   25061 ** of the following:
   25062 **
   25063 **     (1) SHARED_LOCK
   25064 **     (2) RESERVED_LOCK
   25065 **     (3) PENDING_LOCK
   25066 **     (4) EXCLUSIVE_LOCK
   25067 **
   25068 ** Sometimes when requesting one lock state, additional lock states
   25069 ** are inserted in between.  The locking might fail on one of the later
   25070 ** transitions leaving the lock state different from what it started but
   25071 ** still short of its goal.  The following chart shows the allowed
   25072 ** transitions and the inserted intermediate states:
   25073 **
   25074 **    UNLOCKED -> SHARED
   25075 **    SHARED -> RESERVED
   25076 **    SHARED -> (PENDING) -> EXCLUSIVE
   25077 **    RESERVED -> (PENDING) -> EXCLUSIVE
   25078 **    PENDING -> EXCLUSIVE
   25079 **
   25080 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
   25081 ** lock states in the sqlite3_file structure, but all locks SHARED or
   25082 ** above are really EXCLUSIVE locks and exclude all other processes from
   25083 ** access the file.
   25084 **
   25085 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   25086 ** routine to lower a locking level.
   25087 */
   25088 static int semLock(sqlite3_file *id, int eFileLock) {
   25089   unixFile *pFile = (unixFile*)id;
   25090   int fd;
   25091   sem_t *pSem = pFile->pInode->pSem;
   25092   int rc = SQLITE_OK;
   25093 
   25094   /* if we already have a lock, it is exclusive.
   25095   ** Just adjust level and punt on outta here. */
   25096   if (pFile->eFileLock > NO_LOCK) {
   25097     pFile->eFileLock = eFileLock;
   25098     rc = SQLITE_OK;
   25099     goto sem_end_lock;
   25100   }
   25101 
   25102   /* lock semaphore now but bail out when already locked. */
   25103   if( sem_trywait(pSem)==-1 ){
   25104     rc = SQLITE_BUSY;
   25105     goto sem_end_lock;
   25106   }
   25107 
   25108   /* got it, set the type and return ok */
   25109   pFile->eFileLock = eFileLock;
   25110 
   25111  sem_end_lock:
   25112   return rc;
   25113 }
   25114 
   25115 /*
   25116 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   25117 ** must be either NO_LOCK or SHARED_LOCK.
   25118 **
   25119 ** If the locking level of the file descriptor is already at or below
   25120 ** the requested locking level, this routine is a no-op.
   25121 */
   25122 static int semUnlock(sqlite3_file *id, int eFileLock) {
   25123   unixFile *pFile = (unixFile*)id;
   25124   sem_t *pSem = pFile->pInode->pSem;
   25125 
   25126   assert( pFile );
   25127   assert( pSem );
   25128   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
   25129 	   pFile->eFileLock, getpid()));
   25130   assert( eFileLock<=SHARED_LOCK );
   25131 
   25132   /* no-op if possible */
   25133   if( pFile->eFileLock==eFileLock ){
   25134     return SQLITE_OK;
   25135   }
   25136 
   25137   /* shared can just be set because we always have an exclusive */
   25138   if (eFileLock==SHARED_LOCK) {
   25139     pFile->eFileLock = eFileLock;
   25140     return SQLITE_OK;
   25141   }
   25142 
   25143   /* no, really unlock. */
   25144   if ( sem_post(pSem)==-1 ) {
   25145     int rc, tErrno = errno;
   25146     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
   25147     if( IS_LOCK_ERROR(rc) ){
   25148       pFile->lastErrno = tErrno;
   25149     }
   25150     return rc;
   25151   }
   25152   pFile->eFileLock = NO_LOCK;
   25153   return SQLITE_OK;
   25154 }
   25155 
   25156 /*
   25157  ** Close a file.
   25158  */
   25159 static int semClose(sqlite3_file *id) {
   25160   if( id ){
   25161     unixFile *pFile = (unixFile*)id;
   25162     semUnlock(id, NO_LOCK);
   25163     assert( pFile );
   25164     unixEnterMutex();
   25165     releaseInodeInfo(pFile);
   25166     unixLeaveMutex();
   25167     closeUnixFile(id);
   25168   }
   25169   return SQLITE_OK;
   25170 }
   25171 
   25172 #endif /* OS_VXWORKS */
   25173 /*
   25174 ** Named semaphore locking is only available on VxWorks.
   25175 **
   25176 *************** End of the named semaphore lock implementation ****************
   25177 ******************************************************************************/
   25178 
   25179 
   25180 /******************************************************************************
   25181 *************************** Begin AFP Locking *********************************
   25182 **
   25183 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
   25184 ** on Apple Macintosh computers - both OS9 and OSX.
   25185 **
   25186 ** Third-party implementations of AFP are available.  But this code here
   25187 ** only works on OSX.
   25188 */
   25189 
   25190 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   25191 /*
   25192 ** The afpLockingContext structure contains all afp lock specific state
   25193 */
   25194 typedef struct afpLockingContext afpLockingContext;
   25195 struct afpLockingContext {
   25196   int reserved;
   25197   const char *dbPath;             /* Name of the open file */
   25198 };
   25199 
   25200 struct ByteRangeLockPB2
   25201 {
   25202   unsigned long long offset;        /* offset to first byte to lock */
   25203   unsigned long long length;        /* nbr of bytes to lock */
   25204   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
   25205   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
   25206   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
   25207   int fd;                           /* file desc to assoc this lock with */
   25208 };
   25209 
   25210 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
   25211 
   25212 /*
   25213 ** This is a utility for setting or clearing a bit-range lock on an
   25214 ** AFP filesystem.
   25215 **
   25216 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
   25217 */
   25218 static int afpSetLock(
   25219   const char *path,              /* Name of the file to be locked or unlocked */
   25220   unixFile *pFile,               /* Open file descriptor on path */
   25221   unsigned long long offset,     /* First byte to be locked */
   25222   unsigned long long length,     /* Number of bytes to lock */
   25223   int setLockFlag                /* True to set lock.  False to clear lock */
   25224 ){
   25225   struct ByteRangeLockPB2 pb;
   25226   int err;
   25227 
   25228   pb.unLockFlag = setLockFlag ? 0 : 1;
   25229   pb.startEndFlag = 0;
   25230   pb.offset = offset;
   25231   pb.length = length;
   25232   pb.fd = pFile->h;
   25233 
   25234   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
   25235     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
   25236     offset, length));
   25237   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
   25238   if ( err==-1 ) {
   25239     int rc;
   25240     int tErrno = errno;
   25241     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
   25242              path, tErrno, strerror(tErrno)));
   25243 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
   25244     rc = SQLITE_BUSY;
   25245 #else
   25246     rc = sqliteErrorFromPosixError(tErrno,
   25247                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
   25248 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
   25249     if( IS_LOCK_ERROR(rc) ){
   25250       pFile->lastErrno = tErrno;
   25251     }
   25252     return rc;
   25253   } else {
   25254     return SQLITE_OK;
   25255   }
   25256 }
   25257 
   25258 /*
   25259 ** This routine checks if there is a RESERVED lock held on the specified
   25260 ** file by this or any other process. If such a lock is held, set *pResOut
   25261 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   25262 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   25263 */
   25264 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   25265   int rc = SQLITE_OK;
   25266   int reserved = 0;
   25267   unixFile *pFile = (unixFile*)id;
   25268 
   25269   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   25270 
   25271   assert( pFile );
   25272   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   25273   if( context->reserved ){
   25274     *pResOut = 1;
   25275     return SQLITE_OK;
   25276   }
   25277   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
   25278 
   25279   /* Check if a thread in this process holds such a lock */
   25280   if( pFile->pInode->eFileLock>SHARED_LOCK ){
   25281     reserved = 1;
   25282   }
   25283 
   25284   /* Otherwise see if some other process holds it.
   25285    */
   25286   if( !reserved ){
   25287     /* lock the RESERVED byte */
   25288     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   25289     if( SQLITE_OK==lrc ){
   25290       /* if we succeeded in taking the reserved lock, unlock it to restore
   25291       ** the original state */
   25292       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   25293     } else {
   25294       /* if we failed to get the lock then someone else must have it */
   25295       reserved = 1;
   25296     }
   25297     if( IS_LOCK_ERROR(lrc) ){
   25298       rc=lrc;
   25299     }
   25300   }
   25301 
   25302   unixLeaveMutex();
   25303   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
   25304 
   25305   *pResOut = reserved;
   25306   return rc;
   25307 }
   25308 
   25309 /*
   25310 ** Lock the file with the lock specified by parameter eFileLock - one
   25311 ** of the following:
   25312 **
   25313 **     (1) SHARED_LOCK
   25314 **     (2) RESERVED_LOCK
   25315 **     (3) PENDING_LOCK
   25316 **     (4) EXCLUSIVE_LOCK
   25317 **
   25318 ** Sometimes when requesting one lock state, additional lock states
   25319 ** are inserted in between.  The locking might fail on one of the later
   25320 ** transitions leaving the lock state different from what it started but
   25321 ** still short of its goal.  The following chart shows the allowed
   25322 ** transitions and the inserted intermediate states:
   25323 **
   25324 **    UNLOCKED -> SHARED
   25325 **    SHARED -> RESERVED
   25326 **    SHARED -> (PENDING) -> EXCLUSIVE
   25327 **    RESERVED -> (PENDING) -> EXCLUSIVE
   25328 **    PENDING -> EXCLUSIVE
   25329 **
   25330 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   25331 ** routine to lower a locking level.
   25332 */
   25333 static int afpLock(sqlite3_file *id, int eFileLock){
   25334   int rc = SQLITE_OK;
   25335   unixFile *pFile = (unixFile*)id;
   25336   unixInodeInfo *pInode = pFile->pInode;
   25337   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   25338 
   25339   assert( pFile );
   25340   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
   25341            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
   25342            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
   25343 
   25344   /* If there is already a lock of this type or more restrictive on the
   25345   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
   25346   ** unixEnterMutex() hasn't been called yet.
   25347   */
   25348   if( pFile->eFileLock>=eFileLock ){
   25349     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
   25350            azFileLock(eFileLock)));
   25351     return SQLITE_OK;
   25352   }
   25353 
   25354   /* Make sure the locking sequence is correct
   25355   **  (1) We never move from unlocked to anything higher than shared lock.
   25356   **  (2) SQLite never explicitly requests a pendig lock.
   25357   **  (3) A shared lock is always held when a reserve lock is requested.
   25358   */
   25359   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   25360   assert( eFileLock!=PENDING_LOCK );
   25361   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
   25362 
   25363   /* This mutex is needed because pFile->pInode is shared across threads
   25364   */
   25365   unixEnterMutex();
   25366   pInode = pFile->pInode;
   25367 
   25368   /* If some thread using this PID has a lock via a different unixFile*
   25369   ** handle that precludes the requested lock, return BUSY.
   25370   */
   25371   if( (pFile->eFileLock!=pInode->eFileLock &&
   25372        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   25373      ){
   25374     rc = SQLITE_BUSY;
   25375     goto afp_end_lock;
   25376   }
   25377 
   25378   /* If a SHARED lock is requested, and some thread using this PID already
   25379   ** has a SHARED or RESERVED lock, then increment reference counts and
   25380   ** return SQLITE_OK.
   25381   */
   25382   if( eFileLock==SHARED_LOCK &&
   25383      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
   25384     assert( eFileLock==SHARED_LOCK );
   25385     assert( pFile->eFileLock==0 );
   25386     assert( pInode->nShared>0 );
   25387     pFile->eFileLock = SHARED_LOCK;
   25388     pInode->nShared++;
   25389     pInode->nLock++;
   25390     goto afp_end_lock;
   25391   }
   25392 
   25393   /* A PENDING lock is needed before acquiring a SHARED lock and before
   25394   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   25395   ** be released.
   25396   */
   25397   if( eFileLock==SHARED_LOCK
   25398       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   25399   ){
   25400     int failed;
   25401     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
   25402     if (failed) {
   25403       rc = failed;
   25404       goto afp_end_lock;
   25405     }
   25406   }
   25407 
   25408   /* If control gets to this point, then actually go ahead and make
   25409   ** operating system calls for the specified lock.
   25410   */
   25411   if( eFileLock==SHARED_LOCK ){
   25412     int lrc1, lrc2, lrc1Errno;
   25413     long lk, mask;
   25414 
   25415     assert( pInode->nShared==0 );
   25416     assert( pInode->eFileLock==0 );
   25417 
   25418     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
   25419     /* Now get the read-lock SHARED_LOCK */
   25420     /* note that the quality of the randomness doesn't matter that much */
   25421     lk = random();
   25422     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
   25423     lrc1 = afpSetLock(context->dbPath, pFile,
   25424           SHARED_FIRST+pInode->sharedByte, 1, 1);
   25425     if( IS_LOCK_ERROR(lrc1) ){
   25426       lrc1Errno = pFile->lastErrno;
   25427     }
   25428     /* Drop the temporary PENDING lock */
   25429     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   25430 
   25431     if( IS_LOCK_ERROR(lrc1) ) {
   25432       pFile->lastErrno = lrc1Errno;
   25433       rc = lrc1;
   25434       goto afp_end_lock;
   25435     } else if( IS_LOCK_ERROR(lrc2) ){
   25436       rc = lrc2;
   25437       goto afp_end_lock;
   25438     } else if( lrc1 != SQLITE_OK ) {
   25439       rc = lrc1;
   25440     } else {
   25441       pFile->eFileLock = SHARED_LOCK;
   25442       pInode->nLock++;
   25443       pInode->nShared = 1;
   25444     }
   25445   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
   25446     /* We are trying for an exclusive lock but another thread in this
   25447      ** same process is still holding a shared lock. */
   25448     rc = SQLITE_BUSY;
   25449   }else{
   25450     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
   25451     ** assumed that there is a SHARED or greater lock on the file
   25452     ** already.
   25453     */
   25454     int failed = 0;
   25455     assert( 0!=pFile->eFileLock );
   25456     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
   25457         /* Acquire a RESERVED lock */
   25458         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
   25459       if( !failed ){
   25460         context->reserved = 1;
   25461       }
   25462     }
   25463     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
   25464       /* Acquire an EXCLUSIVE lock */
   25465 
   25466       /* Remove the shared lock before trying the range.  we'll need to
   25467       ** reestablish the shared lock if we can't get the  afpUnlock
   25468       */
   25469       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
   25470                          pInode->sharedByte, 1, 0)) ){
   25471         int failed2 = SQLITE_OK;
   25472         /* now attemmpt to get the exclusive lock range */
   25473         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
   25474                                SHARED_SIZE, 1);
   25475         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
   25476                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
   25477           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
   25478           ** a critical I/O error
   25479           */
   25480           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
   25481                SQLITE_IOERR_LOCK;
   25482           goto afp_end_lock;
   25483         }
   25484       }else{
   25485         rc = failed;
   25486       }
   25487     }
   25488     if( failed ){
   25489       rc = failed;
   25490     }
   25491   }
   25492 
   25493   if( rc==SQLITE_OK ){
   25494     pFile->eFileLock = eFileLock;
   25495     pInode->eFileLock = eFileLock;
   25496   }else if( eFileLock==EXCLUSIVE_LOCK ){
   25497     pFile->eFileLock = PENDING_LOCK;
   25498     pInode->eFileLock = PENDING_LOCK;
   25499   }
   25500 
   25501 afp_end_lock:
   25502   unixLeaveMutex();
   25503   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
   25504          rc==SQLITE_OK ? "ok" : "failed"));
   25505   return rc;
   25506 }
   25507 
   25508 /*
   25509 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   25510 ** must be either NO_LOCK or SHARED_LOCK.
   25511 **
   25512 ** If the locking level of the file descriptor is already at or below
   25513 ** the requested locking level, this routine is a no-op.
   25514 */
   25515 static int afpUnlock(sqlite3_file *id, int eFileLock) {
   25516   int rc = SQLITE_OK;
   25517   unixFile *pFile = (unixFile*)id;
   25518   unixInodeInfo *pInode;
   25519   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
   25520   int skipShared = 0;
   25521 #ifdef SQLITE_TEST
   25522   int h = pFile->h;
   25523 #endif
   25524 
   25525   assert( pFile );
   25526   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
   25527            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
   25528            getpid()));
   25529 
   25530   assert( eFileLock<=SHARED_LOCK );
   25531   if( pFile->eFileLock<=eFileLock ){
   25532     return SQLITE_OK;
   25533   }
   25534   unixEnterMutex();
   25535   pInode = pFile->pInode;
   25536   assert( pInode->nShared!=0 );
   25537   if( pFile->eFileLock>SHARED_LOCK ){
   25538     assert( pInode->eFileLock==pFile->eFileLock );
   25539     SimulateIOErrorBenign(1);
   25540     SimulateIOError( h=(-1) )
   25541     SimulateIOErrorBenign(0);
   25542 
   25543 #ifndef NDEBUG
   25544     /* When reducing a lock such that other processes can start
   25545     ** reading the database file again, make sure that the
   25546     ** transaction counter was updated if any part of the database
   25547     ** file changed.  If the transaction counter is not updated,
   25548     ** other connections to the same file might not realize that
   25549     ** the file has changed and hence might not know to flush their
   25550     ** cache.  The use of a stale cache can lead to database corruption.
   25551     */
   25552     assert( pFile->inNormalWrite==0
   25553            || pFile->dbUpdate==0
   25554            || pFile->transCntrChng==1 );
   25555     pFile->inNormalWrite = 0;
   25556 #endif
   25557 
   25558     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
   25559       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
   25560       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
   25561         /* only re-establish the shared lock if necessary */
   25562         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   25563         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
   25564       } else {
   25565         skipShared = 1;
   25566       }
   25567     }
   25568     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
   25569       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
   25570     }
   25571     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
   25572       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
   25573       if( !rc ){
   25574         context->reserved = 0;
   25575       }
   25576     }
   25577     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
   25578       pInode->eFileLock = SHARED_LOCK;
   25579     }
   25580   }
   25581   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
   25582 
   25583     /* Decrement the shared lock counter.  Release the lock using an
   25584     ** OS call only when all threads in this same process have released
   25585     ** the lock.
   25586     */
   25587     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
   25588     pInode->nShared--;
   25589     if( pInode->nShared==0 ){
   25590       SimulateIOErrorBenign(1);
   25591       SimulateIOError( h=(-1) )
   25592       SimulateIOErrorBenign(0);
   25593       if( !skipShared ){
   25594         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
   25595       }
   25596       if( !rc ){
   25597         pInode->eFileLock = NO_LOCK;
   25598         pFile->eFileLock = NO_LOCK;
   25599       }
   25600     }
   25601     if( rc==SQLITE_OK ){
   25602       pInode->nLock--;
   25603       assert( pInode->nLock>=0 );
   25604       if( pInode->nLock==0 ){
   25605         rc = closePendingFds(pFile);
   25606       }
   25607     }
   25608   }
   25609 
   25610   unixLeaveMutex();
   25611   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
   25612   return rc;
   25613 }
   25614 
   25615 /*
   25616 ** Close a file & cleanup AFP specific locking context
   25617 */
   25618 static int afpClose(sqlite3_file *id) {
   25619   int rc = SQLITE_OK;
   25620   if( id ){
   25621     unixFile *pFile = (unixFile*)id;
   25622     afpUnlock(id, NO_LOCK);
   25623     unixEnterMutex();
   25624     if( pFile->pInode && pFile->pInode->nLock ){
   25625       /* If there are outstanding locks, do not actually close the file just
   25626       ** yet because that would clear those locks.  Instead, add the file
   25627       ** descriptor to pInode->aPending.  It will be automatically closed when
   25628       ** the last lock is cleared.
   25629       */
   25630       setPendingFd(pFile);
   25631     }
   25632     releaseInodeInfo(pFile);
   25633     sqlite3_free(pFile->lockingContext);
   25634     rc = closeUnixFile(id);
   25635     unixLeaveMutex();
   25636   }
   25637   return rc;
   25638 }
   25639 
   25640 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   25641 /*
   25642 ** The code above is the AFP lock implementation.  The code is specific
   25643 ** to MacOSX and does not work on other unix platforms.  No alternative
   25644 ** is available.  If you don't compile for a mac, then the "unix-afp"
   25645 ** VFS is not available.
   25646 **
   25647 ********************* End of the AFP lock implementation **********************
   25648 ******************************************************************************/
   25649 
   25650 /******************************************************************************
   25651 *************************** Begin NFS Locking ********************************/
   25652 
   25653 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   25654 /*
   25655  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   25656  ** must be either NO_LOCK or SHARED_LOCK.
   25657  **
   25658  ** If the locking level of the file descriptor is already at or below
   25659  ** the requested locking level, this routine is a no-op.
   25660  */
   25661 static int nfsUnlock(sqlite3_file *id, int eFileLock){
   25662   return _posixUnlock(id, eFileLock, 1);
   25663 }
   25664 
   25665 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   25666 /*
   25667 ** The code above is the NFS lock implementation.  The code is specific
   25668 ** to MacOSX and does not work on other unix platforms.  No alternative
   25669 ** is available.
   25670 **
   25671 ********************* End of the NFS lock implementation **********************
   25672 ******************************************************************************/
   25673 
   25674 /******************************************************************************
   25675 **************** Non-locking sqlite3_file methods *****************************
   25676 **
   25677 ** The next division contains implementations for all methods of the
   25678 ** sqlite3_file object other than the locking methods.  The locking
   25679 ** methods were defined in divisions above (one locking method per
   25680 ** division).  Those methods that are common to all locking modes
   25681 ** are gather together into this division.
   25682 */
   25683 
   25684 /*
   25685 ** Seek to the offset passed as the second argument, then read cnt
   25686 ** bytes into pBuf. Return the number of bytes actually read.
   25687 **
   25688 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
   25689 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
   25690 ** one system to another.  Since SQLite does not define USE_PREAD
   25691 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
   25692 ** See tickets #2741 and #2681.
   25693 **
   25694 ** To avoid stomping the errno value on a failed read the lastErrno value
   25695 ** is set before returning.
   25696 */
   25697 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
   25698   int got;
   25699 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   25700   i64 newOffset;
   25701 #endif
   25702   TIMER_START;
   25703 #if defined(USE_PREAD)
   25704   do{ got = pread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   25705   SimulateIOError( got = -1 );
   25706 #elif defined(USE_PREAD64)
   25707   do{ got = pread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   25708   SimulateIOError( got = -1 );
   25709 #else
   25710   newOffset = lseek(id->h, offset, SEEK_SET);
   25711   SimulateIOError( newOffset-- );
   25712   if( newOffset!=offset ){
   25713     if( newOffset == -1 ){
   25714       ((unixFile*)id)->lastErrno = errno;
   25715     }else{
   25716       ((unixFile*)id)->lastErrno = 0;
   25717     }
   25718     return -1;
   25719   }
   25720   do{ got = read(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
   25721 #endif
   25722   TIMER_END;
   25723   if( got<0 ){
   25724     ((unixFile*)id)->lastErrno = errno;
   25725   }
   25726   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   25727   return got;
   25728 }
   25729 
   25730 /*
   25731 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   25732 ** bytes were read successfully and SQLITE_IOERR if anything goes
   25733 ** wrong.
   25734 */
   25735 static int unixRead(
   25736   sqlite3_file *id,
   25737   void *pBuf,
   25738   int amt,
   25739   sqlite3_int64 offset
   25740 ){
   25741   unixFile *pFile = (unixFile *)id;
   25742   int got;
   25743   assert( id );
   25744 
   25745   /* If this is a database file (not a journal, master-journal or temp
   25746   ** file), the bytes in the locking range should never be read or written. */
   25747 #if 0
   25748   assert( pFile->pUnused==0
   25749        || offset>=PENDING_BYTE+512
   25750        || offset+amt<=PENDING_BYTE
   25751   );
   25752 #endif
   25753 
   25754   got = seekAndRead(pFile, offset, pBuf, amt);
   25755   if( got==amt ){
   25756     return SQLITE_OK;
   25757   }else if( got<0 ){
   25758     /* lastErrno set by seekAndRead */
   25759     return SQLITE_IOERR_READ;
   25760   }else{
   25761     pFile->lastErrno = 0; /* not a system error */
   25762     /* Unread parts of the buffer must be zero-filled */
   25763     memset(&((char*)pBuf)[got], 0, amt-got);
   25764     return SQLITE_IOERR_SHORT_READ;
   25765   }
   25766 }
   25767 
   25768 /*
   25769 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
   25770 ** Return the number of bytes actually read.  Update the offset.
   25771 **
   25772 ** To avoid stomping the errno value on a failed write the lastErrno value
   25773 ** is set before returning.
   25774 */
   25775 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
   25776   int got;
   25777 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
   25778   i64 newOffset;
   25779 #endif
   25780   TIMER_START;
   25781 #if defined(USE_PREAD)
   25782   do{ got = pwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   25783 #elif defined(USE_PREAD64)
   25784   do{ got = pwrite64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
   25785 #else
   25786   newOffset = lseek(id->h, offset, SEEK_SET);
   25787   if( newOffset!=offset ){
   25788     if( newOffset == -1 ){
   25789       ((unixFile*)id)->lastErrno = errno;
   25790     }else{
   25791       ((unixFile*)id)->lastErrno = 0;
   25792     }
   25793     return -1;
   25794   }
   25795   do{ got = write(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
   25796 #endif
   25797   TIMER_END;
   25798   if( got<0 ){
   25799     ((unixFile*)id)->lastErrno = errno;
   25800   }
   25801 
   25802   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
   25803   return got;
   25804 }
   25805 
   25806 
   25807 /*
   25808 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   25809 ** or some other error code on failure.
   25810 */
   25811 static int unixWrite(
   25812   sqlite3_file *id,
   25813   const void *pBuf,
   25814   int amt,
   25815   sqlite3_int64 offset
   25816 ){
   25817   unixFile *pFile = (unixFile*)id;
   25818   int wrote = 0;
   25819   assert( id );
   25820   assert( amt>0 );
   25821 
   25822   /* If this is a database file (not a journal, master-journal or temp
   25823   ** file), the bytes in the locking range should never be read or written. */
   25824 #if 0
   25825   assert( pFile->pUnused==0
   25826        || offset>=PENDING_BYTE+512
   25827        || offset+amt<=PENDING_BYTE
   25828   );
   25829 #endif
   25830 
   25831 #ifndef NDEBUG
   25832   /* If we are doing a normal write to a database file (as opposed to
   25833   ** doing a hot-journal rollback or a write to some file other than a
   25834   ** normal database file) then record the fact that the database
   25835   ** has changed.  If the transaction counter is modified, record that
   25836   ** fact too.
   25837   */
   25838   if( pFile->inNormalWrite ){
   25839     pFile->dbUpdate = 1;  /* The database has been modified */
   25840     if( offset<=24 && offset+amt>=27 ){
   25841       int rc;
   25842       char oldCntr[4];
   25843       SimulateIOErrorBenign(1);
   25844       rc = seekAndRead(pFile, 24, oldCntr, 4);
   25845       SimulateIOErrorBenign(0);
   25846       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
   25847         pFile->transCntrChng = 1;  /* The transaction counter has changed */
   25848       }
   25849     }
   25850   }
   25851 #endif
   25852 
   25853   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
   25854     amt -= wrote;
   25855     offset += wrote;
   25856     pBuf = &((char*)pBuf)[wrote];
   25857   }
   25858   SimulateIOError(( wrote=(-1), amt=1 ));
   25859   SimulateDiskfullError(( wrote=0, amt=1 ));
   25860 
   25861   if( amt>0 ){
   25862     if( wrote<0 ){
   25863       /* lastErrno set by seekAndWrite */
   25864       return SQLITE_IOERR_WRITE;
   25865     }else{
   25866       pFile->lastErrno = 0; /* not a system error */
   25867       return SQLITE_FULL;
   25868     }
   25869   }
   25870 
   25871   return SQLITE_OK;
   25872 }
   25873 
   25874 #ifdef SQLITE_TEST
   25875 /*
   25876 ** Count the number of fullsyncs and normal syncs.  This is used to test
   25877 ** that syncs and fullsyncs are occurring at the right times.
   25878 */
   25879 SQLITE_API int sqlite3_sync_count = 0;
   25880 SQLITE_API int sqlite3_fullsync_count = 0;
   25881 #endif
   25882 
   25883 /*
   25884 ** We do not trust systems to provide a working fdatasync().  Some do.
   25885 ** Others do no.  To be safe, we will stick with the (slower) fsync().
   25886 ** If you know that your system does support fdatasync() correctly,
   25887 ** then simply compile with -Dfdatasync=fdatasync
   25888 */
   25889 #if !defined(fdatasync) && !defined(__linux__)
   25890 # define fdatasync fsync
   25891 #endif
   25892 
   25893 /*
   25894 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
   25895 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
   25896 ** only available on Mac OS X.  But that could change.
   25897 */
   25898 #ifdef F_FULLFSYNC
   25899 # define HAVE_FULLFSYNC 1
   25900 #else
   25901 # define HAVE_FULLFSYNC 0
   25902 #endif
   25903 
   25904 
   25905 /*
   25906 ** The fsync() system call does not work as advertised on many
   25907 ** unix systems.  The following procedure is an attempt to make
   25908 ** it work better.
   25909 **
   25910 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
   25911 ** for testing when we want to run through the test suite quickly.
   25912 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
   25913 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
   25914 ** or power failure will likely corrupt the database file.
   25915 **
   25916 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
   25917 ** The idea behind dataOnly is that it should only write the file content
   25918 ** to disk, not the inode.  We only set dataOnly if the file size is
   25919 ** unchanged since the file size is part of the inode.  However,
   25920 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
   25921 ** file size has changed.  The only real difference between fdatasync()
   25922 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
   25923 ** inode if the mtime or owner or other inode attributes have changed.
   25924 ** We only care about the file size, not the other file attributes, so
   25925 ** as far as SQLite is concerned, an fdatasync() is always adequate.
   25926 ** So, we always use fdatasync() if it is available, regardless of
   25927 ** the value of the dataOnly flag.
   25928 */
   25929 static int full_fsync(int fd, int fullSync, int dataOnly){
   25930   int rc;
   25931 
   25932   /* The following "ifdef/elif/else/" block has the same structure as
   25933   ** the one below. It is replicated here solely to avoid cluttering
   25934   ** up the real code with the UNUSED_PARAMETER() macros.
   25935   */
   25936 #ifdef SQLITE_NO_SYNC
   25937   UNUSED_PARAMETER(fd);
   25938   UNUSED_PARAMETER(fullSync);
   25939   UNUSED_PARAMETER(dataOnly);
   25940 #elif HAVE_FULLFSYNC
   25941   UNUSED_PARAMETER(dataOnly);
   25942 #else
   25943   UNUSED_PARAMETER(fullSync);
   25944   UNUSED_PARAMETER(dataOnly);
   25945 #endif
   25946 
   25947   /* Record the number of times that we do a normal fsync() and
   25948   ** FULLSYNC.  This is used during testing to verify that this procedure
   25949   ** gets called with the correct arguments.
   25950   */
   25951 #ifdef SQLITE_TEST
   25952   if( fullSync ) sqlite3_fullsync_count++;
   25953   sqlite3_sync_count++;
   25954 #endif
   25955 
   25956   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   25957   ** no-op
   25958   */
   25959 #ifdef SQLITE_NO_SYNC
   25960   rc = SQLITE_OK;
   25961 #elif HAVE_FULLFSYNC
   25962   if( fullSync ){
   25963     rc = fcntl(fd, F_FULLFSYNC, 0);
   25964   }else{
   25965     rc = 1;
   25966   }
   25967   /* If the FULLFSYNC failed, fall back to attempting an fsync().
   25968   ** It shouldn't be possible for fullfsync to fail on the local
   25969   ** file system (on OSX), so failure indicates that FULLFSYNC
   25970   ** isn't supported for this file system. So, attempt an fsync
   25971   ** and (for now) ignore the overhead of a superfluous fcntl call.
   25972   ** It'd be better to detect fullfsync support once and avoid
   25973   ** the fcntl call every time sync is called.
   25974   */
   25975   if( rc ) rc = fsync(fd);
   25976 
   25977 #elif defined(__APPLE__)
   25978   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
   25979   ** so currently we default to the macro that redefines fdatasync to fsync
   25980   */
   25981   rc = fsync(fd);
   25982 #else
   25983   rc = fdatasync(fd);
   25984 #if OS_VXWORKS
   25985   if( rc==-1 && errno==ENOTSUP ){
   25986     rc = fsync(fd);
   25987   }
   25988 #endif /* OS_VXWORKS */
   25989 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
   25990 
   25991   if( OS_VXWORKS && rc!= -1 ){
   25992     rc = 0;
   25993   }
   25994   return rc;
   25995 }
   25996 
   25997 /*
   25998 ** Make sure all writes to a particular file are committed to disk.
   25999 **
   26000 ** If dataOnly==0 then both the file itself and its metadata (file
   26001 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
   26002 ** file data is synced.
   26003 **
   26004 ** Under Unix, also make sure that the directory entry for the file
   26005 ** has been created by fsync-ing the directory that contains the file.
   26006 ** If we do not do this and we encounter a power failure, the directory
   26007 ** entry for the journal might not exist after we reboot.  The next
   26008 ** SQLite to access the file will not know that the journal exists (because
   26009 ** the directory entry for the journal was never created) and the transaction
   26010 ** will not roll back - possibly leading to database corruption.
   26011 */
   26012 static int unixSync(sqlite3_file *id, int flags){
   26013   int rc;
   26014   unixFile *pFile = (unixFile*)id;
   26015 
   26016   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
   26017   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
   26018 
   26019   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   26020   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   26021       || (flags&0x0F)==SQLITE_SYNC_FULL
   26022   );
   26023 
   26024   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   26025   ** line is to test that doing so does not cause any problems.
   26026   */
   26027   SimulateDiskfullError( return SQLITE_FULL );
   26028 
   26029   assert( pFile );
   26030   OSTRACE(("SYNC    %-3d\n", pFile->h));
   26031   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
   26032   SimulateIOError( rc=1 );
   26033   if( rc ){
   26034     pFile->lastErrno = errno;
   26035     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
   26036   }
   26037   if( pFile->dirfd>=0 ){
   26038     int err;
   26039     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
   26040             HAVE_FULLFSYNC, isFullsync));
   26041 #ifndef SQLITE_DISABLE_DIRSYNC
   26042     /* The directory sync is only attempted if full_fsync is
   26043     ** turned off or unavailable.  If a full_fsync occurred above,
   26044     ** then the directory sync is superfluous.
   26045     */
   26046     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
   26047        /*
   26048        ** We have received multiple reports of fsync() returning
   26049        ** errors when applied to directories on certain file systems.
   26050        ** A failed directory sync is not a big deal.  So it seems
   26051        ** better to ignore the error.  Ticket #1657
   26052        */
   26053        /* pFile->lastErrno = errno; */
   26054        /* return SQLITE_IOERR; */
   26055     }
   26056 #endif
   26057     err = close(pFile->dirfd); /* Only need to sync once, so close the */
   26058     if( err==0 ){              /* directory when we are done */
   26059       pFile->dirfd = -1;
   26060     }else{
   26061       pFile->lastErrno = errno;
   26062       rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", pFile->zPath);
   26063     }
   26064   }
   26065   return rc;
   26066 }
   26067 
   26068 /*
   26069 ** Truncate an open file to a specified size
   26070 */
   26071 static int unixTruncate(sqlite3_file *id, i64 nByte){
   26072   unixFile *pFile = (unixFile *)id;
   26073   int rc;
   26074   assert( pFile );
   26075   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
   26076 
   26077   /* If the user has configured a chunk-size for this file, truncate the
   26078   ** file so that it consists of an integer number of chunks (i.e. the
   26079   ** actual file size after the operation may be larger than the requested
   26080   ** size).
   26081   */
   26082   if( pFile->szChunk ){
   26083     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   26084   }
   26085 
   26086   rc = robust_ftruncate(pFile->h, (off_t)nByte);
   26087   if( rc ){
   26088     pFile->lastErrno = errno;
   26089     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   26090   }else{
   26091 #ifndef NDEBUG
   26092     /* If we are doing a normal write to a database file (as opposed to
   26093     ** doing a hot-journal rollback or a write to some file other than a
   26094     ** normal database file) and we truncate the file to zero length,
   26095     ** that effectively updates the change counter.  This might happen
   26096     ** when restoring a database using the backup API from a zero-length
   26097     ** source.
   26098     */
   26099     if( pFile->inNormalWrite && nByte==0 ){
   26100       pFile->transCntrChng = 1;
   26101     }
   26102 #endif
   26103 
   26104     return SQLITE_OK;
   26105   }
   26106 }
   26107 
   26108 /*
   26109 ** Determine the current size of a file in bytes
   26110 */
   26111 static int unixFileSize(sqlite3_file *id, i64 *pSize){
   26112   int rc;
   26113   struct stat buf;
   26114   assert( id );
   26115   rc = fstat(((unixFile*)id)->h, &buf);
   26116   SimulateIOError( rc=1 );
   26117   if( rc!=0 ){
   26118     ((unixFile*)id)->lastErrno = errno;
   26119     return SQLITE_IOERR_FSTAT;
   26120   }
   26121   *pSize = buf.st_size;
   26122 
   26123   /* When opening a zero-size database, the findInodeInfo() procedure
   26124   ** writes a single byte into that file in order to work around a bug
   26125   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
   26126   ** layers, we need to report this file size as zero even though it is
   26127   ** really 1.   Ticket #3260.
   26128   */
   26129   if( *pSize==1 ) *pSize = 0;
   26130 
   26131 
   26132   return SQLITE_OK;
   26133 }
   26134 
   26135 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   26136 /*
   26137 ** Handler for proxy-locking file-control verbs.  Defined below in the
   26138 ** proxying locking division.
   26139 */
   26140 static int proxyFileControl(sqlite3_file*,int,void*);
   26141 #endif
   26142 
   26143 /*
   26144 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
   26145 ** file-control operation.
   26146 **
   26147 ** If the user has configured a chunk-size for this file, it could be
   26148 ** that the file needs to be extended at this point. Otherwise, the
   26149 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
   26150 */
   26151 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   26152   if( pFile->szChunk ){
   26153     i64 nSize;                    /* Required file size */
   26154     struct stat buf;              /* Used to hold return values of fstat() */
   26155 
   26156     if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
   26157 
   26158     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
   26159     if( nSize>(i64)buf.st_size ){
   26160 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
   26161       int rc;
   26162       do{
   26163         rc = posix_fallocate(pFile-.h, buf.st_size, nSize-buf.st_size;
   26164       }while( rc<0 && errno=EINTR );
   26165       if( rc ) return SQLITE_IOERR_WRITE;
   26166 #else
   26167       /* If the OS does not have posix_fallocate(), fake it. First use
   26168       ** ftruncate() to set the file size, then write a single byte to
   26169       ** the last byte in each block within the extended region. This
   26170       ** is the same technique used by glibc to implement posix_fallocate()
   26171       ** on systems that do not have a real fallocate() system call.
   26172       */
   26173       int nBlk = buf.st_blksize;  /* File-system block size */
   26174       i64 iWrite;                 /* Next offset to write to */
   26175       int nWrite;                 /* Return value from seekAndWrite() */
   26176 
   26177       if( robust_ftruncate(pFile->h, nSize) ){
   26178         pFile->lastErrno = errno;
   26179         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
   26180       }
   26181       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
   26182       do {
   26183         nWrite = seekAndWrite(pFile, iWrite, "", 1);
   26184         iWrite += nBlk;
   26185       } while( nWrite==1 && iWrite<nSize );
   26186       if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
   26187 #endif
   26188     }
   26189   }
   26190 
   26191   return SQLITE_OK;
   26192 }
   26193 
   26194 /*
   26195 ** Information and control of an open file handle.
   26196 */
   26197 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
   26198   switch( op ){
   26199     case SQLITE_FCNTL_LOCKSTATE: {
   26200       *(int*)pArg = ((unixFile*)id)->eFileLock;
   26201       return SQLITE_OK;
   26202     }
   26203     case SQLITE_LAST_ERRNO: {
   26204       *(int*)pArg = ((unixFile*)id)->lastErrno;
   26205       return SQLITE_OK;
   26206     }
   26207     case SQLITE_FCNTL_CHUNK_SIZE: {
   26208       ((unixFile*)id)->szChunk = *(int *)pArg;
   26209       return SQLITE_OK;
   26210     }
   26211     case SQLITE_FCNTL_SIZE_HINT: {
   26212       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
   26213     }
   26214 #ifndef NDEBUG
   26215     /* The pager calls this method to signal that it has done
   26216     ** a rollback and that the database is therefore unchanged and
   26217     ** it hence it is OK for the transaction change counter to be
   26218     ** unchanged.
   26219     */
   26220     case SQLITE_FCNTL_DB_UNCHANGED: {
   26221       ((unixFile*)id)->dbUpdate = 0;
   26222       return SQLITE_OK;
   26223     }
   26224 #endif
   26225 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   26226     case SQLITE_SET_LOCKPROXYFILE:
   26227     case SQLITE_GET_LOCKPROXYFILE: {
   26228       return proxyFileControl(id,op,pArg);
   26229     }
   26230 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
   26231   }
   26232   return SQLITE_ERROR;
   26233 }
   26234 
   26235 /*
   26236 ** Return the sector size in bytes of the underlying block device for
   26237 ** the specified file. This is almost always 512 bytes, but may be
   26238 ** larger for some devices.
   26239 **
   26240 ** SQLite code assumes this function cannot fail. It also assumes that
   26241 ** if two files are created in the same file-system directory (i.e.
   26242 ** a database and its journal file) that the sector size will be the
   26243 ** same for both.
   26244 */
   26245 static int unixSectorSize(sqlite3_file *NotUsed){
   26246   UNUSED_PARAMETER(NotUsed);
   26247   return SQLITE_DEFAULT_SECTOR_SIZE;
   26248 }
   26249 
   26250 /*
   26251 ** Return the device characteristics for the file. This is always 0 for unix.
   26252 */
   26253 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
   26254   UNUSED_PARAMETER(NotUsed);
   26255   return 0;
   26256 }
   26257 
   26258 #ifndef SQLITE_OMIT_WAL
   26259 
   26260 
   26261 /*
   26262 ** Object used to represent an shared memory buffer.
   26263 **
   26264 ** When multiple threads all reference the same wal-index, each thread
   26265 ** has its own unixShm object, but they all point to a single instance
   26266 ** of this unixShmNode object.  In other words, each wal-index is opened
   26267 ** only once per process.
   26268 **
   26269 ** Each unixShmNode object is connected to a single unixInodeInfo object.
   26270 ** We could coalesce this object into unixInodeInfo, but that would mean
   26271 ** every open file that does not use shared memory (in other words, most
   26272 ** open files) would have to carry around this extra information.  So
   26273 ** the unixInodeInfo object contains a pointer to this unixShmNode object
   26274 ** and the unixShmNode object is created only when needed.
   26275 **
   26276 ** unixMutexHeld() must be true when creating or destroying
   26277 ** this object or while reading or writing the following fields:
   26278 **
   26279 **      nRef
   26280 **
   26281 ** The following fields are read-only after the object is created:
   26282 **
   26283 **      fid
   26284 **      zFilename
   26285 **
   26286 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
   26287 ** unixMutexHeld() is true when reading or writing any other field
   26288 ** in this structure.
   26289 */
   26290 struct unixShmNode {
   26291   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
   26292   sqlite3_mutex *mutex;      /* Mutex to access this object */
   26293   char *zFilename;           /* Name of the mmapped file */
   26294   int h;                     /* Open file descriptor */
   26295   int szRegion;              /* Size of shared-memory regions */
   26296   int nRegion;               /* Size of array apRegion */
   26297   char **apRegion;           /* Array of mapped shared-memory regions */
   26298   int nRef;                  /* Number of unixShm objects pointing to this */
   26299   unixShm *pFirst;           /* All unixShm objects pointing to this */
   26300 #ifdef SQLITE_DEBUG
   26301   u8 exclMask;               /* Mask of exclusive locks held */
   26302   u8 sharedMask;             /* Mask of shared locks held */
   26303   u8 nextShmId;              /* Next available unixShm.id value */
   26304 #endif
   26305 };
   26306 
   26307 /*
   26308 ** Structure used internally by this VFS to record the state of an
   26309 ** open shared memory connection.
   26310 **
   26311 ** The following fields are initialized when this object is created and
   26312 ** are read-only thereafter:
   26313 **
   26314 **    unixShm.pFile
   26315 **    unixShm.id
   26316 **
   26317 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
   26318 ** while accessing any read/write fields.
   26319 */
   26320 struct unixShm {
   26321   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
   26322   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
   26323   u8 hasMutex;               /* True if holding the unixShmNode mutex */
   26324   u16 sharedMask;            /* Mask of shared locks held */
   26325   u16 exclMask;              /* Mask of exclusive locks held */
   26326 #ifdef SQLITE_DEBUG
   26327   u8 id;                     /* Id of this connection within its unixShmNode */
   26328 #endif
   26329 };
   26330 
   26331 /*
   26332 ** Constants used for locking
   26333 */
   26334 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
   26335 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   26336 
   26337 /*
   26338 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
   26339 **
   26340 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
   26341 ** otherwise.
   26342 */
   26343 static int unixShmSystemLock(
   26344   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
   26345   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
   26346   int ofst,              /* First byte of the locking range */
   26347   int n                  /* Number of bytes to lock */
   26348 ){
   26349   struct flock f;       /* The posix advisory locking structure */
   26350   int rc = SQLITE_OK;   /* Result code form fcntl() */
   26351 
   26352   /* Access to the unixShmNode object is serialized by the caller */
   26353   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
   26354 
   26355   /* Shared locks never span more than one byte */
   26356   assert( n==1 || lockType!=F_RDLCK );
   26357 
   26358   /* Locks are within range */
   26359   assert( n>=1 && n<SQLITE_SHM_NLOCK );
   26360 
   26361   /* Initialize the locking parameters */
   26362   memset(&f, 0, sizeof(f));
   26363   f.l_type = lockType;
   26364   f.l_whence = SEEK_SET;
   26365   f.l_start = ofst;
   26366   f.l_len = n;
   26367 
   26368   rc = fcntl(pShmNode->h, F_SETLK, &f);
   26369   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
   26370 
   26371   /* Update the global lock state and do debug tracing */
   26372 #ifdef SQLITE_DEBUG
   26373   { u16 mask;
   26374   OSTRACE(("SHM-LOCK "));
   26375   mask = (1<<(ofst+n)) - (1<<ofst);
   26376   if( rc==SQLITE_OK ){
   26377     if( lockType==F_UNLCK ){
   26378       OSTRACE(("unlock %d ok", ofst));
   26379       pShmNode->exclMask &= ~mask;
   26380       pShmNode->sharedMask &= ~mask;
   26381     }else if( lockType==F_RDLCK ){
   26382       OSTRACE(("read-lock %d ok", ofst));
   26383       pShmNode->exclMask &= ~mask;
   26384       pShmNode->sharedMask |= mask;
   26385     }else{
   26386       assert( lockType==F_WRLCK );
   26387       OSTRACE(("write-lock %d ok", ofst));
   26388       pShmNode->exclMask |= mask;
   26389       pShmNode->sharedMask &= ~mask;
   26390     }
   26391   }else{
   26392     if( lockType==F_UNLCK ){
   26393       OSTRACE(("unlock %d failed", ofst));
   26394     }else if( lockType==F_RDLCK ){
   26395       OSTRACE(("read-lock failed"));
   26396     }else{
   26397       assert( lockType==F_WRLCK );
   26398       OSTRACE(("write-lock %d failed", ofst));
   26399     }
   26400   }
   26401   OSTRACE((" - afterwards %03x,%03x\n",
   26402            pShmNode->sharedMask, pShmNode->exclMask));
   26403   }
   26404 #endif
   26405 
   26406   return rc;
   26407 }
   26408 
   26409 
   26410 /*
   26411 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
   26412 **
   26413 ** This is not a VFS shared-memory method; it is a utility function called
   26414 ** by VFS shared-memory methods.
   26415 */
   26416 static void unixShmPurge(unixFile *pFd){
   26417   unixShmNode *p = pFd->pInode->pShmNode;
   26418   assert( unixMutexHeld() );
   26419   if( p && p->nRef==0 ){
   26420     int i;
   26421     assert( p->pInode==pFd->pInode );
   26422     if( p->mutex ) sqlite3_mutex_free(p->mutex);
   26423     for(i=0; i<p->nRegion; i++){
   26424       munmap(p->apRegion[i], p->szRegion);
   26425     }
   26426     sqlite3_free(p->apRegion);
   26427     if( p->h>=0 ) close(p->h);
   26428     p->pInode->pShmNode = 0;
   26429     sqlite3_free(p);
   26430   }
   26431 }
   26432 
   26433 /*
   26434 ** Open a shared-memory area associated with open database file pDbFd.
   26435 ** This particular implementation uses mmapped files.
   26436 **
   26437 ** The file used to implement shared-memory is in the same directory
   26438 ** as the open database file and has the same name as the open database
   26439 ** file with the "-shm" suffix added.  For example, if the database file
   26440 ** is "/home/user1/config.db" then the file that is created and mmapped
   26441 ** for shared memory will be called "/home/user1/config.db-shm".
   26442 **
   26443 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
   26444 ** some other tmpfs mount. But if a file in a different directory
   26445 ** from the database file is used, then differing access permissions
   26446 ** or a chroot() might cause two different processes on the same
   26447 ** database to end up using different files for shared memory -
   26448 ** meaning that their memory would not really be shared - resulting
   26449 ** in database corruption.  Nevertheless, this tmpfs file usage
   26450 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
   26451 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
   26452 ** option results in an incompatible build of SQLite;  builds of SQLite
   26453 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
   26454 ** same database file at the same time, database corruption will likely
   26455 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
   26456 ** "unsupported" and may go away in a future SQLite release.
   26457 **
   26458 ** When opening a new shared-memory file, if no other instances of that
   26459 ** file are currently open, in this process or in other processes, then
   26460 ** the file must be truncated to zero length or have its header cleared.
   26461 */
   26462 static int unixOpenSharedMemory(unixFile *pDbFd){
   26463   struct unixShm *p = 0;          /* The connection to be opened */
   26464   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
   26465   int rc;                         /* Result code */
   26466   unixInodeInfo *pInode;          /* The inode of fd */
   26467   char *zShmFilename;             /* Name of the file used for SHM */
   26468   int nShmFilename;               /* Size of the SHM filename in bytes */
   26469 
   26470   /* Allocate space for the new unixShm object. */
   26471   p = sqlite3_malloc( sizeof(*p) );
   26472   if( p==0 ) return SQLITE_NOMEM;
   26473   memset(p, 0, sizeof(*p));
   26474   assert( pDbFd->pShm==0 );
   26475 
   26476   /* Check to see if a unixShmNode object already exists. Reuse an existing
   26477   ** one if present. Create a new one if necessary.
   26478   */
   26479   unixEnterMutex();
   26480   pInode = pDbFd->pInode;
   26481   pShmNode = pInode->pShmNode;
   26482   if( pShmNode==0 ){
   26483     struct stat sStat;                 /* fstat() info for database file */
   26484 
   26485     /* Call fstat() to figure out the permissions on the database file. If
   26486     ** a new *-shm file is created, an attempt will be made to create it
   26487     ** with the same permissions. The actual permissions the file is created
   26488     ** with are subject to the current umask setting.
   26489     */
   26490     if( fstat(pDbFd->h, &sStat) ){
   26491       rc = SQLITE_IOERR_FSTAT;
   26492       goto shm_open_err;
   26493     }
   26494 
   26495 #ifdef SQLITE_SHM_DIRECTORY
   26496     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
   26497 #else
   26498     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
   26499 #endif
   26500     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
   26501     if( pShmNode==0 ){
   26502       rc = SQLITE_NOMEM;
   26503       goto shm_open_err;
   26504     }
   26505     memset(pShmNode, 0, sizeof(*pShmNode));
   26506     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
   26507 #ifdef SQLITE_SHM_DIRECTORY
   26508     sqlite3_snprintf(nShmFilename, zShmFilename,
   26509                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
   26510                      (u32)sStat.st_ino, (u32)sStat.st_dev);
   26511 #else
   26512     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
   26513 #endif
   26514     pShmNode->h = -1;
   26515     pDbFd->pInode->pShmNode = pShmNode;
   26516     pShmNode->pInode = pDbFd->pInode;
   26517     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   26518     if( pShmNode->mutex==0 ){
   26519       rc = SQLITE_NOMEM;
   26520       goto shm_open_err;
   26521     }
   26522 
   26523     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
   26524     if( pShmNode->h<0 ){
   26525       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
   26526       goto shm_open_err;
   26527     }
   26528 
   26529     /* Check to see if another process is holding the dead-man switch.
   26530     ** If not, truncate the file to zero length.
   26531     */
   26532     rc = SQLITE_OK;
   26533     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
   26534       if( robust_ftruncate(pShmNode->h, 0) ){
   26535         rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
   26536       }
   26537     }
   26538     if( rc==SQLITE_OK ){
   26539       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
   26540     }
   26541     if( rc ) goto shm_open_err;
   26542   }
   26543 
   26544   /* Make the new connection a child of the unixShmNode */
   26545   p->pShmNode = pShmNode;
   26546 #ifdef SQLITE_DEBUG
   26547   p->id = pShmNode->nextShmId++;
   26548 #endif
   26549   pShmNode->nRef++;
   26550   pDbFd->pShm = p;
   26551   unixLeaveMutex();
   26552 
   26553   /* The reference count on pShmNode has already been incremented under
   26554   ** the cover of the unixEnterMutex() mutex and the pointer from the
   26555   ** new (struct unixShm) object to the pShmNode has been set. All that is
   26556   ** left to do is to link the new object into the linked list starting
   26557   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   26558   ** mutex.
   26559   */
   26560   sqlite3_mutex_enter(pShmNode->mutex);
   26561   p->pNext = pShmNode->pFirst;
   26562   pShmNode->pFirst = p;
   26563   sqlite3_mutex_leave(pShmNode->mutex);
   26564   return SQLITE_OK;
   26565 
   26566   /* Jump here on any error */
   26567 shm_open_err:
   26568   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
   26569   sqlite3_free(p);
   26570   unixLeaveMutex();
   26571   return rc;
   26572 }
   26573 
   26574 /*
   26575 ** This function is called to obtain a pointer to region iRegion of the
   26576 ** shared-memory associated with the database file fd. Shared-memory regions
   26577 ** are numbered starting from zero. Each shared-memory region is szRegion
   26578 ** bytes in size.
   26579 **
   26580 ** If an error occurs, an error code is returned and *pp is set to NULL.
   26581 **
   26582 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
   26583 ** region has not been allocated (by any client, including one running in a
   26584 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   26585 ** bExtend is non-zero and the requested shared-memory region has not yet
   26586 ** been allocated, it is allocated by this function.
   26587 **
   26588 ** If the shared-memory region has already been allocated or is allocated by
   26589 ** this call as described above, then it is mapped into this processes
   26590 ** address space (if it is not already), *pp is set to point to the mapped
   26591 ** memory and SQLITE_OK returned.
   26592 */
   26593 static int unixShmMap(
   26594   sqlite3_file *fd,               /* Handle open on database file */
   26595   int iRegion,                    /* Region to retrieve */
   26596   int szRegion,                   /* Size of regions */
   26597   int bExtend,                    /* True to extend file if necessary */
   26598   void volatile **pp              /* OUT: Mapped memory */
   26599 ){
   26600   unixFile *pDbFd = (unixFile*)fd;
   26601   unixShm *p;
   26602   unixShmNode *pShmNode;
   26603   int rc = SQLITE_OK;
   26604 
   26605   /* If the shared-memory file has not yet been opened, open it now. */
   26606   if( pDbFd->pShm==0 ){
   26607     rc = unixOpenSharedMemory(pDbFd);
   26608     if( rc!=SQLITE_OK ) return rc;
   26609   }
   26610 
   26611   p = pDbFd->pShm;
   26612   pShmNode = p->pShmNode;
   26613   sqlite3_mutex_enter(pShmNode->mutex);
   26614   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   26615 
   26616   if( pShmNode->nRegion<=iRegion ){
   26617     char **apNew;                      /* New apRegion[] array */
   26618     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   26619     struct stat sStat;                 /* Used by fstat() */
   26620 
   26621     pShmNode->szRegion = szRegion;
   26622 
   26623     /* The requested region is not mapped into this processes address space.
   26624     ** Check to see if it has been allocated (i.e. if the wal-index file is
   26625     ** large enough to contain the requested region).
   26626     */
   26627     if( fstat(pShmNode->h, &sStat) ){
   26628       rc = SQLITE_IOERR_SHMSIZE;
   26629       goto shmpage_out;
   26630     }
   26631 
   26632     if( sStat.st_size<nByte ){
   26633       /* The requested memory region does not exist. If bExtend is set to
   26634       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
   26635       **
   26636       ** Alternatively, if bExtend is true, use ftruncate() to allocate
   26637       ** the requested memory region.
   26638       */
   26639       if( !bExtend ) goto shmpage_out;
   26640       if( robust_ftruncate(pShmNode->h, nByte) ){
   26641         rc = unixLogError(SQLITE_IOERR_SHMSIZE,"ftruncate",pShmNode->zFilename);
   26642         goto shmpage_out;
   26643       }
   26644     }
   26645 
   26646     /* Map the requested memory region into this processes address space. */
   26647     apNew = (char **)sqlite3_realloc(
   26648         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
   26649     );
   26650     if( !apNew ){
   26651       rc = SQLITE_IOERR_NOMEM;
   26652       goto shmpage_out;
   26653     }
   26654     pShmNode->apRegion = apNew;
   26655     while(pShmNode->nRegion<=iRegion){
   26656       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
   26657           MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
   26658       );
   26659       if( pMem==MAP_FAILED ){
   26660         rc = SQLITE_IOERR;
   26661         goto shmpage_out;
   26662       }
   26663       pShmNode->apRegion[pShmNode->nRegion] = pMem;
   26664       pShmNode->nRegion++;
   26665     }
   26666   }
   26667 
   26668 shmpage_out:
   26669   if( pShmNode->nRegion>iRegion ){
   26670     *pp = pShmNode->apRegion[iRegion];
   26671   }else{
   26672     *pp = 0;
   26673   }
   26674   sqlite3_mutex_leave(pShmNode->mutex);
   26675   return rc;
   26676 }
   26677 
   26678 /*
   26679 ** Change the lock state for a shared-memory segment.
   26680 **
   26681 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
   26682 ** different here than in posix.  In xShmLock(), one can go from unlocked
   26683 ** to shared and back or from unlocked to exclusive and back.  But one may
   26684 ** not go from shared to exclusive or from exclusive to shared.
   26685 */
   26686 static int unixShmLock(
   26687   sqlite3_file *fd,          /* Database file holding the shared memory */
   26688   int ofst,                  /* First lock to acquire or release */
   26689   int n,                     /* Number of locks to acquire or release */
   26690   int flags                  /* What to do with the lock */
   26691 ){
   26692   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   26693   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
   26694   unixShm *pX;                          /* For looping over all siblings */
   26695   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   26696   int rc = SQLITE_OK;                   /* Result code */
   26697   u16 mask;                             /* Mask of locks to take or release */
   26698 
   26699   assert( pShmNode==pDbFd->pInode->pShmNode );
   26700   assert( pShmNode->pInode==pDbFd->pInode );
   26701   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   26702   assert( n>=1 );
   26703   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   26704        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   26705        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   26706        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   26707   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   26708 
   26709   mask = (1<<(ofst+n)) - (1<<ofst);
   26710   assert( n>1 || mask==(1<<ofst) );
   26711   sqlite3_mutex_enter(pShmNode->mutex);
   26712   if( flags & SQLITE_SHM_UNLOCK ){
   26713     u16 allMask = 0; /* Mask of locks held by siblings */
   26714 
   26715     /* See if any siblings hold this same lock */
   26716     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   26717       if( pX==p ) continue;
   26718       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   26719       allMask |= pX->sharedMask;
   26720     }
   26721 
   26722     /* Unlock the system-level locks */
   26723     if( (mask & allMask)==0 ){
   26724       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
   26725     }else{
   26726       rc = SQLITE_OK;
   26727     }
   26728 
   26729     /* Undo the local locks */
   26730     if( rc==SQLITE_OK ){
   26731       p->exclMask &= ~mask;
   26732       p->sharedMask &= ~mask;
   26733     }
   26734   }else if( flags & SQLITE_SHM_SHARED ){
   26735     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   26736 
   26737     /* Find out which shared locks are already held by sibling connections.
   26738     ** If any sibling already holds an exclusive lock, go ahead and return
   26739     ** SQLITE_BUSY.
   26740     */
   26741     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   26742       if( (pX->exclMask & mask)!=0 ){
   26743         rc = SQLITE_BUSY;
   26744         break;
   26745       }
   26746       allShared |= pX->sharedMask;
   26747     }
   26748 
   26749     /* Get shared locks at the system level, if necessary */
   26750     if( rc==SQLITE_OK ){
   26751       if( (allShared & mask)==0 ){
   26752         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
   26753       }else{
   26754         rc = SQLITE_OK;
   26755       }
   26756     }
   26757 
   26758     /* Get the local shared locks */
   26759     if( rc==SQLITE_OK ){
   26760       p->sharedMask |= mask;
   26761     }
   26762   }else{
   26763     /* Make sure no sibling connections hold locks that will block this
   26764     ** lock.  If any do, return SQLITE_BUSY right away.
   26765     */
   26766     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   26767       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   26768         rc = SQLITE_BUSY;
   26769         break;
   26770       }
   26771     }
   26772 
   26773     /* Get the exclusive locks at the system level.  Then if successful
   26774     ** also mark the local connection as being locked.
   26775     */
   26776     if( rc==SQLITE_OK ){
   26777       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
   26778       if( rc==SQLITE_OK ){
   26779         assert( (p->sharedMask & mask)==0 );
   26780         p->exclMask |= mask;
   26781       }
   26782     }
   26783   }
   26784   sqlite3_mutex_leave(pShmNode->mutex);
   26785   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
   26786            p->id, getpid(), p->sharedMask, p->exclMask));
   26787   return rc;
   26788 }
   26789 
   26790 /*
   26791 ** Implement a memory barrier or memory fence on shared memory.
   26792 **
   26793 ** All loads and stores begun before the barrier must complete before
   26794 ** any load or store begun after the barrier.
   26795 */
   26796 static void unixShmBarrier(
   26797   sqlite3_file *fd                /* Database file holding the shared memory */
   26798 ){
   26799   UNUSED_PARAMETER(fd);
   26800   unixEnterMutex();
   26801   unixLeaveMutex();
   26802 }
   26803 
   26804 /*
   26805 ** Close a connection to shared-memory.  Delete the underlying
   26806 ** storage if deleteFlag is true.
   26807 **
   26808 ** If there is no shared memory associated with the connection then this
   26809 ** routine is a harmless no-op.
   26810 */
   26811 static int unixShmUnmap(
   26812   sqlite3_file *fd,               /* The underlying database file */
   26813   int deleteFlag                  /* Delete shared-memory if true */
   26814 ){
   26815   unixShm *p;                     /* The connection to be closed */
   26816   unixShmNode *pShmNode;          /* The underlying shared-memory file */
   26817   unixShm **pp;                   /* For looping over sibling connections */
   26818   unixFile *pDbFd;                /* The underlying database file */
   26819 
   26820   pDbFd = (unixFile*)fd;
   26821   p = pDbFd->pShm;
   26822   if( p==0 ) return SQLITE_OK;
   26823   pShmNode = p->pShmNode;
   26824 
   26825   assert( pShmNode==pDbFd->pInode->pShmNode );
   26826   assert( pShmNode->pInode==pDbFd->pInode );
   26827 
   26828   /* Remove connection p from the set of connections associated
   26829   ** with pShmNode */
   26830   sqlite3_mutex_enter(pShmNode->mutex);
   26831   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   26832   *pp = p->pNext;
   26833 
   26834   /* Free the connection p */
   26835   sqlite3_free(p);
   26836   pDbFd->pShm = 0;
   26837   sqlite3_mutex_leave(pShmNode->mutex);
   26838 
   26839   /* If pShmNode->nRef has reached 0, then close the underlying
   26840   ** shared-memory file, too */
   26841   unixEnterMutex();
   26842   assert( pShmNode->nRef>0 );
   26843   pShmNode->nRef--;
   26844   if( pShmNode->nRef==0 ){
   26845     if( deleteFlag ) unlink(pShmNode->zFilename);
   26846     unixShmPurge(pDbFd);
   26847   }
   26848   unixLeaveMutex();
   26849 
   26850   return SQLITE_OK;
   26851 }
   26852 
   26853 
   26854 #else
   26855 # define unixShmMap     0
   26856 # define unixShmLock    0
   26857 # define unixShmBarrier 0
   26858 # define unixShmUnmap   0
   26859 #endif /* #ifndef SQLITE_OMIT_WAL */
   26860 
   26861 /*
   26862 ** Here ends the implementation of all sqlite3_file methods.
   26863 **
   26864 ********************** End sqlite3_file Methods *******************************
   26865 ******************************************************************************/
   26866 
   26867 /*
   26868 ** This division contains definitions of sqlite3_io_methods objects that
   26869 ** implement various file locking strategies.  It also contains definitions
   26870 ** of "finder" functions.  A finder-function is used to locate the appropriate
   26871 ** sqlite3_io_methods object for a particular database file.  The pAppData
   26872 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
   26873 ** the correct finder-function for that VFS.
   26874 **
   26875 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
   26876 ** object.  The only interesting finder-function is autolockIoFinder, which
   26877 ** looks at the filesystem type and tries to guess the best locking
   26878 ** strategy from that.
   26879 **
   26880 ** For finder-funtion F, two objects are created:
   26881 **
   26882 **    (1) The real finder-function named "FImpt()".
   26883 **
   26884 **    (2) A constant pointer to this function named just "F".
   26885 **
   26886 **
   26887 ** A pointer to the F pointer is used as the pAppData value for VFS
   26888 ** objects.  We have to do this instead of letting pAppData point
   26889 ** directly at the finder-function since C90 rules prevent a void*
   26890 ** from be cast into a function pointer.
   26891 **
   26892 **
   26893 ** Each instance of this macro generates two objects:
   26894 **
   26895 **   *  A constant sqlite3_io_methods object call METHOD that has locking
   26896 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
   26897 **
   26898 **   *  An I/O method finder function called FINDER that returns a pointer
   26899 **      to the METHOD object in the previous bullet.
   26900 */
   26901 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
   26902 static const sqlite3_io_methods METHOD = {                                   \
   26903    VERSION,                    /* iVersion */                                \
   26904    CLOSE,                      /* xClose */                                  \
   26905    unixRead,                   /* xRead */                                   \
   26906    unixWrite,                  /* xWrite */                                  \
   26907    unixTruncate,               /* xTruncate */                               \
   26908    unixSync,                   /* xSync */                                   \
   26909    unixFileSize,               /* xFileSize */                               \
   26910    LOCK,                       /* xLock */                                   \
   26911    UNLOCK,                     /* xUnlock */                                 \
   26912    CKLOCK,                     /* xCheckReservedLock */                      \
   26913    unixFileControl,            /* xFileControl */                            \
   26914    unixSectorSize,             /* xSectorSize */                             \
   26915    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
   26916    unixShmMap,                 /* xShmMap */                                 \
   26917    unixShmLock,                /* xShmLock */                                \
   26918    unixShmBarrier,             /* xShmBarrier */                             \
   26919    unixShmUnmap                /* xShmUnmap */                               \
   26920 };                                                                           \
   26921 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
   26922   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
   26923   return &METHOD;                                                            \
   26924 }                                                                            \
   26925 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
   26926     = FINDER##Impl;
   26927 
   26928 /*
   26929 ** Here are all of the sqlite3_io_methods objects for each of the
   26930 ** locking strategies.  Functions that return pointers to these methods
   26931 ** are also created.
   26932 */
   26933 IOMETHODS(
   26934   posixIoFinder,            /* Finder function name */
   26935   posixIoMethods,           /* sqlite3_io_methods object name */
   26936   2,                        /* shared memory is enabled */
   26937   unixClose,                /* xClose method */
   26938   unixLock,                 /* xLock method */
   26939   unixUnlock,               /* xUnlock method */
   26940   unixCheckReservedLock     /* xCheckReservedLock method */
   26941 )
   26942 IOMETHODS(
   26943   nolockIoFinder,           /* Finder function name */
   26944   nolockIoMethods,          /* sqlite3_io_methods object name */
   26945   1,                        /* shared memory is disabled */
   26946   nolockClose,              /* xClose method */
   26947   nolockLock,               /* xLock method */
   26948   nolockUnlock,             /* xUnlock method */
   26949   nolockCheckReservedLock   /* xCheckReservedLock method */
   26950 )
   26951 IOMETHODS(
   26952   dotlockIoFinder,          /* Finder function name */
   26953   dotlockIoMethods,         /* sqlite3_io_methods object name */
   26954   1,                        /* shared memory is disabled */
   26955   dotlockClose,             /* xClose method */
   26956   dotlockLock,              /* xLock method */
   26957   dotlockUnlock,            /* xUnlock method */
   26958   dotlockCheckReservedLock  /* xCheckReservedLock method */
   26959 )
   26960 
   26961 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
   26962 IOMETHODS(
   26963   flockIoFinder,            /* Finder function name */
   26964   flockIoMethods,           /* sqlite3_io_methods object name */
   26965   1,                        /* shared memory is disabled */
   26966   flockClose,               /* xClose method */
   26967   flockLock,                /* xLock method */
   26968   flockUnlock,              /* xUnlock method */
   26969   flockCheckReservedLock    /* xCheckReservedLock method */
   26970 )
   26971 #endif
   26972 
   26973 #if OS_VXWORKS
   26974 IOMETHODS(
   26975   semIoFinder,              /* Finder function name */
   26976   semIoMethods,             /* sqlite3_io_methods object name */
   26977   1,                        /* shared memory is disabled */
   26978   semClose,                 /* xClose method */
   26979   semLock,                  /* xLock method */
   26980   semUnlock,                /* xUnlock method */
   26981   semCheckReservedLock      /* xCheckReservedLock method */
   26982 )
   26983 #endif
   26984 
   26985 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   26986 IOMETHODS(
   26987   afpIoFinder,              /* Finder function name */
   26988   afpIoMethods,             /* sqlite3_io_methods object name */
   26989   1,                        /* shared memory is disabled */
   26990   afpClose,                 /* xClose method */
   26991   afpLock,                  /* xLock method */
   26992   afpUnlock,                /* xUnlock method */
   26993   afpCheckReservedLock      /* xCheckReservedLock method */
   26994 )
   26995 #endif
   26996 
   26997 /*
   26998 ** The proxy locking method is a "super-method" in the sense that it
   26999 ** opens secondary file descriptors for the conch and lock files and
   27000 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
   27001 ** secondary files.  For this reason, the division that implements
   27002 ** proxy locking is located much further down in the file.  But we need
   27003 ** to go ahead and define the sqlite3_io_methods and finder function
   27004 ** for proxy locking here.  So we forward declare the I/O methods.
   27005 */
   27006 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27007 static int proxyClose(sqlite3_file*);
   27008 static int proxyLock(sqlite3_file*, int);
   27009 static int proxyUnlock(sqlite3_file*, int);
   27010 static int proxyCheckReservedLock(sqlite3_file*, int*);
   27011 IOMETHODS(
   27012   proxyIoFinder,            /* Finder function name */
   27013   proxyIoMethods,           /* sqlite3_io_methods object name */
   27014   1,                        /* shared memory is disabled */
   27015   proxyClose,               /* xClose method */
   27016   proxyLock,                /* xLock method */
   27017   proxyUnlock,              /* xUnlock method */
   27018   proxyCheckReservedLock    /* xCheckReservedLock method */
   27019 )
   27020 #endif
   27021 
   27022 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
   27023 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27024 IOMETHODS(
   27025   nfsIoFinder,               /* Finder function name */
   27026   nfsIoMethods,              /* sqlite3_io_methods object name */
   27027   1,                         /* shared memory is disabled */
   27028   unixClose,                 /* xClose method */
   27029   unixLock,                  /* xLock method */
   27030   nfsUnlock,                 /* xUnlock method */
   27031   unixCheckReservedLock      /* xCheckReservedLock method */
   27032 )
   27033 #endif
   27034 
   27035 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27036 /*
   27037 ** This "finder" function attempts to determine the best locking strategy
   27038 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   27039 ** object that implements that strategy.
   27040 **
   27041 ** This is for MacOSX only.
   27042 */
   27043 static const sqlite3_io_methods *autolockIoFinderImpl(
   27044   const char *filePath,    /* name of the database file */
   27045   unixFile *pNew           /* open file object for the database file */
   27046 ){
   27047   static const struct Mapping {
   27048     const char *zFilesystem;              /* Filesystem type name */
   27049     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
   27050   } aMap[] = {
   27051     { "hfs",    &posixIoMethods },
   27052     { "ufs",    &posixIoMethods },
   27053     { "afpfs",  &afpIoMethods },
   27054     { "smbfs",  &afpIoMethods },
   27055     { "webdav", &nolockIoMethods },
   27056     { 0, 0 }
   27057   };
   27058   int i;
   27059   struct statfs fsInfo;
   27060   struct flock lockInfo;
   27061 
   27062   if( !filePath ){
   27063     /* If filePath==NULL that means we are dealing with a transient file
   27064     ** that does not need to be locked. */
   27065     return &nolockIoMethods;
   27066   }
   27067   if( statfs(filePath, &fsInfo) != -1 ){
   27068     if( fsInfo.f_flags & MNT_RDONLY ){
   27069       return &nolockIoMethods;
   27070     }
   27071     for(i=0; aMap[i].zFilesystem; i++){
   27072       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
   27073         return aMap[i].pMethods;
   27074       }
   27075     }
   27076   }
   27077 
   27078   /* Default case. Handles, amongst others, "nfs".
   27079   ** Test byte-range lock using fcntl(). If the call succeeds,
   27080   ** assume that the file-system supports POSIX style locks.
   27081   */
   27082   lockInfo.l_len = 1;
   27083   lockInfo.l_start = 0;
   27084   lockInfo.l_whence = SEEK_SET;
   27085   lockInfo.l_type = F_RDLCK;
   27086   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   27087     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
   27088       return &nfsIoMethods;
   27089     } else {
   27090       return &posixIoMethods;
   27091     }
   27092   }else{
   27093     return &dotlockIoMethods;
   27094   }
   27095 }
   27096 static const sqlite3_io_methods
   27097   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   27098 
   27099 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   27100 
   27101 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
   27102 /*
   27103 ** This "finder" function attempts to determine the best locking strategy
   27104 ** for the database file "filePath".  It then returns the sqlite3_io_methods
   27105 ** object that implements that strategy.
   27106 **
   27107 ** This is for VXWorks only.
   27108 */
   27109 static const sqlite3_io_methods *autolockIoFinderImpl(
   27110   const char *filePath,    /* name of the database file */
   27111   unixFile *pNew           /* the open file object */
   27112 ){
   27113   struct flock lockInfo;
   27114 
   27115   if( !filePath ){
   27116     /* If filePath==NULL that means we are dealing with a transient file
   27117     ** that does not need to be locked. */
   27118     return &nolockIoMethods;
   27119   }
   27120 
   27121   /* Test if fcntl() is supported and use POSIX style locks.
   27122   ** Otherwise fall back to the named semaphore method.
   27123   */
   27124   lockInfo.l_len = 1;
   27125   lockInfo.l_start = 0;
   27126   lockInfo.l_whence = SEEK_SET;
   27127   lockInfo.l_type = F_RDLCK;
   27128   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
   27129     return &posixIoMethods;
   27130   }else{
   27131     return &semIoMethods;
   27132   }
   27133 }
   27134 static const sqlite3_io_methods
   27135   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
   27136 
   27137 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
   27138 
   27139 /*
   27140 ** An abstract type for a pointer to a IO method finder function:
   27141 */
   27142 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
   27143 
   27144 
   27145 /****************************************************************************
   27146 **************************** sqlite3_vfs methods ****************************
   27147 **
   27148 ** This division contains the implementation of methods on the
   27149 ** sqlite3_vfs object.
   27150 */
   27151 
   27152 /*
   27153 ** Initialize the contents of the unixFile structure pointed to by pId.
   27154 */
   27155 static int fillInUnixFile(
   27156   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
   27157   int h,                  /* Open file descriptor of file being opened */
   27158   int dirfd,              /* Directory file descriptor */
   27159   sqlite3_file *pId,      /* Write to the unixFile structure here */
   27160   const char *zFilename,  /* Name of the file being opened */
   27161   int noLock,             /* Omit locking if true */
   27162   int isDelete            /* Delete on close if true */
   27163 ){
   27164   const sqlite3_io_methods *pLockingStyle;
   27165   unixFile *pNew = (unixFile *)pId;
   27166   int rc = SQLITE_OK;
   27167 
   27168   assert( pNew->pInode==NULL );
   27169 
   27170   /* Parameter isDelete is only used on vxworks. Express this explicitly
   27171   ** here to prevent compiler warnings about unused parameters.
   27172   */
   27173   UNUSED_PARAMETER(isDelete);
   27174 
   27175   /* Usually the path zFilename should not be a relative pathname. The
   27176   ** exception is when opening the proxy "conch" file in builds that
   27177   ** include the special Apple locking styles.
   27178   */
   27179 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27180   assert( zFilename==0 || zFilename[0]=='/'
   27181     || pVfs->pAppData==(void*)&autolockIoFinder );
   27182 #else
   27183   assert( zFilename==0 || zFilename[0]=='/' );
   27184 #endif
   27185 
   27186   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
   27187   pNew->h = h;
   27188   pNew->dirfd = dirfd;
   27189   pNew->fileFlags = 0;
   27190   pNew->zPath = zFilename;
   27191 
   27192 #if OS_VXWORKS
   27193   pNew->pId = vxworksFindFileId(zFilename);
   27194   if( pNew->pId==0 ){
   27195     noLock = 1;
   27196     rc = SQLITE_NOMEM;
   27197   }
   27198 #endif
   27199 
   27200   if( noLock ){
   27201     pLockingStyle = &nolockIoMethods;
   27202   }else{
   27203     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
   27204 #if SQLITE_ENABLE_LOCKING_STYLE
   27205     /* Cache zFilename in the locking context (AFP and dotlock override) for
   27206     ** proxyLock activation is possible (remote proxy is based on db name)
   27207     ** zFilename remains valid until file is closed, to support */
   27208     pNew->lockingContext = (void*)zFilename;
   27209 #endif
   27210   }
   27211 
   27212   if( pLockingStyle == &posixIoMethods
   27213 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   27214     || pLockingStyle == &nfsIoMethods
   27215 #endif
   27216   ){
   27217     unixEnterMutex();
   27218     rc = findInodeInfo(pNew, &pNew->pInode);
   27219     if( rc!=SQLITE_OK ){
   27220       /* If an error occured in findInodeInfo(), close the file descriptor
   27221       ** immediately, before releasing the mutex. findInodeInfo() may fail
   27222       ** in two scenarios:
   27223       **
   27224       **   (a) A call to fstat() failed.
   27225       **   (b) A malloc failed.
   27226       **
   27227       ** Scenario (b) may only occur if the process is holding no other
   27228       ** file descriptors open on the same file. If there were other file
   27229       ** descriptors on this file, then no malloc would be required by
   27230       ** findInodeInfo(). If this is the case, it is quite safe to close
   27231       ** handle h - as it is guaranteed that no posix locks will be released
   27232       ** by doing so.
   27233       **
   27234       ** If scenario (a) caused the error then things are not so safe. The
   27235       ** implicit assumption here is that if fstat() fails, things are in
   27236       ** such bad shape that dropping a lock or two doesn't matter much.
   27237       */
   27238       close(h);
   27239       h = -1;
   27240     }
   27241     unixLeaveMutex();
   27242   }
   27243 
   27244 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   27245   else if( pLockingStyle == &afpIoMethods ){
   27246     /* AFP locking uses the file path so it needs to be included in
   27247     ** the afpLockingContext.
   27248     */
   27249     afpLockingContext *pCtx;
   27250     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
   27251     if( pCtx==0 ){
   27252       rc = SQLITE_NOMEM;
   27253     }else{
   27254       /* NB: zFilename exists and remains valid until the file is closed
   27255       ** according to requirement F11141.  So we do not need to make a
   27256       ** copy of the filename. */
   27257       pCtx->dbPath = zFilename;
   27258       pCtx->reserved = 0;
   27259       srandomdev();
   27260       unixEnterMutex();
   27261       rc = findInodeInfo(pNew, &pNew->pInode);
   27262       if( rc!=SQLITE_OK ){
   27263         sqlite3_free(pNew->lockingContext);
   27264         close(h);
   27265         h = -1;
   27266       }
   27267       unixLeaveMutex();
   27268     }
   27269   }
   27270 #endif
   27271 
   27272   else if( pLockingStyle == &dotlockIoMethods ){
   27273     /* Dotfile locking uses the file path so it needs to be included in
   27274     ** the dotlockLockingContext
   27275     */
   27276     char *zLockFile;
   27277     int nFilename;
   27278     nFilename = (int)strlen(zFilename) + 6;
   27279     zLockFile = (char *)sqlite3_malloc(nFilename);
   27280     if( zLockFile==0 ){
   27281       rc = SQLITE_NOMEM;
   27282     }else{
   27283       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
   27284     }
   27285     pNew->lockingContext = zLockFile;
   27286   }
   27287 
   27288 #if OS_VXWORKS
   27289   else if( pLockingStyle == &semIoMethods ){
   27290     /* Named semaphore locking uses the file path so it needs to be
   27291     ** included in the semLockingContext
   27292     */
   27293     unixEnterMutex();
   27294     rc = findInodeInfo(pNew, &pNew->pInode);
   27295     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
   27296       char *zSemName = pNew->pInode->aSemName;
   27297       int n;
   27298       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
   27299                        pNew->pId->zCanonicalName);
   27300       for( n=1; zSemName[n]; n++ )
   27301         if( zSemName[n]=='/' ) zSemName[n] = '_';
   27302       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
   27303       if( pNew->pInode->pSem == SEM_FAILED ){
   27304         rc = SQLITE_NOMEM;
   27305         pNew->pInode->aSemName[0] = '\0';
   27306       }
   27307     }
   27308     unixLeaveMutex();
   27309   }
   27310 #endif
   27311 
   27312   pNew->lastErrno = 0;
   27313 #if OS_VXWORKS
   27314   if( rc!=SQLITE_OK ){
   27315     if( h>=0 ) close(h);
   27316     h = -1;
   27317     unlink(zFilename);
   27318     isDelete = 0;
   27319   }
   27320   pNew->isDelete = isDelete;
   27321 #endif
   27322   if( rc!=SQLITE_OK ){
   27323     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
   27324     if( h>=0 ) close(h);
   27325   }else{
   27326     pNew->pMethod = pLockingStyle;
   27327     OpenCounter(+1);
   27328   }
   27329   return rc;
   27330 }
   27331 
   27332 /*
   27333 ** Open a file descriptor to the directory containing file zFilename.
   27334 ** If successful, *pFd is set to the opened file descriptor and
   27335 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
   27336 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
   27337 ** value.
   27338 **
   27339 ** If SQLITE_OK is returned, the caller is responsible for closing
   27340 ** the file descriptor *pFd using close().
   27341 */
   27342 static int openDirectory(const char *zFilename, int *pFd){
   27343   int ii;
   27344   int fd = -1;
   27345   char zDirname[MAX_PATHNAME+1];
   27346 
   27347   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
   27348   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
   27349   if( ii>0 ){
   27350     zDirname[ii] = '\0';
   27351     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
   27352     if( fd>=0 ){
   27353 #ifdef FD_CLOEXEC
   27354       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   27355 #endif
   27356       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
   27357     }
   27358   }
   27359   *pFd = fd;
   27360   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
   27361 }
   27362 
   27363 /*
   27364 ** Return the name of a directory in which to put temporary files.
   27365 ** If no suitable temporary file directory can be found, return NULL.
   27366 */
   27367 static const char *unixTempFileDir(void){
   27368   static const char *azDirs[] = {
   27369      0,
   27370      0,
   27371      "/var/tmp",
   27372      "/usr/tmp",
   27373      "/tmp",
   27374      0        /* List terminator */
   27375   };
   27376   unsigned int i;
   27377   struct stat buf;
   27378   const char *zDir = 0;
   27379 
   27380   azDirs[0] = sqlite3_temp_directory;
   27381   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
   27382   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
   27383     if( zDir==0 ) continue;
   27384     if( stat(zDir, &buf) ) continue;
   27385     if( !S_ISDIR(buf.st_mode) ) continue;
   27386     if( access(zDir, 07) ) continue;
   27387     break;
   27388   }
   27389   return zDir;
   27390 }
   27391 
   27392 /*
   27393 ** Create a temporary file name in zBuf.  zBuf must be allocated
   27394 ** by the calling process and must be big enough to hold at least
   27395 ** pVfs->mxPathname bytes.
   27396 */
   27397 static int unixGetTempname(int nBuf, char *zBuf){
   27398   static const unsigned char zChars[] =
   27399     "abcdefghijklmnopqrstuvwxyz"
   27400     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   27401     "0123456789";
   27402   unsigned int i, j;
   27403   const char *zDir;
   27404 
   27405   /* It's odd to simulate an io-error here, but really this is just
   27406   ** using the io-error infrastructure to test that SQLite handles this
   27407   ** function failing.
   27408   */
   27409   SimulateIOError( return SQLITE_IOERR );
   27410 
   27411   zDir = unixTempFileDir();
   27412   if( zDir==0 ) zDir = ".";
   27413 
   27414   /* Check that the output buffer is large enough for the temporary file
   27415   ** name. If it is not, return SQLITE_ERROR.
   27416   */
   27417   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
   27418     return SQLITE_ERROR;
   27419   }
   27420 
   27421   do{
   27422     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
   27423     j = (int)strlen(zBuf);
   27424     sqlite3_randomness(15, &zBuf[j]);
   27425     for(i=0; i<15; i++, j++){
   27426       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   27427     }
   27428     zBuf[j] = 0;
   27429   }while( access(zBuf,0)==0 );
   27430   return SQLITE_OK;
   27431 }
   27432 
   27433 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   27434 /*
   27435 ** Routine to transform a unixFile into a proxy-locking unixFile.
   27436 ** Implementation in the proxy-lock division, but used by unixOpen()
   27437 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
   27438 */
   27439 static int proxyTransformUnixFile(unixFile*, const char*);
   27440 #endif
   27441 
   27442 /*
   27443 ** Search for an unused file descriptor that was opened on the database
   27444 ** file (not a journal or master-journal file) identified by pathname
   27445 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
   27446 ** argument to this function.
   27447 **
   27448 ** Such a file descriptor may exist if a database connection was closed
   27449 ** but the associated file descriptor could not be closed because some
   27450 ** other file descriptor open on the same file is holding a file-lock.
   27451 ** Refer to comments in the unixClose() function and the lengthy comment
   27452 ** describing "Posix Advisory Locking" at the start of this file for
   27453 ** further details. Also, ticket #4018.
   27454 **
   27455 ** If a suitable file descriptor is found, then it is returned. If no
   27456 ** such file descriptor is located, -1 is returned.
   27457 */
   27458 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
   27459   UnixUnusedFd *pUnused = 0;
   27460 
   27461   /* Do not search for an unused file descriptor on vxworks. Not because
   27462   ** vxworks would not benefit from the change (it might, we're not sure),
   27463   ** but because no way to test it is currently available. It is better
   27464   ** not to risk breaking vxworks support for the sake of such an obscure
   27465   ** feature.  */
   27466 #if !OS_VXWORKS
   27467   struct stat sStat;                   /* Results of stat() call */
   27468 
   27469   /* A stat() call may fail for various reasons. If this happens, it is
   27470   ** almost certain that an open() call on the same path will also fail.
   27471   ** For this reason, if an error occurs in the stat() call here, it is
   27472   ** ignored and -1 is returned. The caller will try to open a new file
   27473   ** descriptor on the same path, fail, and return an error to SQLite.
   27474   **
   27475   ** Even if a subsequent open() call does succeed, the consequences of
   27476   ** not searching for a resusable file descriptor are not dire.  */
   27477   if( 0==stat(zPath, &sStat) ){
   27478     unixInodeInfo *pInode;
   27479 
   27480     unixEnterMutex();
   27481     pInode = inodeList;
   27482     while( pInode && (pInode->fileId.dev!=sStat.st_dev
   27483                      || pInode->fileId.ino!=sStat.st_ino) ){
   27484        pInode = pInode->pNext;
   27485     }
   27486     if( pInode ){
   27487       UnixUnusedFd **pp;
   27488       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
   27489       pUnused = *pp;
   27490       if( pUnused ){
   27491         *pp = pUnused->pNext;
   27492       }
   27493     }
   27494     unixLeaveMutex();
   27495   }
   27496 #endif    /* if !OS_VXWORKS */
   27497   return pUnused;
   27498 }
   27499 
   27500 /*
   27501 ** This function is called by unixOpen() to determine the unix permissions
   27502 ** to create new files with. If no error occurs, then SQLITE_OK is returned
   27503 ** and a value suitable for passing as the third argument to open(2) is
   27504 ** written to *pMode. If an IO error occurs, an SQLite error code is
   27505 ** returned and the value of *pMode is not modified.
   27506 **
   27507 ** If the file being opened is a temporary file, it is always created with
   27508 ** the octal permissions 0600 (read/writable by owner only). If the file
   27509 ** is a database or master journal file, it is created with the permissions
   27510 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
   27511 **
   27512 ** Finally, if the file being opened is a WAL or regular journal file, then
   27513 ** this function queries the file-system for the permissions on the
   27514 ** corresponding database file and sets *pMode to this value. Whenever
   27515 ** possible, WAL and journal files are created using the same permissions
   27516 ** as the associated database file.
   27517 */
   27518 static int findCreateFileMode(
   27519   const char *zPath,              /* Path of file (possibly) being created */
   27520   int flags,                      /* Flags passed as 4th argument to xOpen() */
   27521   mode_t *pMode                   /* OUT: Permissions to open file with */
   27522 ){
   27523   int rc = SQLITE_OK;             /* Return Code */
   27524   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
   27525     char zDb[MAX_PATHNAME+1];     /* Database file path */
   27526     int nDb;                      /* Number of valid bytes in zDb */
   27527     struct stat sStat;            /* Output of stat() on database file */
   27528 
   27529     /* zPath is a path to a WAL or journal file. The following block derives
   27530     ** the path to the associated database file from zPath. This block handles
   27531     ** the following naming conventions:
   27532     **
   27533     **   "<path to db>-journal"
   27534     **   "<path to db>-wal"
   27535     **   "<path to db>-journal-NNNN"
   27536     **   "<path to db>-wal-NNNN"
   27537     **
   27538     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
   27539     ** used by the test_multiplex.c module.
   27540     */
   27541     nDb = sqlite3Strlen30(zPath) - 1;
   27542     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
   27543     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
   27544     memcpy(zDb, zPath, nDb);
   27545     zDb[nDb] = '\0';
   27546 
   27547     if( 0==stat(zDb, &sStat) ){
   27548       *pMode = sStat.st_mode & 0777;
   27549     }else{
   27550       rc = SQLITE_IOERR_FSTAT;
   27551     }
   27552   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
   27553     *pMode = 0600;
   27554   }else{
   27555     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
   27556   }
   27557   return rc;
   27558 }
   27559 
   27560 /*
   27561 ** Open the file zPath.
   27562 **
   27563 ** Previously, the SQLite OS layer used three functions in place of this
   27564 ** one:
   27565 **
   27566 **     sqlite3OsOpenReadWrite();
   27567 **     sqlite3OsOpenReadOnly();
   27568 **     sqlite3OsOpenExclusive();
   27569 **
   27570 ** These calls correspond to the following combinations of flags:
   27571 **
   27572 **     ReadWrite() ->     (READWRITE | CREATE)
   27573 **     ReadOnly()  ->     (READONLY)
   27574 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
   27575 **
   27576 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
   27577 ** true, the file was configured to be automatically deleted when the
   27578 ** file handle closed. To achieve the same effect using this new
   27579 ** interface, add the DELETEONCLOSE flag to those specified above for
   27580 ** OpenExclusive().
   27581 */
   27582 static int unixOpen(
   27583   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
   27584   const char *zPath,           /* Pathname of file to be opened */
   27585   sqlite3_file *pFile,         /* The file descriptor to be filled in */
   27586   int flags,                   /* Input flags to control the opening */
   27587   int *pOutFlags               /* Output flags returned to SQLite core */
   27588 ){
   27589   unixFile *p = (unixFile *)pFile;
   27590   int fd = -1;                   /* File descriptor returned by open() */
   27591   int dirfd = -1;                /* Directory file descriptor */
   27592   int openFlags = 0;             /* Flags to pass to open() */
   27593   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   27594   int noLock;                    /* True to omit locking primitives */
   27595   int rc = SQLITE_OK;            /* Function Return Code */
   27596 
   27597   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   27598   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   27599   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   27600   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   27601   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   27602 #if SQLITE_ENABLE_LOCKING_STYLE
   27603   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
   27604 #endif
   27605 
   27606   /* If creating a master or main-file journal, this function will open
   27607   ** a file-descriptor on the directory too. The first time unixSync()
   27608   ** is called the directory file descriptor will be fsync()ed and close()d.
   27609   */
   27610   int isOpenDirectory = (isCreate && (
   27611         eType==SQLITE_OPEN_MASTER_JOURNAL
   27612      || eType==SQLITE_OPEN_MAIN_JOURNAL
   27613      || eType==SQLITE_OPEN_WAL
   27614   ));
   27615 
   27616   /* If argument zPath is a NULL pointer, this function is required to open
   27617   ** a temporary file. Use this buffer to store the file name in.
   27618   */
   27619   char zTmpname[MAX_PATHNAME+1];
   27620   const char *zName = zPath;
   27621 
   27622   /* Check the following statements are true:
   27623   **
   27624   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   27625   **   (b) if CREATE is set, then READWRITE must also be set, and
   27626   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   27627   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   27628   */
   27629   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   27630   assert(isCreate==0 || isReadWrite);
   27631   assert(isExclusive==0 || isCreate);
   27632   assert(isDelete==0 || isCreate);
   27633 
   27634   /* The main DB, main journal, WAL file and master journal are never
   27635   ** automatically deleted. Nor are they ever temporary files.  */
   27636   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   27637   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   27638   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   27639   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   27640 
   27641   /* Assert that the upper layer has set one of the "file-type" flags. */
   27642   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   27643        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   27644        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   27645        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   27646   );
   27647 
   27648   memset(p, 0, sizeof(unixFile));
   27649 
   27650   if( eType==SQLITE_OPEN_MAIN_DB ){
   27651     UnixUnusedFd *pUnused;
   27652     pUnused = findReusableFd(zName, flags);
   27653     if( pUnused ){
   27654       fd = pUnused->fd;
   27655     }else{
   27656       pUnused = sqlite3_malloc(sizeof(*pUnused));
   27657       if( !pUnused ){
   27658         return SQLITE_NOMEM;
   27659       }
   27660     }
   27661     p->pUnused = pUnused;
   27662   }else if( !zName ){
   27663     /* If zName is NULL, the upper layer is requesting a temp file. */
   27664     assert(isDelete && !isOpenDirectory);
   27665     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
   27666     if( rc!=SQLITE_OK ){
   27667       return rc;
   27668     }
   27669     zName = zTmpname;
   27670   }
   27671 
   27672   /* Determine the value of the flags parameter passed to POSIX function
   27673   ** open(). These must be calculated even if open() is not called, as
   27674   ** they may be stored as part of the file handle and used by the
   27675   ** 'conch file' locking functions later on.  */
   27676   if( isReadonly )  openFlags |= O_RDONLY;
   27677   if( isReadWrite ) openFlags |= O_RDWR;
   27678   if( isCreate )    openFlags |= O_CREAT;
   27679   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
   27680   openFlags |= (O_LARGEFILE|O_BINARY);
   27681 
   27682   if( fd<0 ){
   27683     mode_t openMode;              /* Permissions to create file with */
   27684     rc = findCreateFileMode(zName, flags, &openMode);
   27685     if( rc!=SQLITE_OK ){
   27686       assert( !p->pUnused );
   27687       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
   27688       return rc;
   27689     }
   27690     fd = open(zName, openFlags, openMode);
   27691     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
   27692     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
   27693       /* Failed to open the file for read/write access. Try read-only. */
   27694       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
   27695       openFlags &= ~(O_RDWR|O_CREAT);
   27696       flags |= SQLITE_OPEN_READONLY;
   27697       openFlags |= O_RDONLY;
   27698       fd = open(zName, openFlags, openMode);
   27699     }
   27700     if( fd<0 ){
   27701       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
   27702       goto open_finished;
   27703     }
   27704   }
   27705   assert( fd>=0 );
   27706   if( pOutFlags ){
   27707     *pOutFlags = flags;
   27708   }
   27709 
   27710   if( p->pUnused ){
   27711     p->pUnused->fd = fd;
   27712     p->pUnused->flags = flags;
   27713   }
   27714 
   27715   if( isDelete ){
   27716 #if OS_VXWORKS
   27717     zPath = zName;
   27718 #else
   27719     unlink(zName);
   27720 #endif
   27721   }
   27722 #if SQLITE_ENABLE_LOCKING_STYLE
   27723   else{
   27724     p->openFlags = openFlags;
   27725   }
   27726 #endif
   27727 
   27728   if( isOpenDirectory ){
   27729     rc = openDirectory(zPath, &dirfd);
   27730     if( rc!=SQLITE_OK ){
   27731       /* It is safe to close fd at this point, because it is guaranteed not
   27732       ** to be open on a database file. If it were open on a database file,
   27733       ** it would not be safe to close as this would release any locks held
   27734       ** on the file by this process.  */
   27735       assert( eType!=SQLITE_OPEN_MAIN_DB );
   27736       close(fd);             /* silently leak if fail, already in error */
   27737       goto open_finished;
   27738     }
   27739   }
   27740 
   27741 #ifdef FD_CLOEXEC
   27742   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
   27743 #endif
   27744 
   27745   noLock = eType!=SQLITE_OPEN_MAIN_DB;
   27746 
   27747 
   27748 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   27749   struct statfs fsInfo;
   27750   if( fstatfs(fd, &fsInfo) == -1 ){
   27751     ((unixFile*)pFile)->lastErrno = errno;
   27752     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
   27753     close(fd); /* silently leak if fail, in error */
   27754     return SQLITE_IOERR_ACCESS;
   27755   }
   27756   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
   27757     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
   27758   }
   27759 #endif
   27760 
   27761 #if SQLITE_ENABLE_LOCKING_STYLE
   27762 #if SQLITE_PREFER_PROXY_LOCKING
   27763   isAutoProxy = 1;
   27764 #endif
   27765   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
   27766     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
   27767     int useProxy = 0;
   27768 
   27769     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
   27770     ** never use proxy, NULL means use proxy for non-local files only.  */
   27771     if( envforce!=NULL ){
   27772       useProxy = atoi(envforce)>0;
   27773     }else{
   27774       struct statfs fsInfo;
   27775       if( statfs(zPath, &fsInfo) == -1 ){
   27776         /* In theory, the close(fd) call is sub-optimal. If the file opened
   27777         ** with fd is a database file, and there are other connections open
   27778         ** on that file that are currently holding advisory locks on it,
   27779         ** then the call to close() will cancel those locks. In practice,
   27780         ** we're assuming that statfs() doesn't fail very often. At least
   27781         ** not while other file descriptors opened by the same process on
   27782         ** the same file are working.  */
   27783         p->lastErrno = errno;
   27784         if( dirfd>=0 ){
   27785           close(dirfd); /* silently leak if fail, in error */
   27786         }
   27787         close(fd); /* silently leak if fail, in error */
   27788         rc = SQLITE_IOERR_ACCESS;
   27789         goto open_finished;
   27790       }
   27791       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
   27792     }
   27793     if( useProxy ){
   27794       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
   27795       if( rc==SQLITE_OK ){
   27796         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
   27797         if( rc!=SQLITE_OK ){
   27798           /* Use unixClose to clean up the resources added in fillInUnixFile
   27799           ** and clear all the structure's references.  Specifically,
   27800           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
   27801           */
   27802           unixClose(pFile);
   27803           return rc;
   27804         }
   27805       }
   27806       goto open_finished;
   27807     }
   27808   }
   27809 #endif
   27810 
   27811   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
   27812 open_finished:
   27813   if( rc!=SQLITE_OK ){
   27814     sqlite3_free(p->pUnused);
   27815   }
   27816   return rc;
   27817 }
   27818 
   27819 
   27820 /*
   27821 ** Delete the file at zPath. If the dirSync argument is true, fsync()
   27822 ** the directory after deleting the file.
   27823 */
   27824 static int unixDelete(
   27825   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
   27826   const char *zPath,        /* Name of file to be deleted */
   27827   int dirSync               /* If true, fsync() directory after deleting file */
   27828 ){
   27829   int rc = SQLITE_OK;
   27830   UNUSED_PARAMETER(NotUsed);
   27831   SimulateIOError(return SQLITE_IOERR_DELETE);
   27832   if( unlink(zPath)==(-1) && errno!=ENOENT ){
   27833     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
   27834   }
   27835 #ifndef SQLITE_DISABLE_DIRSYNC
   27836   if( dirSync ){
   27837     int fd;
   27838     rc = openDirectory(zPath, &fd);
   27839     if( rc==SQLITE_OK ){
   27840 #if OS_VXWORKS
   27841       if( fsync(fd)==-1 )
   27842 #else
   27843       if( fsync(fd) )
   27844 #endif
   27845       {
   27846         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
   27847       }
   27848       if( close(fd)&&!rc ){
   27849         rc = unixLogError(SQLITE_IOERR_DIR_CLOSE, "close", zPath);
   27850       }
   27851     }
   27852   }
   27853 #endif
   27854   return rc;
   27855 }
   27856 
   27857 /*
   27858 ** Test the existance of or access permissions of file zPath. The
   27859 ** test performed depends on the value of flags:
   27860 **
   27861 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
   27862 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
   27863 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
   27864 **
   27865 ** Otherwise return 0.
   27866 */
   27867 static int unixAccess(
   27868   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
   27869   const char *zPath,      /* Path of the file to examine */
   27870   int flags,              /* What do we want to learn about the zPath file? */
   27871   int *pResOut            /* Write result boolean here */
   27872 ){
   27873   int amode = 0;
   27874   UNUSED_PARAMETER(NotUsed);
   27875   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   27876   switch( flags ){
   27877     case SQLITE_ACCESS_EXISTS:
   27878       amode = F_OK;
   27879       break;
   27880     case SQLITE_ACCESS_READWRITE:
   27881       amode = W_OK|R_OK;
   27882       break;
   27883     case SQLITE_ACCESS_READ:
   27884       amode = R_OK;
   27885       break;
   27886 
   27887     default:
   27888       assert(!"Invalid flags argument");
   27889   }
   27890   *pResOut = (access(zPath, amode)==0);
   27891   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
   27892     struct stat buf;
   27893     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
   27894       *pResOut = 0;
   27895     }
   27896   }
   27897   return SQLITE_OK;
   27898 }
   27899 
   27900 
   27901 /*
   27902 ** Turn a relative pathname into a full pathname. The relative path
   27903 ** is stored as a nul-terminated string in the buffer pointed to by
   27904 ** zPath.
   27905 **
   27906 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
   27907 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
   27908 ** this buffer before returning.
   27909 */
   27910 static int unixFullPathname(
   27911   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   27912   const char *zPath,            /* Possibly relative input path */
   27913   int nOut,                     /* Size of output buffer in bytes */
   27914   char *zOut                    /* Output buffer */
   27915 ){
   27916 
   27917   /* It's odd to simulate an io-error here, but really this is just
   27918   ** using the io-error infrastructure to test that SQLite handles this
   27919   ** function failing. This function could fail if, for example, the
   27920   ** current working directory has been unlinked.
   27921   */
   27922   SimulateIOError( return SQLITE_ERROR );
   27923 
   27924   assert( pVfs->mxPathname==MAX_PATHNAME );
   27925   UNUSED_PARAMETER(pVfs);
   27926 
   27927   zOut[nOut-1] = '\0';
   27928   if( zPath[0]=='/' ){
   27929     sqlite3_snprintf(nOut, zOut, "%s", zPath);
   27930   }else{
   27931     int nCwd;
   27932     if( getcwd(zOut, nOut-1)==0 ){
   27933       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
   27934     }
   27935     nCwd = (int)strlen(zOut);
   27936     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
   27937   }
   27938   return SQLITE_OK;
   27939 }
   27940 
   27941 
   27942 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   27943 /*
   27944 ** Interfaces for opening a shared library, finding entry points
   27945 ** within the shared library, and closing the shared library.
   27946 */
   27947 #include <dlfcn.h>
   27948 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
   27949   UNUSED_PARAMETER(NotUsed);
   27950   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
   27951 }
   27952 
   27953 /*
   27954 ** SQLite calls this function immediately after a call to unixDlSym() or
   27955 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
   27956 ** message is available, it is written to zBufOut. If no error message
   27957 ** is available, zBufOut is left unmodified and SQLite uses a default
   27958 ** error message.
   27959 */
   27960 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   27961   const char *zErr;
   27962   UNUSED_PARAMETER(NotUsed);
   27963   unixEnterMutex();
   27964   zErr = dlerror();
   27965   if( zErr ){
   27966     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
   27967   }
   27968   unixLeaveMutex();
   27969 }
   27970 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   27971   /*
   27972   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   27973   ** cast into a pointer to a function.  And yet the library dlsym() routine
   27974   ** returns a void* which is really a pointer to a function.  So how do we
   27975   ** use dlsym() with -pedantic-errors?
   27976   **
   27977   ** Variable x below is defined to be a pointer to a function taking
   27978   ** parameters void* and const char* and returning a pointer to a function.
   27979   ** We initialize x by assigning it a pointer to the dlsym() function.
   27980   ** (That assignment requires a cast.)  Then we call the function that
   27981   ** x points to.
   27982   **
   27983   ** This work-around is unlikely to work correctly on any system where
   27984   ** you really cannot cast a function pointer into void*.  But then, on the
   27985   ** other hand, dlsym() will not work on such a system either, so we have
   27986   ** not really lost anything.
   27987   */
   27988   void (*(*x)(void*,const char*))(void);
   27989   UNUSED_PARAMETER(NotUsed);
   27990   x = (void(*(*)(void*,const char*))(void))dlsym;
   27991   return (*x)(p, zSym);
   27992 }
   27993 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
   27994   UNUSED_PARAMETER(NotUsed);
   27995   dlclose(pHandle);
   27996 }
   27997 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   27998   #define unixDlOpen  0
   27999   #define unixDlError 0
   28000   #define unixDlSym   0
   28001   #define unixDlClose 0
   28002 #endif
   28003 
   28004 /*
   28005 ** Write nBuf bytes of random data to the supplied buffer zBuf.
   28006 */
   28007 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   28008   UNUSED_PARAMETER(NotUsed);
   28009   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
   28010 
   28011   /* We have to initialize zBuf to prevent valgrind from reporting
   28012   ** errors.  The reports issued by valgrind are incorrect - we would
   28013   ** prefer that the randomness be increased by making use of the
   28014   ** uninitialized space in zBuf - but valgrind errors tend to worry
   28015   ** some users.  Rather than argue, it seems easier just to initialize
   28016   ** the whole array and silence valgrind, even if that means less randomness
   28017   ** in the random seed.
   28018   **
   28019   ** When testing, initializing zBuf[] to zero is all we do.  That means
   28020   ** that we always use the same random number sequence.  This makes the
   28021   ** tests repeatable.
   28022   */
   28023   memset(zBuf, 0, nBuf);
   28024 #if !defined(SQLITE_TEST)
   28025   {
   28026     int pid, fd;
   28027     fd = open("/dev/urandom", O_RDONLY);
   28028     if( fd<0 ){
   28029       time_t t;
   28030       time(&t);
   28031       memcpy(zBuf, &t, sizeof(t));
   28032       pid = getpid();
   28033       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
   28034       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
   28035       nBuf = sizeof(t) + sizeof(pid);
   28036     }else{
   28037       do{ nBuf = read(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
   28038       close(fd);
   28039     }
   28040   }
   28041 #endif
   28042   return nBuf;
   28043 }
   28044 
   28045 
   28046 /*
   28047 ** Sleep for a little while.  Return the amount of time slept.
   28048 ** The argument is the number of microseconds we want to sleep.
   28049 ** The return value is the number of microseconds of sleep actually
   28050 ** requested from the underlying operating system, a number which
   28051 ** might be greater than or equal to the argument, but not less
   28052 ** than the argument.
   28053 */
   28054 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   28055 #if OS_VXWORKS
   28056   struct timespec sp;
   28057 
   28058   sp.tv_sec = microseconds / 1000000;
   28059   sp.tv_nsec = (microseconds % 1000000) * 1000;
   28060   nanosleep(&sp, NULL);
   28061   UNUSED_PARAMETER(NotUsed);
   28062   return microseconds;
   28063 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
   28064   usleep(microseconds);
   28065   UNUSED_PARAMETER(NotUsed);
   28066   return microseconds;
   28067 #else
   28068   int seconds = (microseconds+999999)/1000000;
   28069   sleep(seconds);
   28070   UNUSED_PARAMETER(NotUsed);
   28071   return seconds*1000000;
   28072 #endif
   28073 }
   28074 
   28075 /*
   28076 ** The following variable, if set to a non-zero value, is interpreted as
   28077 ** the number of seconds since 1970 and is used to set the result of
   28078 ** sqlite3OsCurrentTime() during testing.
   28079 */
   28080 #ifdef SQLITE_TEST
   28081 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   28082 #endif
   28083 
   28084 /*
   28085 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   28086 ** the current time and date as a Julian Day number times 86_400_000.  In
   28087 ** other words, write into *piNow the number of milliseconds since the Julian
   28088 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   28089 ** proleptic Gregorian calendar.
   28090 **
   28091 ** On success, return 0.  Return 1 if the time and date cannot be found.
   28092 */
   28093 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
   28094   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   28095 #if defined(NO_GETTOD)
   28096   time_t t;
   28097   time(&t);
   28098   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
   28099 #elif OS_VXWORKS
   28100   struct timespec sNow;
   28101   clock_gettime(CLOCK_REALTIME, &sNow);
   28102   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
   28103 #else
   28104   struct timeval sNow;
   28105   gettimeofday(&sNow, 0);
   28106   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
   28107 #endif
   28108 
   28109 #ifdef SQLITE_TEST
   28110   if( sqlite3_current_time ){
   28111     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   28112   }
   28113 #endif
   28114   UNUSED_PARAMETER(NotUsed);
   28115   return 0;
   28116 }
   28117 
   28118 /*
   28119 ** Find the current time (in Universal Coordinated Time).  Write the
   28120 ** current time and date as a Julian Day number into *prNow and
   28121 ** return 0.  Return 1 if the time and date cannot be found.
   28122 */
   28123 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
   28124   sqlite3_int64 i;
   28125   UNUSED_PARAMETER(NotUsed);
   28126   unixCurrentTimeInt64(0, &i);
   28127   *prNow = i/86400000.0;
   28128   return 0;
   28129 }
   28130 
   28131 /*
   28132 ** We added the xGetLastError() method with the intention of providing
   28133 ** better low-level error messages when operating-system problems come up
   28134 ** during SQLite operation.  But so far, none of that has been implemented
   28135 ** in the core.  So this routine is never called.  For now, it is merely
   28136 ** a place-holder.
   28137 */
   28138 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
   28139   UNUSED_PARAMETER(NotUsed);
   28140   UNUSED_PARAMETER(NotUsed2);
   28141   UNUSED_PARAMETER(NotUsed3);
   28142   return 0;
   28143 }
   28144 
   28145 
   28146 /*
   28147 ************************ End of sqlite3_vfs methods ***************************
   28148 ******************************************************************************/
   28149 
   28150 /******************************************************************************
   28151 ************************** Begin Proxy Locking ********************************
   28152 **
   28153 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
   28154 ** other locking methods on secondary lock files.  Proxy locking is a
   28155 ** meta-layer over top of the primitive locking implemented above.  For
   28156 ** this reason, the division that implements of proxy locking is deferred
   28157 ** until late in the file (here) after all of the other I/O methods have
   28158 ** been defined - so that the primitive locking methods are available
   28159 ** as services to help with the implementation of proxy locking.
   28160 **
   28161 ****
   28162 **
   28163 ** The default locking schemes in SQLite use byte-range locks on the
   28164 ** database file to coordinate safe, concurrent access by multiple readers
   28165 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
   28166 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
   28167 ** as POSIX read & write locks over fixed set of locations (via fsctl),
   28168 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
   28169 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
   28170 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
   28171 ** address in the shared range is taken for a SHARED lock, the entire
   28172 ** shared range is taken for an EXCLUSIVE lock):
   28173 **
   28174 **      PENDING_BYTE        0x40000000
   28175 **      RESERVED_BYTE       0x40000001
   28176 **      SHARED_RANGE        0x40000002 -> 0x40000200
   28177 **
   28178 ** This works well on the local file system, but shows a nearly 100x
   28179 ** slowdown in read performance on AFP because the AFP client disables
   28180 ** the read cache when byte-range locks are present.  Enabling the read
   28181 ** cache exposes a cache coherency problem that is present on all OS X
   28182 ** supported network file systems.  NFS and AFP both observe the
   28183 ** close-to-open semantics for ensuring cache coherency
   28184 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
   28185 ** address the requirements for concurrent database access by multiple
   28186 ** readers and writers
   28187 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
   28188 **
   28189 ** To address the performance and cache coherency issues, proxy file locking
   28190 ** changes the way database access is controlled by limiting access to a
   28191 ** single host at a time and moving file locks off of the database file
   28192 ** and onto a proxy file on the local file system.
   28193 **
   28194 **
   28195 ** Using proxy locks
   28196 ** -----------------
   28197 **
   28198 ** C APIs
   28199 **
   28200 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
   28201 **                       <proxy_path> | ":auto:");
   28202 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
   28203 **
   28204 **
   28205 ** SQL pragmas
   28206 **
   28207 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
   28208 **  PRAGMA [database.]lock_proxy_file
   28209 **
   28210 ** Specifying ":auto:" means that if there is a conch file with a matching
   28211 ** host ID in it, the proxy path in the conch file will be used, otherwise
   28212 ** a proxy path based on the user's temp dir
   28213 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
   28214 ** actual proxy file name is generated from the name and path of the
   28215 ** database file.  For example:
   28216 **
   28217 **       For database path "/Users/me/foo.db"
   28218 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
   28219 **
   28220 ** Once a lock proxy is configured for a database connection, it can not
   28221 ** be removed, however it may be switched to a different proxy path via
   28222 ** the above APIs (assuming the conch file is not being held by another
   28223 ** connection or process).
   28224 **
   28225 **
   28226 ** How proxy locking works
   28227 ** -----------------------
   28228 **
   28229 ** Proxy file locking relies primarily on two new supporting files:
   28230 **
   28231 **   *  conch file to limit access to the database file to a single host
   28232 **      at a time
   28233 **
   28234 **   *  proxy file to act as a proxy for the advisory locks normally
   28235 **      taken on the database
   28236 **
   28237 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
   28238 ** by taking an sqlite-style shared lock on the conch file, reading the
   28239 ** contents and comparing the host's unique host ID (see below) and lock
   28240 ** proxy path against the values stored in the conch.  The conch file is
   28241 ** stored in the same directory as the database file and the file name
   28242 ** is patterned after the database file name as ".<databasename>-conch".
   28243 ** If the conch file does not exist, or it's contents do not match the
   28244 ** host ID and/or proxy path, then the lock is escalated to an exclusive
   28245 ** lock and the conch file contents is updated with the host ID and proxy
   28246 ** path and the lock is downgraded to a shared lock again.  If the conch
   28247 ** is held by another process (with a shared lock), the exclusive lock
   28248 ** will fail and SQLITE_BUSY is returned.
   28249 **
   28250 ** The proxy file - a single-byte file used for all advisory file locks
   28251 ** normally taken on the database file.   This allows for safe sharing
   28252 ** of the database file for multiple readers and writers on the same
   28253 ** host (the conch ensures that they all use the same local lock file).
   28254 **
   28255 ** Requesting the lock proxy does not immediately take the conch, it is
   28256 ** only taken when the first request to lock database file is made.
   28257 ** This matches the semantics of the traditional locking behavior, where
   28258 ** opening a connection to a database file does not take a lock on it.
   28259 ** The shared lock and an open file descriptor are maintained until
   28260 ** the connection to the database is closed.
   28261 **
   28262 ** The proxy file and the lock file are never deleted so they only need
   28263 ** to be created the first time they are used.
   28264 **
   28265 ** Configuration options
   28266 ** ---------------------
   28267 **
   28268 **  SQLITE_PREFER_PROXY_LOCKING
   28269 **
   28270 **       Database files accessed on non-local file systems are
   28271 **       automatically configured for proxy locking, lock files are
   28272 **       named automatically using the same logic as
   28273 **       PRAGMA lock_proxy_file=":auto:"
   28274 **
   28275 **  SQLITE_PROXY_DEBUG
   28276 **
   28277 **       Enables the logging of error messages during host id file
   28278 **       retrieval and creation
   28279 **
   28280 **  LOCKPROXYDIR
   28281 **
   28282 **       Overrides the default directory used for lock proxy files that
   28283 **       are named automatically via the ":auto:" setting
   28284 **
   28285 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
   28286 **
   28287 **       Permissions to use when creating a directory for storing the
   28288 **       lock proxy files, only used when LOCKPROXYDIR is not set.
   28289 **
   28290 **
   28291 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
   28292 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
   28293 ** force proxy locking to be used for every database file opened, and 0
   28294 ** will force automatic proxy locking to be disabled for all database
   28295 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
   28296 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
   28297 */
   28298 
   28299 /*
   28300 ** Proxy locking is only available on MacOSX
   28301 */
   28302 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
   28303 
   28304 /*
   28305 ** The proxyLockingContext has the path and file structures for the remote
   28306 ** and local proxy files in it
   28307 */
   28308 typedef struct proxyLockingContext proxyLockingContext;
   28309 struct proxyLockingContext {
   28310   unixFile *conchFile;         /* Open conch file */
   28311   char *conchFilePath;         /* Name of the conch file */
   28312   unixFile *lockProxy;         /* Open proxy lock file */
   28313   char *lockProxyPath;         /* Name of the proxy lock file */
   28314   char *dbPath;                /* Name of the open file */
   28315   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
   28316   void *oldLockingContext;     /* Original lockingcontext to restore on close */
   28317   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
   28318 };
   28319 
   28320 /*
   28321 ** The proxy lock file path for the database at dbPath is written into lPath,
   28322 ** which must point to valid, writable memory large enough for a maxLen length
   28323 ** file path.
   28324 */
   28325 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   28326   int len;
   28327   int dbLen;
   28328   int i;
   28329 
   28330 #ifdef LOCKPROXYDIR
   28331   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
   28332 #else
   28333 # ifdef _CS_DARWIN_USER_TEMP_DIR
   28334   {
   28335     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
   28336       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
   28337                lPath, errno, getpid()));
   28338       return SQLITE_IOERR_LOCK;
   28339     }
   28340     len = strlcat(lPath, "sqliteplocks", maxLen);
   28341   }
   28342 # else
   28343   len = strlcpy(lPath, "/tmp/", maxLen);
   28344 # endif
   28345 #endif
   28346 
   28347   if( lPath[len-1]!='/' ){
   28348     len = strlcat(lPath, "/", maxLen);
   28349   }
   28350 
   28351   /* transform the db path to a unique cache name */
   28352   dbLen = (int)strlen(dbPath);
   28353   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
   28354     char c = dbPath[i];
   28355     lPath[i+len] = (c=='/')?'_':c;
   28356   }
   28357   lPath[i+len]='\0';
   28358   strlcat(lPath, ":auto:", maxLen);
   28359   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
   28360   return SQLITE_OK;
   28361 }
   28362 
   28363 /*
   28364  ** Creates the lock file and any missing directories in lockPath
   28365  */
   28366 static int proxyCreateLockPath(const char *lockPath){
   28367   int i, len;
   28368   char buf[MAXPATHLEN];
   28369   int start = 0;
   28370 
   28371   assert(lockPath!=NULL);
   28372   /* try to create all the intermediate directories */
   28373   len = (int)strlen(lockPath);
   28374   buf[0] = lockPath[0];
   28375   for( i=1; i<len; i++ ){
   28376     if( lockPath[i] == '/' && (i - start > 0) ){
   28377       /* only mkdir if leaf dir != "." or "/" or ".." */
   28378       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
   28379          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
   28380         buf[i]='\0';
   28381         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
   28382           int err=errno;
   28383           if( err!=EEXIST ) {
   28384             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
   28385                      "'%s' proxy lock path=%s pid=%d\n",
   28386                      buf, strerror(err), lockPath, getpid()));
   28387             return err;
   28388           }
   28389         }
   28390       }
   28391       start=i+1;
   28392     }
   28393     buf[i] = lockPath[i];
   28394   }
   28395   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
   28396   return 0;
   28397 }
   28398 
   28399 /*
   28400 ** Create a new VFS file descriptor (stored in memory obtained from
   28401 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
   28402 **
   28403 ** The caller is responsible not only for closing the file descriptor
   28404 ** but also for freeing the memory associated with the file descriptor.
   28405 */
   28406 static int proxyCreateUnixFile(
   28407     const char *path,        /* path for the new unixFile */
   28408     unixFile **ppFile,       /* unixFile created and returned by ref */
   28409     int islockfile           /* if non zero missing dirs will be created */
   28410 ) {
   28411   int fd = -1;
   28412   int dirfd = -1;
   28413   unixFile *pNew;
   28414   int rc = SQLITE_OK;
   28415   int openFlags = O_RDWR | O_CREAT;
   28416   sqlite3_vfs dummyVfs;
   28417   int terrno = 0;
   28418   UnixUnusedFd *pUnused = NULL;
   28419 
   28420   /* 1. first try to open/create the file
   28421   ** 2. if that fails, and this is a lock file (not-conch), try creating
   28422   ** the parent directories and then try again.
   28423   ** 3. if that fails, try to open the file read-only
   28424   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
   28425   */
   28426   pUnused = findReusableFd(path, openFlags);
   28427   if( pUnused ){
   28428     fd = pUnused->fd;
   28429   }else{
   28430     pUnused = sqlite3_malloc(sizeof(*pUnused));
   28431     if( !pUnused ){
   28432       return SQLITE_NOMEM;
   28433     }
   28434   }
   28435   if( fd<0 ){
   28436     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   28437     terrno = errno;
   28438     if( fd<0 && errno==ENOENT && islockfile ){
   28439       if( proxyCreateLockPath(path) == SQLITE_OK ){
   28440         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   28441       }
   28442     }
   28443   }
   28444   if( fd<0 ){
   28445     openFlags = O_RDONLY;
   28446     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
   28447     terrno = errno;
   28448   }
   28449   if( fd<0 ){
   28450     if( islockfile ){
   28451       return SQLITE_BUSY;
   28452     }
   28453     switch (terrno) {
   28454       case EACCES:
   28455         return SQLITE_PERM;
   28456       case EIO:
   28457         return SQLITE_IOERR_LOCK; /* even though it is the conch */
   28458       default:
   28459         return SQLITE_CANTOPEN_BKPT;
   28460     }
   28461   }
   28462 
   28463   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
   28464   if( pNew==NULL ){
   28465     rc = SQLITE_NOMEM;
   28466     goto end_create_proxy;
   28467   }
   28468   memset(pNew, 0, sizeof(unixFile));
   28469   pNew->openFlags = openFlags;
   28470   dummyVfs.pAppData = (void*)&autolockIoFinder;
   28471   pUnused->fd = fd;
   28472   pUnused->flags = openFlags;
   28473   pNew->pUnused = pUnused;
   28474 
   28475   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
   28476   if( rc==SQLITE_OK ){
   28477     *ppFile = pNew;
   28478     return SQLITE_OK;
   28479   }
   28480 end_create_proxy:
   28481   close(fd); /* silently leak fd if error, we're already in error */
   28482   sqlite3_free(pNew);
   28483   sqlite3_free(pUnused);
   28484   return rc;
   28485 }
   28486 
   28487 #ifdef SQLITE_TEST
   28488 /* simulate multiple hosts by creating unique hostid file paths */
   28489 SQLITE_API int sqlite3_hostid_num = 0;
   28490 #endif
   28491 
   28492 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
   28493 
   28494 /* Not always defined in the headers as it ought to be */
   28495 extern int gethostuuid(uuid_t id, const struct timespec *wait);
   28496 
   28497 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
   28498 ** bytes of writable memory.
   28499 */
   28500 static int proxyGetHostID(unsigned char *pHostID, int *pError){
   28501   struct timespec timeout = {1, 0}; /* 1 sec timeout */
   28502 
   28503   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
   28504   memset(pHostID, 0, PROXY_HOSTIDLEN);
   28505 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
   28506                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
   28507   if( gethostuuid(pHostID, &timeout) ){
   28508     int err = errno;
   28509     if( pError ){
   28510       *pError = err;
   28511     }
   28512     return SQLITE_IOERR;
   28513   }
   28514 #endif
   28515 #ifdef SQLITE_TEST
   28516   /* simulate multiple hosts by creating unique hostid file paths */
   28517   if( sqlite3_hostid_num != 0){
   28518     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   28519   }
   28520 #endif
   28521 
   28522   return SQLITE_OK;
   28523 }
   28524 
   28525 /* The conch file contains the header, host id and lock file path
   28526  */
   28527 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
   28528 #define PROXY_HEADERLEN    1   /* conch file header length */
   28529 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
   28530 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
   28531 
   28532 /*
   28533 ** Takes an open conch file, copies the contents to a new path and then moves
   28534 ** it back.  The newly created file's file descriptor is assigned to the
   28535 ** conch file structure and finally the original conch file descriptor is
   28536 ** closed.  Returns zero if successful.
   28537 */
   28538 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
   28539   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   28540   unixFile *conchFile = pCtx->conchFile;
   28541   char tPath[MAXPATHLEN];
   28542   char buf[PROXY_MAXCONCHLEN];
   28543   char *cPath = pCtx->conchFilePath;
   28544   size_t readLen = 0;
   28545   size_t pathLen = 0;
   28546   char errmsg[64] = "";
   28547   int fd = -1;
   28548   int rc = -1;
   28549   UNUSED_PARAMETER(myHostID);
   28550 
   28551   /* create a new path by replace the trailing '-conch' with '-break' */
   28552   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
   28553   if( pathLen>MAXPATHLEN || pathLen<6 ||
   28554      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
   28555     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
   28556     goto end_breaklock;
   28557   }
   28558   /* read the conch content */
   28559   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
   28560   if( readLen<PROXY_PATHINDEX ){
   28561     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
   28562     goto end_breaklock;
   28563   }
   28564   /* write it out to the temporary break file */
   28565   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
   28566   if( fd<0 ){
   28567     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
   28568     goto end_breaklock;
   28569   }
   28570   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
   28571     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
   28572     goto end_breaklock;
   28573   }
   28574   if( rename(tPath, cPath) ){
   28575     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
   28576     goto end_breaklock;
   28577   }
   28578   rc = 0;
   28579   fprintf(stderr, "broke stale lock on %s\n", cPath);
   28580   close(conchFile->h);
   28581   conchFile->h = fd;
   28582   conchFile->openFlags = O_RDWR | O_CREAT;
   28583 
   28584 end_breaklock:
   28585   if( rc ){
   28586     if( fd>=0 ){
   28587       unlink(tPath);
   28588       close(fd);
   28589     }
   28590     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
   28591   }
   28592   return rc;
   28593 }
   28594 
   28595 /* Take the requested lock on the conch file and break a stale lock if the
   28596 ** host id matches.
   28597 */
   28598 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
   28599   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   28600   unixFile *conchFile = pCtx->conchFile;
   28601   int rc = SQLITE_OK;
   28602   int nTries = 0;
   28603   struct timespec conchModTime;
   28604 
   28605   do {
   28606     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   28607     nTries ++;
   28608     if( rc==SQLITE_BUSY ){
   28609       /* If the lock failed (busy):
   28610        * 1st try: get the mod time of the conch, wait 0.5s and try again.
   28611        * 2nd try: fail if the mod time changed or host id is different, wait
   28612        *           10 sec and try again
   28613        * 3rd try: break the lock unless the mod time has changed.
   28614        */
   28615       struct stat buf;
   28616       if( fstat(conchFile->h, &buf) ){
   28617         pFile->lastErrno = errno;
   28618         return SQLITE_IOERR_LOCK;
   28619       }
   28620 
   28621       if( nTries==1 ){
   28622         conchModTime = buf.st_mtimespec;
   28623         usleep(500000); /* wait 0.5 sec and try the lock again*/
   28624         continue;
   28625       }
   28626 
   28627       assert( nTries>1 );
   28628       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
   28629          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
   28630         return SQLITE_BUSY;
   28631       }
   28632 
   28633       if( nTries==2 ){
   28634         char tBuf[PROXY_MAXCONCHLEN];
   28635         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
   28636         if( len<0 ){
   28637           pFile->lastErrno = errno;
   28638           return SQLITE_IOERR_LOCK;
   28639         }
   28640         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
   28641           /* don't break the lock if the host id doesn't match */
   28642           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
   28643             return SQLITE_BUSY;
   28644           }
   28645         }else{
   28646           /* don't break the lock on short read or a version mismatch */
   28647           return SQLITE_BUSY;
   28648         }
   28649         usleep(10000000); /* wait 10 sec and try the lock again */
   28650         continue;
   28651       }
   28652 
   28653       assert( nTries==3 );
   28654       if( 0==proxyBreakConchLock(pFile, myHostID) ){
   28655         rc = SQLITE_OK;
   28656         if( lockType==EXCLUSIVE_LOCK ){
   28657           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
   28658         }
   28659         if( !rc ){
   28660           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
   28661         }
   28662       }
   28663     }
   28664   } while( rc==SQLITE_BUSY && nTries<3 );
   28665 
   28666   return rc;
   28667 }
   28668 
   28669 /* Takes the conch by taking a shared lock and read the contents conch, if
   28670 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
   28671 ** lockPath means that the lockPath in the conch file will be used if the
   28672 ** host IDs match, or a new lock path will be generated automatically
   28673 ** and written to the conch file.
   28674 */
   28675 static int proxyTakeConch(unixFile *pFile){
   28676   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   28677 
   28678   if( pCtx->conchHeld!=0 ){
   28679     return SQLITE_OK;
   28680   }else{
   28681     unixFile *conchFile = pCtx->conchFile;
   28682     uuid_t myHostID;
   28683     int pError = 0;
   28684     char readBuf[PROXY_MAXCONCHLEN];
   28685     char lockPath[MAXPATHLEN];
   28686     char *tempLockPath = NULL;
   28687     int rc = SQLITE_OK;
   28688     int createConch = 0;
   28689     int hostIdMatch = 0;
   28690     int readLen = 0;
   28691     int tryOldLockPath = 0;
   28692     int forceNewLockPath = 0;
   28693 
   28694     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
   28695              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
   28696 
   28697     rc = proxyGetHostID(myHostID, &pError);
   28698     if( (rc&0xff)==SQLITE_IOERR ){
   28699       pFile->lastErrno = pError;
   28700       goto end_takeconch;
   28701     }
   28702     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
   28703     if( rc!=SQLITE_OK ){
   28704       goto end_takeconch;
   28705     }
   28706     /* read the existing conch file */
   28707     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
   28708     if( readLen<0 ){
   28709       /* I/O error: lastErrno set by seekAndRead */
   28710       pFile->lastErrno = conchFile->lastErrno;
   28711       rc = SQLITE_IOERR_READ;
   28712       goto end_takeconch;
   28713     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
   28714              readBuf[0]!=(char)PROXY_CONCHVERSION ){
   28715       /* a short read or version format mismatch means we need to create a new
   28716       ** conch file.
   28717       */
   28718       createConch = 1;
   28719     }
   28720     /* if the host id matches and the lock path already exists in the conch
   28721     ** we'll try to use the path there, if we can't open that path, we'll
   28722     ** retry with a new auto-generated path
   28723     */
   28724     do { /* in case we need to try again for an :auto: named lock file */
   28725 
   28726       if( !createConch && !forceNewLockPath ){
   28727         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
   28728                                   PROXY_HOSTIDLEN);
   28729         /* if the conch has data compare the contents */
   28730         if( !pCtx->lockProxyPath ){
   28731           /* for auto-named local lock file, just check the host ID and we'll
   28732            ** use the local lock file path that's already in there
   28733            */
   28734           if( hostIdMatch ){
   28735             size_t pathLen = (readLen - PROXY_PATHINDEX);
   28736 
   28737             if( pathLen>=MAXPATHLEN ){
   28738               pathLen=MAXPATHLEN-1;
   28739             }
   28740             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
   28741             lockPath[pathLen] = 0;
   28742             tempLockPath = lockPath;
   28743             tryOldLockPath = 1;
   28744             /* create a copy of the lock path if the conch is taken */
   28745             goto end_takeconch;
   28746           }
   28747         }else if( hostIdMatch
   28748                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
   28749                            readLen-PROXY_PATHINDEX)
   28750         ){
   28751           /* conch host and lock path match */
   28752           goto end_takeconch;
   28753         }
   28754       }
   28755 
   28756       /* if the conch isn't writable and doesn't match, we can't take it */
   28757       if( (conchFile->openFlags&O_RDWR) == 0 ){
   28758         rc = SQLITE_BUSY;
   28759         goto end_takeconch;
   28760       }
   28761 
   28762       /* either the conch didn't match or we need to create a new one */
   28763       if( !pCtx->lockProxyPath ){
   28764         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
   28765         tempLockPath = lockPath;
   28766         /* create a copy of the lock path _only_ if the conch is taken */
   28767       }
   28768 
   28769       /* update conch with host and path (this will fail if other process
   28770       ** has a shared lock already), if the host id matches, use the big
   28771       ** stick.
   28772       */
   28773       futimes(conchFile->h, NULL);
   28774       if( hostIdMatch && !createConch ){
   28775         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
   28776           /* We are trying for an exclusive lock but another thread in this
   28777            ** same process is still holding a shared lock. */
   28778           rc = SQLITE_BUSY;
   28779         } else {
   28780           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
   28781         }
   28782       }else{
   28783         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
   28784       }
   28785       if( rc==SQLITE_OK ){
   28786         char writeBuffer[PROXY_MAXCONCHLEN];
   28787         int writeSize = 0;
   28788 
   28789         writeBuffer[0] = (char)PROXY_CONCHVERSION;
   28790         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
   28791         if( pCtx->lockProxyPath!=NULL ){
   28792           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
   28793         }else{
   28794           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
   28795         }
   28796         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
   28797         robust_ftruncate(conchFile->h, writeSize);
   28798         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
   28799         fsync(conchFile->h);
   28800         /* If we created a new conch file (not just updated the contents of a
   28801          ** valid conch file), try to match the permissions of the database
   28802          */
   28803         if( rc==SQLITE_OK && createConch ){
   28804           struct stat buf;
   28805           int rc;
   28806           int err = fstat(pFile->h, &buf);
   28807           if( err==0 ){
   28808             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
   28809                                         S_IROTH|S_IWOTH);
   28810             /* try to match the database file R/W permissions, ignore failure */
   28811 #ifndef SQLITE_PROXY_DEBUG
   28812             fchmod(conchFile->h, cmode);
   28813 #else
   28814             do{
   28815               rc = fchmod(conchFile->h, cmode);
   28816             }while( rc==(-1) && errno==EINTR );
   28817             if( rc!=0 ){
   28818               int code = errno;
   28819               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
   28820                       cmode, code, strerror(code));
   28821             } else {
   28822               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
   28823             }
   28824           }else{
   28825             int code = errno;
   28826             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
   28827                     err, code, strerror(code));
   28828 #endif
   28829           }
   28830         }
   28831       }
   28832       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
   28833 
   28834     end_takeconch:
   28835       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
   28836       if( rc==SQLITE_OK && pFile->openFlags ){
   28837         if( pFile->h>=0 ){
   28838 #ifdef STRICT_CLOSE_ERROR
   28839           if( close(pFile->h) ){
   28840             pFile->lastErrno = errno;
   28841             return SQLITE_IOERR_CLOSE;
   28842           }
   28843 #else
   28844           close(pFile->h); /* silently leak fd if fail */
   28845 #endif
   28846         }
   28847         pFile->h = -1;
   28848         int fd = open(pCtx->dbPath, pFile->openFlags,
   28849                       SQLITE_DEFAULT_FILE_PERMISSIONS);
   28850         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
   28851         if( fd>=0 ){
   28852           pFile->h = fd;
   28853         }else{
   28854           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
   28855            during locking */
   28856         }
   28857       }
   28858       if( rc==SQLITE_OK && !pCtx->lockProxy ){
   28859         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
   28860         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
   28861         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
   28862           /* we couldn't create the proxy lock file with the old lock file path
   28863            ** so try again via auto-naming
   28864            */
   28865           forceNewLockPath = 1;
   28866           tryOldLockPath = 0;
   28867           continue; /* go back to the do {} while start point, try again */
   28868         }
   28869       }
   28870       if( rc==SQLITE_OK ){
   28871         /* Need to make a copy of path if we extracted the value
   28872          ** from the conch file or the path was allocated on the stack
   28873          */
   28874         if( tempLockPath ){
   28875           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
   28876           if( !pCtx->lockProxyPath ){
   28877             rc = SQLITE_NOMEM;
   28878           }
   28879         }
   28880       }
   28881       if( rc==SQLITE_OK ){
   28882         pCtx->conchHeld = 1;
   28883 
   28884         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
   28885           afpLockingContext *afpCtx;
   28886           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
   28887           afpCtx->dbPath = pCtx->lockProxyPath;
   28888         }
   28889       } else {
   28890         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   28891       }
   28892       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
   28893                rc==SQLITE_OK?"ok":"failed"));
   28894       return rc;
   28895     } while (1); /* in case we need to retry the :auto: lock file -
   28896                  ** we should never get here except via the 'continue' call. */
   28897   }
   28898 }
   28899 
   28900 /*
   28901 ** If pFile holds a lock on a conch file, then release that lock.
   28902 */
   28903 static int proxyReleaseConch(unixFile *pFile){
   28904   int rc = SQLITE_OK;         /* Subroutine return code */
   28905   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
   28906   unixFile *conchFile;        /* Name of the conch file */
   28907 
   28908   pCtx = (proxyLockingContext *)pFile->lockingContext;
   28909   conchFile = pCtx->conchFile;
   28910   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
   28911            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
   28912            getpid()));
   28913   if( pCtx->conchHeld>0 ){
   28914     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
   28915   }
   28916   pCtx->conchHeld = 0;
   28917   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
   28918            (rc==SQLITE_OK ? "ok" : "failed")));
   28919   return rc;
   28920 }
   28921 
   28922 /*
   28923 ** Given the name of a database file, compute the name of its conch file.
   28924 ** Store the conch filename in memory obtained from sqlite3_malloc().
   28925 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
   28926 ** or SQLITE_NOMEM if unable to obtain memory.
   28927 **
   28928 ** The caller is responsible for ensuring that the allocated memory
   28929 ** space is eventually freed.
   28930 **
   28931 ** *pConchPath is set to NULL if a memory allocation error occurs.
   28932 */
   28933 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   28934   int i;                        /* Loop counter */
   28935   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
   28936   char *conchPath;              /* buffer in which to construct conch name */
   28937 
   28938   /* Allocate space for the conch filename and initialize the name to
   28939   ** the name of the original database file. */
   28940   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
   28941   if( conchPath==0 ){
   28942     return SQLITE_NOMEM;
   28943   }
   28944   memcpy(conchPath, dbPath, len+1);
   28945 
   28946   /* now insert a "." before the last / character */
   28947   for( i=(len-1); i>=0; i-- ){
   28948     if( conchPath[i]=='/' ){
   28949       i++;
   28950       break;
   28951     }
   28952   }
   28953   conchPath[i]='.';
   28954   while ( i<len ){
   28955     conchPath[i+1]=dbPath[i];
   28956     i++;
   28957   }
   28958 
   28959   /* append the "-conch" suffix to the file */
   28960   memcpy(&conchPath[i+1], "-conch", 7);
   28961   assert( (int)strlen(conchPath) == len+7 );
   28962 
   28963   return SQLITE_OK;
   28964 }
   28965 
   28966 
   28967 /* Takes a fully configured proxy locking-style unix file and switches
   28968 ** the local lock file path
   28969 */
   28970 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   28971   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   28972   char *oldPath = pCtx->lockProxyPath;
   28973   int rc = SQLITE_OK;
   28974 
   28975   if( pFile->eFileLock!=NO_LOCK ){
   28976     return SQLITE_BUSY;
   28977   }
   28978 
   28979   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   28980   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
   28981     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
   28982     return SQLITE_OK;
   28983   }else{
   28984     unixFile *lockProxy = pCtx->lockProxy;
   28985     pCtx->lockProxy=NULL;
   28986     pCtx->conchHeld = 0;
   28987     if( lockProxy!=NULL ){
   28988       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
   28989       if( rc ) return rc;
   28990       sqlite3_free(lockProxy);
   28991     }
   28992     sqlite3_free(oldPath);
   28993     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   28994   }
   28995 
   28996   return rc;
   28997 }
   28998 
   28999 /*
   29000 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
   29001 ** is a string buffer at least MAXPATHLEN+1 characters in size.
   29002 **
   29003 ** This routine find the filename associated with pFile and writes it
   29004 ** int dbPath.
   29005 */
   29006 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
   29007 #if defined(__APPLE__)
   29008   if( pFile->pMethod == &afpIoMethods ){
   29009     /* afp style keeps a reference to the db path in the filePath field
   29010     ** of the struct */
   29011     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   29012     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
   29013   } else
   29014 #endif
   29015   if( pFile->pMethod == &dotlockIoMethods ){
   29016     /* dot lock style uses the locking context to store the dot lock
   29017     ** file path */
   29018     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
   29019     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
   29020   }else{
   29021     /* all other styles use the locking context to store the db file path */
   29022     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
   29023     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
   29024   }
   29025   return SQLITE_OK;
   29026 }
   29027 
   29028 /*
   29029 ** Takes an already filled in unix file and alters it so all file locking
   29030 ** will be performed on the local proxy lock file.  The following fields
   29031 ** are preserved in the locking context so that they can be restored and
   29032 ** the unix structure properly cleaned up at close time:
   29033 **  ->lockingContext
   29034 **  ->pMethod
   29035 */
   29036 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   29037   proxyLockingContext *pCtx;
   29038   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   29039   char *lockPath=NULL;
   29040   int rc = SQLITE_OK;
   29041 
   29042   if( pFile->eFileLock!=NO_LOCK ){
   29043     return SQLITE_BUSY;
   29044   }
   29045   proxyGetDbPathForUnixFile(pFile, dbPath);
   29046   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
   29047     lockPath=NULL;
   29048   }else{
   29049     lockPath=(char *)path;
   29050   }
   29051 
   29052   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
   29053            (lockPath ? lockPath : ":auto:"), getpid()));
   29054 
   29055   pCtx = sqlite3_malloc( sizeof(*pCtx) );
   29056   if( pCtx==0 ){
   29057     return SQLITE_NOMEM;
   29058   }
   29059   memset(pCtx, 0, sizeof(*pCtx));
   29060 
   29061   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
   29062   if( rc==SQLITE_OK ){
   29063     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
   29064     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
   29065       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
   29066       ** (c) the file system is read-only, then enable no-locking access.
   29067       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
   29068       ** that openFlags will have only one of O_RDONLY or O_RDWR.
   29069       */
   29070       struct statfs fsInfo;
   29071       struct stat conchInfo;
   29072       int goLockless = 0;
   29073 
   29074       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
   29075         int err = errno;
   29076         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
   29077           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
   29078         }
   29079       }
   29080       if( goLockless ){
   29081         pCtx->conchHeld = -1; /* read only FS/ lockless */
   29082         rc = SQLITE_OK;
   29083       }
   29084     }
   29085   }
   29086   if( rc==SQLITE_OK && lockPath ){
   29087     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   29088   }
   29089 
   29090   if( rc==SQLITE_OK ){
   29091     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
   29092     if( pCtx->dbPath==NULL ){
   29093       rc = SQLITE_NOMEM;
   29094     }
   29095   }
   29096   if( rc==SQLITE_OK ){
   29097     /* all memory is allocated, proxys are created and assigned,
   29098     ** switch the locking context and pMethod then return.
   29099     */
   29100     pCtx->oldLockingContext = pFile->lockingContext;
   29101     pFile->lockingContext = pCtx;
   29102     pCtx->pOldMethod = pFile->pMethod;
   29103     pFile->pMethod = &proxyIoMethods;
   29104   }else{
   29105     if( pCtx->conchFile ){
   29106       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
   29107       sqlite3_free(pCtx->conchFile);
   29108     }
   29109     sqlite3DbFree(0, pCtx->lockProxyPath);
   29110     sqlite3_free(pCtx->conchFilePath);
   29111     sqlite3_free(pCtx);
   29112   }
   29113   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
   29114            (rc==SQLITE_OK ? "ok" : "failed")));
   29115   return rc;
   29116 }
   29117 
   29118 
   29119 /*
   29120 ** This routine handles sqlite3_file_control() calls that are specific
   29121 ** to proxy locking.
   29122 */
   29123 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
   29124   switch( op ){
   29125     case SQLITE_GET_LOCKPROXYFILE: {
   29126       unixFile *pFile = (unixFile*)id;
   29127       if( pFile->pMethod == &proxyIoMethods ){
   29128         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
   29129         proxyTakeConch(pFile);
   29130         if( pCtx->lockProxyPath ){
   29131           *(const char **)pArg = pCtx->lockProxyPath;
   29132         }else{
   29133           *(const char **)pArg = ":auto: (not held)";
   29134         }
   29135       } else {
   29136         *(const char **)pArg = NULL;
   29137       }
   29138       return SQLITE_OK;
   29139     }
   29140     case SQLITE_SET_LOCKPROXYFILE: {
   29141       unixFile *pFile = (unixFile*)id;
   29142       int rc = SQLITE_OK;
   29143       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
   29144       if( pArg==NULL || (const char *)pArg==0 ){
   29145         if( isProxyStyle ){
   29146           /* turn off proxy locking - not supported */
   29147           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
   29148         }else{
   29149           /* turn off proxy locking - already off - NOOP */
   29150           rc = SQLITE_OK;
   29151         }
   29152       }else{
   29153         const char *proxyPath = (const char *)pArg;
   29154         if( isProxyStyle ){
   29155           proxyLockingContext *pCtx =
   29156             (proxyLockingContext*)pFile->lockingContext;
   29157           if( !strcmp(pArg, ":auto:")
   29158            || (pCtx->lockProxyPath &&
   29159                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
   29160           ){
   29161             rc = SQLITE_OK;
   29162           }else{
   29163             rc = switchLockProxyPath(pFile, proxyPath);
   29164           }
   29165         }else{
   29166           /* turn on proxy file locking */
   29167           rc = proxyTransformUnixFile(pFile, proxyPath);
   29168         }
   29169       }
   29170       return rc;
   29171     }
   29172     default: {
   29173       assert( 0 );  /* The call assures that only valid opcodes are sent */
   29174     }
   29175   }
   29176   /*NOTREACHED*/
   29177   return SQLITE_ERROR;
   29178 }
   29179 
   29180 /*
   29181 ** Within this division (the proxying locking implementation) the procedures
   29182 ** above this point are all utilities.  The lock-related methods of the
   29183 ** proxy-locking sqlite3_io_method object follow.
   29184 */
   29185 
   29186 
   29187 /*
   29188 ** This routine checks if there is a RESERVED lock held on the specified
   29189 ** file by this or any other process. If such a lock is held, set *pResOut
   29190 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
   29191 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
   29192 */
   29193 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
   29194   unixFile *pFile = (unixFile*)id;
   29195   int rc = proxyTakeConch(pFile);
   29196   if( rc==SQLITE_OK ){
   29197     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   29198     if( pCtx->conchHeld>0 ){
   29199       unixFile *proxy = pCtx->lockProxy;
   29200       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
   29201     }else{ /* conchHeld < 0 is lockless */
   29202       pResOut=0;
   29203     }
   29204   }
   29205   return rc;
   29206 }
   29207 
   29208 /*
   29209 ** Lock the file with the lock specified by parameter eFileLock - one
   29210 ** of the following:
   29211 **
   29212 **     (1) SHARED_LOCK
   29213 **     (2) RESERVED_LOCK
   29214 **     (3) PENDING_LOCK
   29215 **     (4) EXCLUSIVE_LOCK
   29216 **
   29217 ** Sometimes when requesting one lock state, additional lock states
   29218 ** are inserted in between.  The locking might fail on one of the later
   29219 ** transitions leaving the lock state different from what it started but
   29220 ** still short of its goal.  The following chart shows the allowed
   29221 ** transitions and the inserted intermediate states:
   29222 **
   29223 **    UNLOCKED -> SHARED
   29224 **    SHARED -> RESERVED
   29225 **    SHARED -> (PENDING) -> EXCLUSIVE
   29226 **    RESERVED -> (PENDING) -> EXCLUSIVE
   29227 **    PENDING -> EXCLUSIVE
   29228 **
   29229 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
   29230 ** routine to lower a locking level.
   29231 */
   29232 static int proxyLock(sqlite3_file *id, int eFileLock) {
   29233   unixFile *pFile = (unixFile*)id;
   29234   int rc = proxyTakeConch(pFile);
   29235   if( rc==SQLITE_OK ){
   29236     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   29237     if( pCtx->conchHeld>0 ){
   29238       unixFile *proxy = pCtx->lockProxy;
   29239       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
   29240       pFile->eFileLock = proxy->eFileLock;
   29241     }else{
   29242       /* conchHeld < 0 is lockless */
   29243     }
   29244   }
   29245   return rc;
   29246 }
   29247 
   29248 
   29249 /*
   29250 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
   29251 ** must be either NO_LOCK or SHARED_LOCK.
   29252 **
   29253 ** If the locking level of the file descriptor is already at or below
   29254 ** the requested locking level, this routine is a no-op.
   29255 */
   29256 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
   29257   unixFile *pFile = (unixFile*)id;
   29258   int rc = proxyTakeConch(pFile);
   29259   if( rc==SQLITE_OK ){
   29260     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   29261     if( pCtx->conchHeld>0 ){
   29262       unixFile *proxy = pCtx->lockProxy;
   29263       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
   29264       pFile->eFileLock = proxy->eFileLock;
   29265     }else{
   29266       /* conchHeld < 0 is lockless */
   29267     }
   29268   }
   29269   return rc;
   29270 }
   29271 
   29272 /*
   29273 ** Close a file that uses proxy locks.
   29274 */
   29275 static int proxyClose(sqlite3_file *id) {
   29276   if( id ){
   29277     unixFile *pFile = (unixFile*)id;
   29278     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   29279     unixFile *lockProxy = pCtx->lockProxy;
   29280     unixFile *conchFile = pCtx->conchFile;
   29281     int rc = SQLITE_OK;
   29282 
   29283     if( lockProxy ){
   29284       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
   29285       if( rc ) return rc;
   29286       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
   29287       if( rc ) return rc;
   29288       sqlite3_free(lockProxy);
   29289       pCtx->lockProxy = 0;
   29290     }
   29291     if( conchFile ){
   29292       if( pCtx->conchHeld ){
   29293         rc = proxyReleaseConch(pFile);
   29294         if( rc ) return rc;
   29295       }
   29296       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
   29297       if( rc ) return rc;
   29298       sqlite3_free(conchFile);
   29299     }
   29300     sqlite3DbFree(0, pCtx->lockProxyPath);
   29301     sqlite3_free(pCtx->conchFilePath);
   29302     sqlite3DbFree(0, pCtx->dbPath);
   29303     /* restore the original locking context and pMethod then close it */
   29304     pFile->lockingContext = pCtx->oldLockingContext;
   29305     pFile->pMethod = pCtx->pOldMethod;
   29306     sqlite3_free(pCtx);
   29307     return pFile->pMethod->xClose(id);
   29308   }
   29309   return SQLITE_OK;
   29310 }
   29311 
   29312 
   29313 
   29314 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
   29315 /*
   29316 ** The proxy locking style is intended for use with AFP filesystems.
   29317 ** And since AFP is only supported on MacOSX, the proxy locking is also
   29318 ** restricted to MacOSX.
   29319 **
   29320 **
   29321 ******************* End of the proxy lock implementation **********************
   29322 ******************************************************************************/
   29323 
   29324 /*
   29325 ** Initialize the operating system interface.
   29326 **
   29327 ** This routine registers all VFS implementations for unix-like operating
   29328 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
   29329 ** should be the only routines in this file that are visible from other
   29330 ** files.
   29331 **
   29332 ** This routine is called once during SQLite initialization and by a
   29333 ** single thread.  The memory allocation and mutex subsystems have not
   29334 ** necessarily been initialized when this routine is called, and so they
   29335 ** should not be used.
   29336 */
   29337 SQLITE_API int sqlite3_os_init(void){
   29338   /*
   29339   ** The following macro defines an initializer for an sqlite3_vfs object.
   29340   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   29341   ** to the "finder" function.  (pAppData is a pointer to a pointer because
   29342   ** silly C90 rules prohibit a void* from being cast to a function pointer
   29343   ** and so we have to go through the intermediate pointer to avoid problems
   29344   ** when compiling with -pedantic-errors on GCC.)
   29345   **
   29346   ** The FINDER parameter to this macro is the name of the pointer to the
   29347   ** finder-function.  The finder-function returns a pointer to the
   29348   ** sqlite_io_methods object that implements the desired locking
   29349   ** behaviors.  See the division above that contains the IOMETHODS
   29350   ** macro for addition information on finder-functions.
   29351   **
   29352   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   29353   ** object.  But the "autolockIoFinder" available on MacOSX does a little
   29354   ** more than that; it looks at the filesystem type that hosts the
   29355   ** database file and tries to choose an locking method appropriate for
   29356   ** that filesystem time.
   29357   */
   29358   #define UNIXVFS(VFSNAME, FINDER) {                        \
   29359     2,                    /* iVersion */                    \
   29360     sizeof(unixFile),     /* szOsFile */                    \
   29361     MAX_PATHNAME,         /* mxPathname */                  \
   29362     0,                    /* pNext */                       \
   29363     VFSNAME,              /* zName */                       \
   29364     (void*)&FINDER,       /* pAppData */                    \
   29365     unixOpen,             /* xOpen */                       \
   29366     unixDelete,           /* xDelete */                     \
   29367     unixAccess,           /* xAccess */                     \
   29368     unixFullPathname,     /* xFullPathname */               \
   29369     unixDlOpen,           /* xDlOpen */                     \
   29370     unixDlError,          /* xDlError */                    \
   29371     unixDlSym,            /* xDlSym */                      \
   29372     unixDlClose,          /* xDlClose */                    \
   29373     unixRandomness,       /* xRandomness */                 \
   29374     unixSleep,            /* xSleep */                      \
   29375     unixCurrentTime,      /* xCurrentTime */                \
   29376     unixGetLastError,     /* xGetLastError */               \
   29377     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
   29378   }
   29379 
   29380   /*
   29381   ** All default VFSes for unix are contained in the following array.
   29382   **
   29383   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
   29384   ** by the SQLite core when the VFS is registered.  So the following
   29385   ** array cannot be const.
   29386   */
   29387   static sqlite3_vfs aVfs[] = {
   29388 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
   29389     UNIXVFS("unix",          autolockIoFinder ),
   29390 #else
   29391     UNIXVFS("unix",          posixIoFinder ),
   29392 #endif
   29393     UNIXVFS("unix-none",     nolockIoFinder ),
   29394     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
   29395 #if OS_VXWORKS
   29396     UNIXVFS("unix-namedsem", semIoFinder ),
   29397 #endif
   29398 #if SQLITE_ENABLE_LOCKING_STYLE
   29399     UNIXVFS("unix-posix",    posixIoFinder ),
   29400 #if !OS_VXWORKS
   29401     UNIXVFS("unix-flock",    flockIoFinder ),
   29402 #endif
   29403 #endif
   29404 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
   29405     UNIXVFS("unix-afp",      afpIoFinder ),
   29406     UNIXVFS("unix-nfs",      nfsIoFinder ),
   29407     UNIXVFS("unix-proxy",    proxyIoFinder ),
   29408 #endif
   29409   };
   29410   unsigned int i;          /* Loop counter */
   29411 
   29412   /* Register all VFSes defined in the aVfs[] array */
   29413   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
   29414     sqlite3_vfs_register(&aVfs[i], i==0);
   29415   }
   29416   return SQLITE_OK;
   29417 }
   29418 
   29419 /*
   29420 ** Shutdown the operating system interface.
   29421 **
   29422 ** Some operating systems might need to do some cleanup in this routine,
   29423 ** to release dynamically allocated objects.  But not on unix.
   29424 ** This routine is a no-op for unix.
   29425 */
   29426 SQLITE_API int sqlite3_os_end(void){
   29427   return SQLITE_OK;
   29428 }
   29429 
   29430 #endif /* SQLITE_OS_UNIX */
   29431 
   29432 /************** End of os_unix.c *********************************************/
   29433 /************** Begin file os_win.c ******************************************/
   29434 /*
   29435 ** 2004 May 22
   29436 **
   29437 ** The author disclaims copyright to this source code.  In place of
   29438 ** a legal notice, here is a blessing:
   29439 **
   29440 **    May you do good and not evil.
   29441 **    May you find forgiveness for yourself and forgive others.
   29442 **    May you share freely, never taking more than you give.
   29443 **
   29444 ******************************************************************************
   29445 **
   29446 ** This file contains code that is specific to windows.
   29447 */
   29448 #if SQLITE_OS_WIN               /* This file is used for windows only */
   29449 
   29450 
   29451 /*
   29452 ** A Note About Memory Allocation:
   29453 **
   29454 ** This driver uses malloc()/free() directly rather than going through
   29455 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
   29456 ** are designed for use on embedded systems where memory is scarce and
   29457 ** malloc failures happen frequently.  Win32 does not typically run on
   29458 ** embedded systems, and when it does the developers normally have bigger
   29459 ** problems to worry about than running out of memory.  So there is not
   29460 ** a compelling need to use the wrappers.
   29461 **
   29462 ** But there is a good reason to not use the wrappers.  If we use the
   29463 ** wrappers then we will get simulated malloc() failures within this
   29464 ** driver.  And that causes all kinds of problems for our tests.  We
   29465 ** could enhance SQLite to deal with simulated malloc failures within
   29466 ** the OS driver, but the code to deal with those failure would not
   29467 ** be exercised on Linux (which does not need to malloc() in the driver)
   29468 ** and so we would have difficulty writing coverage tests for that
   29469 ** code.  Better to leave the code out, we think.
   29470 **
   29471 ** The point of this discussion is as follows:  When creating a new
   29472 ** OS layer for an embedded system, if you use this file as an example,
   29473 ** avoid the use of malloc()/free().  Those routines work ok on windows
   29474 ** desktops but not so well in embedded systems.
   29475 */
   29476 
   29477 #include <winbase.h>
   29478 
   29479 #ifdef __CYGWIN__
   29480 # include <sys/cygwin.h>
   29481 #endif
   29482 
   29483 /*
   29484 ** Macros used to determine whether or not to use threads.
   29485 */
   29486 #if defined(THREADSAFE) && THREADSAFE
   29487 # define SQLITE_W32_THREADS 1
   29488 #endif
   29489 
   29490 /*
   29491 ** Include code that is common to all os_*.c files
   29492 */
   29493 /************** Include os_common.h in the middle of os_win.c ****************/
   29494 /************** Begin file os_common.h ***************************************/
   29495 /*
   29496 ** 2004 May 22
   29497 **
   29498 ** The author disclaims copyright to this source code.  In place of
   29499 ** a legal notice, here is a blessing:
   29500 **
   29501 **    May you do good and not evil.
   29502 **    May you find forgiveness for yourself and forgive others.
   29503 **    May you share freely, never taking more than you give.
   29504 **
   29505 ******************************************************************************
   29506 **
   29507 ** This file contains macros and a little bit of code that is common to
   29508 ** all of the platform-specific files (os_*.c) and is #included into those
   29509 ** files.
   29510 **
   29511 ** This file should be #included by the os_*.c files only.  It is not a
   29512 ** general purpose header file.
   29513 */
   29514 #ifndef _OS_COMMON_H_
   29515 #define _OS_COMMON_H_
   29516 
   29517 /*
   29518 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
   29519 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
   29520 ** switch.  The following code should catch this problem at compile-time.
   29521 */
   29522 #ifdef MEMORY_DEBUG
   29523 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
   29524 #endif
   29525 
   29526 #ifdef SQLITE_DEBUG
   29527 SQLITE_PRIVATE int sqlite3OSTrace = 0;
   29528 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
   29529 #else
   29530 #define OSTRACE(X)
   29531 #endif
   29532 
   29533 /*
   29534 ** Macros for performance tracing.  Normally turned off.  Only works
   29535 ** on i486 hardware.
   29536 */
   29537 #ifdef SQLITE_PERFORMANCE_TRACE
   29538 
   29539 /*
   29540 ** hwtime.h contains inline assembler code for implementing
   29541 ** high-performance timing routines.
   29542 */
   29543 /************** Include hwtime.h in the middle of os_common.h ****************/
   29544 /************** Begin file hwtime.h ******************************************/
   29545 /*
   29546 ** 2008 May 27
   29547 **
   29548 ** The author disclaims copyright to this source code.  In place of
   29549 ** a legal notice, here is a blessing:
   29550 **
   29551 **    May you do good and not evil.
   29552 **    May you find forgiveness for yourself and forgive others.
   29553 **    May you share freely, never taking more than you give.
   29554 **
   29555 ******************************************************************************
   29556 **
   29557 ** This file contains inline asm code for retrieving "high-performance"
   29558 ** counters for x86 class CPUs.
   29559 */
   29560 #ifndef _HWTIME_H_
   29561 #define _HWTIME_H_
   29562 
   29563 /*
   29564 ** The following routine only works on pentium-class (or newer) processors.
   29565 ** It uses the RDTSC opcode to read the cycle count value out of the
   29566 ** processor and returns that value.  This can be used for high-res
   29567 ** profiling.
   29568 */
   29569 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   29570       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   29571 
   29572   #if defined(__GNUC__)
   29573 
   29574   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   29575      unsigned int lo, hi;
   29576      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   29577      return (sqlite_uint64)hi << 32 | lo;
   29578   }
   29579 
   29580   #elif defined(_MSC_VER)
   29581 
   29582   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   29583      __asm {
   29584         rdtsc
   29585         ret       ; return value at EDX:EAX
   29586      }
   29587   }
   29588 
   29589   #endif
   29590 
   29591 #elif (defined(__GNUC__) && defined(__x86_64__))
   29592 
   29593   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   29594       unsigned long val;
   29595       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   29596       return val;
   29597   }
   29598 
   29599 #elif (defined(__GNUC__) && defined(__ppc__))
   29600 
   29601   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   29602       unsigned long long retval;
   29603       unsigned long junk;
   29604       __asm__ __volatile__ ("\n\
   29605           1:      mftbu   %1\n\
   29606                   mftb    %L0\n\
   29607                   mftbu   %0\n\
   29608                   cmpw    %0,%1\n\
   29609                   bne     1b"
   29610                   : "=r" (retval), "=r" (junk));
   29611       return retval;
   29612   }
   29613 
   29614 #else
   29615 
   29616   #error Need implementation of sqlite3Hwtime() for your platform.
   29617 
   29618   /*
   29619   ** To compile without implementing sqlite3Hwtime() for your platform,
   29620   ** you can remove the above #error and use the following
   29621   ** stub function.  You will lose timing support for many
   29622   ** of the debugging and testing utilities, but it should at
   29623   ** least compile and run.
   29624   */
   29625 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   29626 
   29627 #endif
   29628 
   29629 #endif /* !defined(_HWTIME_H_) */
   29630 
   29631 /************** End of hwtime.h **********************************************/
   29632 /************** Continuing where we left off in os_common.h ******************/
   29633 
   29634 static sqlite_uint64 g_start;
   29635 static sqlite_uint64 g_elapsed;
   29636 #define TIMER_START       g_start=sqlite3Hwtime()
   29637 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
   29638 #define TIMER_ELAPSED     g_elapsed
   29639 #else
   29640 #define TIMER_START
   29641 #define TIMER_END
   29642 #define TIMER_ELAPSED     ((sqlite_uint64)0)
   29643 #endif
   29644 
   29645 /*
   29646 ** If we compile with the SQLITE_TEST macro set, then the following block
   29647 ** of code will give us the ability to simulate a disk I/O error.  This
   29648 ** is used for testing the I/O recovery logic.
   29649 */
   29650 #ifdef SQLITE_TEST
   29651 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
   29652 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
   29653 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
   29654 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
   29655 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
   29656 SQLITE_API int sqlite3_diskfull_pending = 0;
   29657 SQLITE_API int sqlite3_diskfull = 0;
   29658 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
   29659 #define SimulateIOError(CODE)  \
   29660   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
   29661        || sqlite3_io_error_pending-- == 1 )  \
   29662               { local_ioerr(); CODE; }
   29663 static void local_ioerr(){
   29664   IOTRACE(("IOERR\n"));
   29665   sqlite3_io_error_hit++;
   29666   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
   29667 }
   29668 #define SimulateDiskfullError(CODE) \
   29669    if( sqlite3_diskfull_pending ){ \
   29670      if( sqlite3_diskfull_pending == 1 ){ \
   29671        local_ioerr(); \
   29672        sqlite3_diskfull = 1; \
   29673        sqlite3_io_error_hit = 1; \
   29674        CODE; \
   29675      }else{ \
   29676        sqlite3_diskfull_pending--; \
   29677      } \
   29678    }
   29679 #else
   29680 #define SimulateIOErrorBenign(X)
   29681 #define SimulateIOError(A)
   29682 #define SimulateDiskfullError(A)
   29683 #endif
   29684 
   29685 /*
   29686 ** When testing, keep a count of the number of open files.
   29687 */
   29688 #ifdef SQLITE_TEST
   29689 SQLITE_API int sqlite3_open_file_count = 0;
   29690 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
   29691 #else
   29692 #define OpenCounter(X)
   29693 #endif
   29694 
   29695 #endif /* !defined(_OS_COMMON_H_) */
   29696 
   29697 /************** End of os_common.h *******************************************/
   29698 /************** Continuing where we left off in os_win.c *********************/
   29699 
   29700 /*
   29701 ** Some microsoft compilers lack this definition.
   29702 */
   29703 #ifndef INVALID_FILE_ATTRIBUTES
   29704 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
   29705 #endif
   29706 
   29707 /*
   29708 ** Determine if we are dealing with WindowsCE - which has a much
   29709 ** reduced API.
   29710 */
   29711 #if SQLITE_OS_WINCE
   29712 # define AreFileApisANSI() 1
   29713 # define FormatMessageW(a,b,c,d,e,f,g) 0
   29714 #endif
   29715 
   29716 /* Forward references */
   29717 typedef struct winShm winShm;           /* A connection to shared-memory */
   29718 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
   29719 
   29720 /*
   29721 ** WinCE lacks native support for file locking so we have to fake it
   29722 ** with some code of our own.
   29723 */
   29724 #if SQLITE_OS_WINCE
   29725 typedef struct winceLock {
   29726   int nReaders;       /* Number of reader locks obtained */
   29727   BOOL bPending;      /* Indicates a pending lock has been obtained */
   29728   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
   29729   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
   29730 } winceLock;
   29731 #endif
   29732 
   29733 /*
   29734 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
   29735 ** portability layer.
   29736 */
   29737 typedef struct winFile winFile;
   29738 struct winFile {
   29739   const sqlite3_io_methods *pMethod; /*** Must be first ***/
   29740   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   29741   HANDLE h;               /* Handle for accessing the file */
   29742   unsigned char locktype; /* Type of lock currently held on this file */
   29743   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   29744   DWORD lastErrno;        /* The Windows errno from the last I/O error */
   29745   DWORD sectorSize;       /* Sector size of the device file is on */
   29746   winShm *pShm;           /* Instance of shared memory on this file */
   29747   const char *zPath;      /* Full pathname of this file */
   29748   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   29749 #if SQLITE_OS_WINCE
   29750   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
   29751   HANDLE hMutex;          /* Mutex used to control access to shared lock */
   29752   HANDLE hShared;         /* Shared memory segment used for locking */
   29753   winceLock local;        /* Locks obtained by this instance of winFile */
   29754   winceLock *shared;      /* Global shared lock memory for the file  */
   29755 #endif
   29756 };
   29757 
   29758 /*
   29759 ** Forward prototypes.
   29760 */
   29761 static int getSectorSize(
   29762     sqlite3_vfs *pVfs,
   29763     const char *zRelative     /* UTF-8 file name */
   29764 );
   29765 
   29766 /*
   29767 ** The following variable is (normally) set once and never changes
   29768 ** thereafter.  It records whether the operating system is Win95
   29769 ** or WinNT.
   29770 **
   29771 ** 0:   Operating system unknown.
   29772 ** 1:   Operating system is Win95.
   29773 ** 2:   Operating system is WinNT.
   29774 **
   29775 ** In order to facilitate testing on a WinNT system, the test fixture
   29776 ** can manually set this value to 1 to emulate Win98 behavior.
   29777 */
   29778 #ifdef SQLITE_TEST
   29779 SQLITE_API int sqlite3_os_type = 0;
   29780 #else
   29781 static int sqlite3_os_type = 0;
   29782 #endif
   29783 
   29784 /*
   29785 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   29786 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   29787 **
   29788 ** Here is an interesting observation:  Win95, Win98, and WinME lack
   29789 ** the LockFileEx() API.  But we can still statically link against that
   29790 ** API as long as we don't call it when running Win95/98/ME.  A call to
   29791 ** this routine is used to determine if the host is Win95/98/ME or
   29792 ** WinNT/2K/XP so that we will know whether or not we can safely call
   29793 ** the LockFileEx() API.
   29794 */
   29795 #if SQLITE_OS_WINCE
   29796 # define isNT()  (1)
   29797 #else
   29798   static int isNT(void){
   29799     if( sqlite3_os_type==0 ){
   29800       OSVERSIONINFO sInfo;
   29801       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   29802       GetVersionEx(&sInfo);
   29803       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   29804     }
   29805     return sqlite3_os_type==2;
   29806   }
   29807 #endif /* SQLITE_OS_WINCE */
   29808 
   29809 /*
   29810 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
   29811 **
   29812 ** Space to hold the returned string is obtained from malloc.
   29813 */
   29814 static WCHAR *utf8ToUnicode(const char *zFilename){
   29815   int nChar;
   29816   WCHAR *zWideFilename;
   29817 
   29818   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   29819   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
   29820   if( zWideFilename==0 ){
   29821     return 0;
   29822   }
   29823   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
   29824   if( nChar==0 ){
   29825     free(zWideFilename);
   29826     zWideFilename = 0;
   29827   }
   29828   return zWideFilename;
   29829 }
   29830 
   29831 /*
   29832 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
   29833 ** obtained from malloc().
   29834 */
   29835 static char *unicodeToUtf8(const WCHAR *zWideFilename){
   29836   int nByte;
   29837   char *zFilename;
   29838 
   29839   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   29840   zFilename = malloc( nByte );
   29841   if( zFilename==0 ){
   29842     return 0;
   29843   }
   29844   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   29845                               0, 0);
   29846   if( nByte == 0 ){
   29847     free(zFilename);
   29848     zFilename = 0;
   29849   }
   29850   return zFilename;
   29851 }
   29852 
   29853 /*
   29854 ** Convert an ansi string to microsoft unicode, based on the
   29855 ** current codepage settings for file apis.
   29856 **
   29857 ** Space to hold the returned string is obtained
   29858 ** from malloc.
   29859 */
   29860 static WCHAR *mbcsToUnicode(const char *zFilename){
   29861   int nByte;
   29862   WCHAR *zMbcsFilename;
   29863   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
   29864 
   29865   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
   29866   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
   29867   if( zMbcsFilename==0 ){
   29868     return 0;
   29869   }
   29870   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
   29871   if( nByte==0 ){
   29872     free(zMbcsFilename);
   29873     zMbcsFilename = 0;
   29874   }
   29875   return zMbcsFilename;
   29876 }
   29877 
   29878 /*
   29879 ** Convert microsoft unicode to multibyte character string, based on the
   29880 ** user's Ansi codepage.
   29881 **
   29882 ** Space to hold the returned string is obtained from
   29883 ** malloc().
   29884 */
   29885 static char *unicodeToMbcs(const WCHAR *zWideFilename){
   29886   int nByte;
   29887   char *zFilename;
   29888   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
   29889 
   29890   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   29891   zFilename = malloc( nByte );
   29892   if( zFilename==0 ){
   29893     return 0;
   29894   }
   29895   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
   29896                               0, 0);
   29897   if( nByte == 0 ){
   29898     free(zFilename);
   29899     zFilename = 0;
   29900   }
   29901   return zFilename;
   29902 }
   29903 
   29904 /*
   29905 ** Convert multibyte character string to UTF-8.  Space to hold the
   29906 ** returned string is obtained from malloc().
   29907 */
   29908 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   29909   char *zFilenameUtf8;
   29910   WCHAR *zTmpWide;
   29911 
   29912   zTmpWide = mbcsToUnicode(zFilename);
   29913   if( zTmpWide==0 ){
   29914     return 0;
   29915   }
   29916   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
   29917   free(zTmpWide);
   29918   return zFilenameUtf8;
   29919 }
   29920 
   29921 /*
   29922 ** Convert UTF-8 to multibyte character string.  Space to hold the
   29923 ** returned string is obtained from malloc().
   29924 */
   29925 static char *utf8ToMbcs(const char *zFilename){
   29926   char *zFilenameMbcs;
   29927   WCHAR *zTmpWide;
   29928 
   29929   zTmpWide = utf8ToUnicode(zFilename);
   29930   if( zTmpWide==0 ){
   29931     return 0;
   29932   }
   29933   zFilenameMbcs = unicodeToMbcs(zTmpWide);
   29934   free(zTmpWide);
   29935   return zFilenameMbcs;
   29936 }
   29937 
   29938 #if SQLITE_OS_WINCE
   29939 /*************************************************************************
   29940 ** This section contains code for WinCE only.
   29941 */
   29942 /*
   29943 ** WindowsCE does not have a localtime() function.  So create a
   29944 ** substitute.
   29945 */
   29946 struct tm *__cdecl localtime(const time_t *t)
   29947 {
   29948   static struct tm y;
   29949   FILETIME uTm, lTm;
   29950   SYSTEMTIME pTm;
   29951   sqlite3_int64 t64;
   29952   t64 = *t;
   29953   t64 = (t64 + 11644473600)*10000000;
   29954   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   29955   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   29956   FileTimeToLocalFileTime(&uTm,&lTm);
   29957   FileTimeToSystemTime(&lTm,&pTm);
   29958   y.tm_year = pTm.wYear - 1900;
   29959   y.tm_mon = pTm.wMonth - 1;
   29960   y.tm_wday = pTm.wDayOfWeek;
   29961   y.tm_mday = pTm.wDay;
   29962   y.tm_hour = pTm.wHour;
   29963   y.tm_min = pTm.wMinute;
   29964   y.tm_sec = pTm.wSecond;
   29965   return &y;
   29966 }
   29967 
   29968 /* This will never be called, but defined to make the code compile */
   29969 #define GetTempPathA(a,b)
   29970 
   29971 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
   29972 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
   29973 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
   29974 
   29975 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   29976 
   29977 /*
   29978 ** Acquire a lock on the handle h
   29979 */
   29980 static void winceMutexAcquire(HANDLE h){
   29981    DWORD dwErr;
   29982    do {
   29983      dwErr = WaitForSingleObject(h, INFINITE);
   29984    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
   29985 }
   29986 /*
   29987 ** Release a lock acquired by winceMutexAcquire()
   29988 */
   29989 #define winceMutexRelease(h) ReleaseMutex(h)
   29990 
   29991 /*
   29992 ** Create the mutex and shared memory used for locking in the file
   29993 ** descriptor pFile
   29994 */
   29995 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
   29996   WCHAR *zTok;
   29997   WCHAR *zName = utf8ToUnicode(zFilename);
   29998   BOOL bInit = TRUE;
   29999 
   30000   /* Initialize the local lockdata */
   30001   ZeroMemory(&pFile->local, sizeof(pFile->local));
   30002 
   30003   /* Replace the backslashes from the filename and lowercase it
   30004   ** to derive a mutex name. */
   30005   zTok = CharLowerW(zName);
   30006   for (;*zTok;zTok++){
   30007     if (*zTok == '\\') *zTok = '_';
   30008   }
   30009 
   30010   /* Create/open the named mutex */
   30011   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
   30012   if (!pFile->hMutex){
   30013     pFile->lastErrno = GetLastError();
   30014     free(zName);
   30015     return FALSE;
   30016   }
   30017 
   30018   /* Acquire the mutex before continuing */
   30019   winceMutexAcquire(pFile->hMutex);
   30020 
   30021   /* Since the names of named mutexes, semaphores, file mappings etc are
   30022   ** case-sensitive, take advantage of that by uppercasing the mutex name
   30023   ** and using that as the shared filemapping name.
   30024   */
   30025   CharUpperW(zName);
   30026   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   30027                                        PAGE_READWRITE, 0, sizeof(winceLock),
   30028                                        zName);
   30029 
   30030   /* Set a flag that indicates we're the first to create the memory so it
   30031   ** must be zero-initialized */
   30032   if (GetLastError() == ERROR_ALREADY_EXISTS){
   30033     bInit = FALSE;
   30034   }
   30035 
   30036   free(zName);
   30037 
   30038   /* If we succeeded in making the shared memory handle, map it. */
   30039   if (pFile->hShared){
   30040     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
   30041              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   30042     /* If mapping failed, close the shared memory handle and erase it */
   30043     if (!pFile->shared){
   30044       pFile->lastErrno = GetLastError();
   30045       CloseHandle(pFile->hShared);
   30046       pFile->hShared = NULL;
   30047     }
   30048   }
   30049 
   30050   /* If shared memory could not be created, then close the mutex and fail */
   30051   if (pFile->hShared == NULL){
   30052     winceMutexRelease(pFile->hMutex);
   30053     CloseHandle(pFile->hMutex);
   30054     pFile->hMutex = NULL;
   30055     return FALSE;
   30056   }
   30057 
   30058   /* Initialize the shared memory if we're supposed to */
   30059   if (bInit) {
   30060     ZeroMemory(pFile->shared, sizeof(winceLock));
   30061   }
   30062 
   30063   winceMutexRelease(pFile->hMutex);
   30064   return TRUE;
   30065 }
   30066 
   30067 /*
   30068 ** Destroy the part of winFile that deals with wince locks
   30069 */
   30070 static void winceDestroyLock(winFile *pFile){
   30071   if (pFile->hMutex){
   30072     /* Acquire the mutex */
   30073     winceMutexAcquire(pFile->hMutex);
   30074 
   30075     /* The following blocks should probably assert in debug mode, but they
   30076        are to cleanup in case any locks remained open */
   30077     if (pFile->local.nReaders){
   30078       pFile->shared->nReaders --;
   30079     }
   30080     if (pFile->local.bReserved){
   30081       pFile->shared->bReserved = FALSE;
   30082     }
   30083     if (pFile->local.bPending){
   30084       pFile->shared->bPending = FALSE;
   30085     }
   30086     if (pFile->local.bExclusive){
   30087       pFile->shared->bExclusive = FALSE;
   30088     }
   30089 
   30090     /* De-reference and close our copy of the shared memory handle */
   30091     UnmapViewOfFile(pFile->shared);
   30092     CloseHandle(pFile->hShared);
   30093 
   30094     /* Done with the mutex */
   30095     winceMutexRelease(pFile->hMutex);
   30096     CloseHandle(pFile->hMutex);
   30097     pFile->hMutex = NULL;
   30098   }
   30099 }
   30100 
   30101 /*
   30102 ** An implementation of the LockFile() API of windows for wince
   30103 */
   30104 static BOOL winceLockFile(
   30105   HANDLE *phFile,
   30106   DWORD dwFileOffsetLow,
   30107   DWORD dwFileOffsetHigh,
   30108   DWORD nNumberOfBytesToLockLow,
   30109   DWORD nNumberOfBytesToLockHigh
   30110 ){
   30111   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   30112   BOOL bReturn = FALSE;
   30113 
   30114   UNUSED_PARAMETER(dwFileOffsetHigh);
   30115   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   30116 
   30117   if (!pFile->hMutex) return TRUE;
   30118   winceMutexAcquire(pFile->hMutex);
   30119 
   30120   /* Wanting an exclusive lock? */
   30121   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
   30122        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   30123     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
   30124        pFile->shared->bExclusive = TRUE;
   30125        pFile->local.bExclusive = TRUE;
   30126        bReturn = TRUE;
   30127     }
   30128   }
   30129 
   30130   /* Want a read-only lock? */
   30131   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
   30132            nNumberOfBytesToLockLow == 1){
   30133     if (pFile->shared->bExclusive == 0){
   30134       pFile->local.nReaders ++;
   30135       if (pFile->local.nReaders == 1){
   30136         pFile->shared->nReaders ++;
   30137       }
   30138       bReturn = TRUE;
   30139     }
   30140   }
   30141 
   30142   /* Want a pending lock? */
   30143   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
   30144     /* If no pending lock has been acquired, then acquire it */
   30145     if (pFile->shared->bPending == 0) {
   30146       pFile->shared->bPending = TRUE;
   30147       pFile->local.bPending = TRUE;
   30148       bReturn = TRUE;
   30149     }
   30150   }
   30151 
   30152   /* Want a reserved lock? */
   30153   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
   30154     if (pFile->shared->bReserved == 0) {
   30155       pFile->shared->bReserved = TRUE;
   30156       pFile->local.bReserved = TRUE;
   30157       bReturn = TRUE;
   30158     }
   30159   }
   30160 
   30161   winceMutexRelease(pFile->hMutex);
   30162   return bReturn;
   30163 }
   30164 
   30165 /*
   30166 ** An implementation of the UnlockFile API of windows for wince
   30167 */
   30168 static BOOL winceUnlockFile(
   30169   HANDLE *phFile,
   30170   DWORD dwFileOffsetLow,
   30171   DWORD dwFileOffsetHigh,
   30172   DWORD nNumberOfBytesToUnlockLow,
   30173   DWORD nNumberOfBytesToUnlockHigh
   30174 ){
   30175   winFile *pFile = HANDLE_TO_WINFILE(phFile);
   30176   BOOL bReturn = FALSE;
   30177 
   30178   UNUSED_PARAMETER(dwFileOffsetHigh);
   30179   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
   30180 
   30181   if (!pFile->hMutex) return TRUE;
   30182   winceMutexAcquire(pFile->hMutex);
   30183 
   30184   /* Releasing a reader lock or an exclusive lock */
   30185   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
   30186     /* Did we have an exclusive lock? */
   30187     if (pFile->local.bExclusive){
   30188       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
   30189       pFile->local.bExclusive = FALSE;
   30190       pFile->shared->bExclusive = FALSE;
   30191       bReturn = TRUE;
   30192     }
   30193 
   30194     /* Did we just have a reader lock? */
   30195     else if (pFile->local.nReaders){
   30196       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
   30197       pFile->local.nReaders --;
   30198       if (pFile->local.nReaders == 0)
   30199       {
   30200         pFile->shared->nReaders --;
   30201       }
   30202       bReturn = TRUE;
   30203     }
   30204   }
   30205 
   30206   /* Releasing a pending lock */
   30207   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
   30208     if (pFile->local.bPending){
   30209       pFile->local.bPending = FALSE;
   30210       pFile->shared->bPending = FALSE;
   30211       bReturn = TRUE;
   30212     }
   30213   }
   30214   /* Releasing a reserved lock */
   30215   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
   30216     if (pFile->local.bReserved) {
   30217       pFile->local.bReserved = FALSE;
   30218       pFile->shared->bReserved = FALSE;
   30219       bReturn = TRUE;
   30220     }
   30221   }
   30222 
   30223   winceMutexRelease(pFile->hMutex);
   30224   return bReturn;
   30225 }
   30226 
   30227 /*
   30228 ** An implementation of the LockFileEx() API of windows for wince
   30229 */
   30230 static BOOL winceLockFileEx(
   30231   HANDLE *phFile,
   30232   DWORD dwFlags,
   30233   DWORD dwReserved,
   30234   DWORD nNumberOfBytesToLockLow,
   30235   DWORD nNumberOfBytesToLockHigh,
   30236   LPOVERLAPPED lpOverlapped
   30237 ){
   30238   UNUSED_PARAMETER(dwReserved);
   30239   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
   30240 
   30241   /* If the caller wants a shared read lock, forward this call
   30242   ** to winceLockFile */
   30243   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
   30244       dwFlags == 1 &&
   30245       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
   30246     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
   30247   }
   30248   return FALSE;
   30249 }
   30250 /*
   30251 ** End of the special code for wince
   30252 *****************************************************************************/
   30253 #endif /* SQLITE_OS_WINCE */
   30254 
   30255 /*****************************************************************************
   30256 ** The next group of routines implement the I/O methods specified
   30257 ** by the sqlite3_io_methods object.
   30258 ******************************************************************************/
   30259 
   30260 /*
   30261 ** Some microsoft compilers lack this definition.
   30262 */
   30263 #ifndef INVALID_SET_FILE_POINTER
   30264 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
   30265 #endif
   30266 
   30267 /*
   30268 ** Move the current position of the file handle passed as the first
   30269 ** argument to offset iOffset within the file. If successful, return 0.
   30270 ** Otherwise, set pFile->lastErrno and return non-zero.
   30271 */
   30272 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
   30273   LONG upperBits;                 /* Most sig. 32 bits of new offset */
   30274   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
   30275   DWORD dwRet;                    /* Value returned by SetFilePointer() */
   30276 
   30277   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
   30278   lowerBits = (LONG)(iOffset & 0xffffffff);
   30279 
   30280   /* API oddity: If successful, SetFilePointer() returns a dword
   30281   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
   30282   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
   30283   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
   30284   ** whether an error has actually occured, it is also necessary to call
   30285   ** GetLastError().
   30286   */
   30287   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
   30288   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
   30289     pFile->lastErrno = GetLastError();
   30290     return 1;
   30291   }
   30292 
   30293   return 0;
   30294 }
   30295 
   30296 /*
   30297 ** Close a file.
   30298 **
   30299 ** It is reported that an attempt to close a handle might sometimes
   30300 ** fail.  This is a very unreasonable result, but windows is notorious
   30301 ** for being unreasonable so I do not doubt that it might happen.  If
   30302 ** the close fails, we pause for 100 milliseconds and try again.  As
   30303 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
   30304 ** giving up and returning an error.
   30305 */
   30306 #define MX_CLOSE_ATTEMPT 3
   30307 static int winClose(sqlite3_file *id){
   30308   int rc, cnt = 0;
   30309   winFile *pFile = (winFile*)id;
   30310 
   30311   assert( id!=0 );
   30312   assert( pFile->pShm==0 );
   30313   OSTRACE(("CLOSE %d\n", pFile->h));
   30314   do{
   30315     rc = CloseHandle(pFile->h);
   30316     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
   30317   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
   30318 #if SQLITE_OS_WINCE
   30319 #define WINCE_DELETION_ATTEMPTS 3
   30320   winceDestroyLock(pFile);
   30321   if( pFile->zDeleteOnClose ){
   30322     int cnt = 0;
   30323     while(
   30324            DeleteFileW(pFile->zDeleteOnClose)==0
   30325         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
   30326         && cnt++ < WINCE_DELETION_ATTEMPTS
   30327     ){
   30328        Sleep(100);  /* Wait a little before trying again */
   30329     }
   30330     free(pFile->zDeleteOnClose);
   30331   }
   30332 #endif
   30333   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
   30334   OpenCounter(-1);
   30335   return rc ? SQLITE_OK : SQLITE_IOERR;
   30336 }
   30337 
   30338 /*
   30339 ** Read data from a file into a buffer.  Return SQLITE_OK if all
   30340 ** bytes were read successfully and SQLITE_IOERR if anything goes
   30341 ** wrong.
   30342 */
   30343 static int winRead(
   30344   sqlite3_file *id,          /* File to read from */
   30345   void *pBuf,                /* Write content into this buffer */
   30346   int amt,                   /* Number of bytes to read */
   30347   sqlite3_int64 offset       /* Begin reading at this offset */
   30348 ){
   30349   winFile *pFile = (winFile*)id;  /* file handle */
   30350   DWORD nRead;                    /* Number of bytes actually read from file */
   30351 
   30352   assert( id!=0 );
   30353   SimulateIOError(return SQLITE_IOERR_READ);
   30354   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
   30355 
   30356   if( seekWinFile(pFile, offset) ){
   30357     return SQLITE_FULL;
   30358   }
   30359   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
   30360     pFile->lastErrno = GetLastError();
   30361     return SQLITE_IOERR_READ;
   30362   }
   30363   if( nRead<(DWORD)amt ){
   30364     /* Unread parts of the buffer must be zero-filled */
   30365     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
   30366     return SQLITE_IOERR_SHORT_READ;
   30367   }
   30368 
   30369   return SQLITE_OK;
   30370 }
   30371 
   30372 /*
   30373 ** Write data from a buffer into a file.  Return SQLITE_OK on success
   30374 ** or some other error code on failure.
   30375 */
   30376 static int winWrite(
   30377   sqlite3_file *id,               /* File to write into */
   30378   const void *pBuf,               /* The bytes to be written */
   30379   int amt,                        /* Number of bytes to write */
   30380   sqlite3_int64 offset            /* Offset into the file to begin writing at */
   30381 ){
   30382   int rc;                         /* True if error has occured, else false */
   30383   winFile *pFile = (winFile*)id;  /* File handle */
   30384 
   30385   assert( amt>0 );
   30386   assert( pFile );
   30387   SimulateIOError(return SQLITE_IOERR_WRITE);
   30388   SimulateDiskfullError(return SQLITE_FULL);
   30389 
   30390   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
   30391 
   30392   rc = seekWinFile(pFile, offset);
   30393   if( rc==0 ){
   30394     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
   30395     int nRem = amt;               /* Number of bytes yet to be written */
   30396     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
   30397 
   30398     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
   30399       aRem += nWrite;
   30400       nRem -= nWrite;
   30401     }
   30402     if( nRem>0 ){
   30403       pFile->lastErrno = GetLastError();
   30404       rc = 1;
   30405     }
   30406   }
   30407 
   30408   if( rc ){
   30409     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
   30410       return SQLITE_FULL;
   30411     }
   30412     return SQLITE_IOERR_WRITE;
   30413   }
   30414   return SQLITE_OK;
   30415 }
   30416 
   30417 /*
   30418 ** Truncate an open file to a specified size
   30419 */
   30420 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
   30421   winFile *pFile = (winFile*)id;  /* File handle object */
   30422   int rc = SQLITE_OK;             /* Return code for this function */
   30423 
   30424   assert( pFile );
   30425 
   30426   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
   30427   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
   30428 
   30429   /* If the user has configured a chunk-size for this file, truncate the
   30430   ** file so that it consists of an integer number of chunks (i.e. the
   30431   ** actual file size after the operation may be larger than the requested
   30432   ** size).
   30433   */
   30434   if( pFile->szChunk ){
   30435     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
   30436   }
   30437 
   30438   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
   30439   if( seekWinFile(pFile, nByte) ){
   30440     rc = SQLITE_IOERR_TRUNCATE;
   30441   }else if( 0==SetEndOfFile(pFile->h) ){
   30442     pFile->lastErrno = GetLastError();
   30443     rc = SQLITE_IOERR_TRUNCATE;
   30444   }
   30445 
   30446   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
   30447   return rc;
   30448 }
   30449 
   30450 #ifdef SQLITE_TEST
   30451 /*
   30452 ** Count the number of fullsyncs and normal syncs.  This is used to test
   30453 ** that syncs and fullsyncs are occuring at the right times.
   30454 */
   30455 SQLITE_API int sqlite3_sync_count = 0;
   30456 SQLITE_API int sqlite3_fullsync_count = 0;
   30457 #endif
   30458 
   30459 /*
   30460 ** Make sure all writes to a particular file are committed to disk.
   30461 */
   30462 static int winSync(sqlite3_file *id, int flags){
   30463 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
   30464   winFile *pFile = (winFile*)id;
   30465 #else
   30466   UNUSED_PARAMETER(id);
   30467 #endif
   30468 
   30469   assert( pFile );
   30470   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
   30471   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
   30472       || (flags&0x0F)==SQLITE_SYNC_FULL
   30473   );
   30474 
   30475   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
   30476 
   30477 #ifndef SQLITE_TEST
   30478   UNUSED_PARAMETER(flags);
   30479 #else
   30480   if( flags & SQLITE_SYNC_FULL ){
   30481     sqlite3_fullsync_count++;
   30482   }
   30483   sqlite3_sync_count++;
   30484 #endif
   30485 
   30486   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
   30487   ** line is to test that doing so does not cause any problems.
   30488   */
   30489   SimulateDiskfullError( return SQLITE_FULL );
   30490   SimulateIOError( return SQLITE_IOERR; );
   30491 
   30492   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
   30493   ** no-op
   30494   */
   30495 #ifdef SQLITE_NO_SYNC
   30496   return SQLITE_OK;
   30497 #else
   30498   if( FlushFileBuffers(pFile->h) ){
   30499     return SQLITE_OK;
   30500   }else{
   30501     pFile->lastErrno = GetLastError();
   30502     return SQLITE_IOERR;
   30503   }
   30504 #endif
   30505 }
   30506 
   30507 /*
   30508 ** Determine the current size of a file in bytes
   30509 */
   30510 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
   30511   DWORD upperBits;
   30512   DWORD lowerBits;
   30513   winFile *pFile = (winFile*)id;
   30514   DWORD error;
   30515 
   30516   assert( id!=0 );
   30517   SimulateIOError(return SQLITE_IOERR_FSTAT);
   30518   lowerBits = GetFileSize(pFile->h, &upperBits);
   30519   if(   (lowerBits == INVALID_FILE_SIZE)
   30520      && ((error = GetLastError()) != NO_ERROR) )
   30521   {
   30522     pFile->lastErrno = error;
   30523     return SQLITE_IOERR_FSTAT;
   30524   }
   30525   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
   30526   return SQLITE_OK;
   30527 }
   30528 
   30529 /*
   30530 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
   30531 */
   30532 #ifndef LOCKFILE_FAIL_IMMEDIATELY
   30533 # define LOCKFILE_FAIL_IMMEDIATELY 1
   30534 #endif
   30535 
   30536 /*
   30537 ** Acquire a reader lock.
   30538 ** Different API routines are called depending on whether or not this
   30539 ** is Win95 or WinNT.
   30540 */
   30541 static int getReadLock(winFile *pFile){
   30542   int res;
   30543   if( isNT() ){
   30544     OVERLAPPED ovlp;
   30545     ovlp.Offset = SHARED_FIRST;
   30546     ovlp.OffsetHigh = 0;
   30547     ovlp.hEvent = 0;
   30548     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
   30549                      0, SHARED_SIZE, 0, &ovlp);
   30550 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   30551 */
   30552 #if SQLITE_OS_WINCE==0
   30553   }else{
   30554     int lk;
   30555     sqlite3_randomness(sizeof(lk), &lk);
   30556     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
   30557     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
   30558 #endif
   30559   }
   30560   if( res == 0 ){
   30561     pFile->lastErrno = GetLastError();
   30562   }
   30563   return res;
   30564 }
   30565 
   30566 /*
   30567 ** Undo a readlock
   30568 */
   30569 static int unlockReadLock(winFile *pFile){
   30570   int res;
   30571   if( isNT() ){
   30572     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   30573 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   30574 */
   30575 #if SQLITE_OS_WINCE==0
   30576   }else{
   30577     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
   30578 #endif
   30579   }
   30580   if( res == 0 ){
   30581     pFile->lastErrno = GetLastError();
   30582   }
   30583   return res;
   30584 }
   30585 
   30586 /*
   30587 ** Lock the file with the lock specified by parameter locktype - one
   30588 ** of the following:
   30589 **
   30590 **     (1) SHARED_LOCK
   30591 **     (2) RESERVED_LOCK
   30592 **     (3) PENDING_LOCK
   30593 **     (4) EXCLUSIVE_LOCK
   30594 **
   30595 ** Sometimes when requesting one lock state, additional lock states
   30596 ** are inserted in between.  The locking might fail on one of the later
   30597 ** transitions leaving the lock state different from what it started but
   30598 ** still short of its goal.  The following chart shows the allowed
   30599 ** transitions and the inserted intermediate states:
   30600 **
   30601 **    UNLOCKED -> SHARED
   30602 **    SHARED -> RESERVED
   30603 **    SHARED -> (PENDING) -> EXCLUSIVE
   30604 **    RESERVED -> (PENDING) -> EXCLUSIVE
   30605 **    PENDING -> EXCLUSIVE
   30606 **
   30607 ** This routine will only increase a lock.  The winUnlock() routine
   30608 ** erases all locks at once and returns us immediately to locking level 0.
   30609 ** It is not possible to lower the locking level one step at a time.  You
   30610 ** must go straight to locking level 0.
   30611 */
   30612 static int winLock(sqlite3_file *id, int locktype){
   30613   int rc = SQLITE_OK;    /* Return code from subroutines */
   30614   int res = 1;           /* Result of a windows lock call */
   30615   int newLocktype;       /* Set pFile->locktype to this value before exiting */
   30616   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
   30617   winFile *pFile = (winFile*)id;
   30618   DWORD error = NO_ERROR;
   30619 
   30620   assert( id!=0 );
   30621   OSTRACE(("LOCK %d %d was %d(%d)\n",
   30622            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
   30623 
   30624   /* If there is already a lock of this type or more restrictive on the
   30625   ** OsFile, do nothing. Don't use the end_lock: exit path, as
   30626   ** sqlite3OsEnterMutex() hasn't been called yet.
   30627   */
   30628   if( pFile->locktype>=locktype ){
   30629     return SQLITE_OK;
   30630   }
   30631 
   30632   /* Make sure the locking sequence is correct
   30633   */
   30634   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
   30635   assert( locktype!=PENDING_LOCK );
   30636   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
   30637 
   30638   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
   30639   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
   30640   ** the PENDING_LOCK byte is temporary.
   30641   */
   30642   newLocktype = pFile->locktype;
   30643   if(   (pFile->locktype==NO_LOCK)
   30644      || (   (locktype==EXCLUSIVE_LOCK)
   30645          && (pFile->locktype==RESERVED_LOCK))
   30646   ){
   30647     int cnt = 3;
   30648     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
   30649       /* Try 3 times to get the pending lock.  The pending lock might be
   30650       ** held by another reader process who will release it momentarily.
   30651       */
   30652       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
   30653       Sleep(1);
   30654     }
   30655     gotPendingLock = res;
   30656     if( !res ){
   30657       error = GetLastError();
   30658     }
   30659   }
   30660 
   30661   /* Acquire a shared lock
   30662   */
   30663   if( locktype==SHARED_LOCK && res ){
   30664     assert( pFile->locktype==NO_LOCK );
   30665     res = getReadLock(pFile);
   30666     if( res ){
   30667       newLocktype = SHARED_LOCK;
   30668     }else{
   30669       error = GetLastError();
   30670     }
   30671   }
   30672 
   30673   /* Acquire a RESERVED lock
   30674   */
   30675   if( locktype==RESERVED_LOCK && res ){
   30676     assert( pFile->locktype==SHARED_LOCK );
   30677     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   30678     if( res ){
   30679       newLocktype = RESERVED_LOCK;
   30680     }else{
   30681       error = GetLastError();
   30682     }
   30683   }
   30684 
   30685   /* Acquire a PENDING lock
   30686   */
   30687   if( locktype==EXCLUSIVE_LOCK && res ){
   30688     newLocktype = PENDING_LOCK;
   30689     gotPendingLock = 0;
   30690   }
   30691 
   30692   /* Acquire an EXCLUSIVE lock
   30693   */
   30694   if( locktype==EXCLUSIVE_LOCK && res ){
   30695     assert( pFile->locktype>=SHARED_LOCK );
   30696     res = unlockReadLock(pFile);
   30697     OSTRACE(("unreadlock = %d\n", res));
   30698     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   30699     if( res ){
   30700       newLocktype = EXCLUSIVE_LOCK;
   30701     }else{
   30702       error = GetLastError();
   30703       OSTRACE(("error-code = %d\n", error));
   30704       getReadLock(pFile);
   30705     }
   30706   }
   30707 
   30708   /* If we are holding a PENDING lock that ought to be released, then
   30709   ** release it now.
   30710   */
   30711   if( gotPendingLock && locktype==SHARED_LOCK ){
   30712     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   30713   }
   30714 
   30715   /* Update the state of the lock has held in the file descriptor then
   30716   ** return the appropriate result code.
   30717   */
   30718   if( res ){
   30719     rc = SQLITE_OK;
   30720   }else{
   30721     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
   30722            locktype, newLocktype));
   30723     pFile->lastErrno = error;
   30724     rc = SQLITE_BUSY;
   30725   }
   30726   pFile->locktype = (u8)newLocktype;
   30727   return rc;
   30728 }
   30729 
   30730 /*
   30731 ** This routine checks if there is a RESERVED lock held on the specified
   30732 ** file by this or any other process. If such a lock is held, return
   30733 ** non-zero, otherwise zero.
   30734 */
   30735 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
   30736   int rc;
   30737   winFile *pFile = (winFile*)id;
   30738 
   30739   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
   30740 
   30741   assert( id!=0 );
   30742   if( pFile->locktype>=RESERVED_LOCK ){
   30743     rc = 1;
   30744     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
   30745   }else{
   30746     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   30747     if( rc ){
   30748       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   30749     }
   30750     rc = !rc;
   30751     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
   30752   }
   30753   *pResOut = rc;
   30754   return SQLITE_OK;
   30755 }
   30756 
   30757 /*
   30758 ** Lower the locking level on file descriptor id to locktype.  locktype
   30759 ** must be either NO_LOCK or SHARED_LOCK.
   30760 **
   30761 ** If the locking level of the file descriptor is already at or below
   30762 ** the requested locking level, this routine is a no-op.
   30763 **
   30764 ** It is not possible for this routine to fail if the second argument
   30765 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
   30766 ** might return SQLITE_IOERR;
   30767 */
   30768 static int winUnlock(sqlite3_file *id, int locktype){
   30769   int type;
   30770   winFile *pFile = (winFile*)id;
   30771   int rc = SQLITE_OK;
   30772   assert( pFile!=0 );
   30773   assert( locktype<=SHARED_LOCK );
   30774   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
   30775           pFile->locktype, pFile->sharedLockByte));
   30776   type = pFile->locktype;
   30777   if( type>=EXCLUSIVE_LOCK ){
   30778     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
   30779     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
   30780       /* This should never happen.  We should always be able to
   30781       ** reacquire the read lock */
   30782       rc = SQLITE_IOERR_UNLOCK;
   30783     }
   30784   }
   30785   if( type>=RESERVED_LOCK ){
   30786     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
   30787   }
   30788   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
   30789     unlockReadLock(pFile);
   30790   }
   30791   if( type>=PENDING_LOCK ){
   30792     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
   30793   }
   30794   pFile->locktype = (u8)locktype;
   30795   return rc;
   30796 }
   30797 
   30798 /*
   30799 ** Control and query of the open file handle.
   30800 */
   30801 static int winFileControl(sqlite3_file *id, int op, void *pArg){
   30802   switch( op ){
   30803     case SQLITE_FCNTL_LOCKSTATE: {
   30804       *(int*)pArg = ((winFile*)id)->locktype;
   30805       return SQLITE_OK;
   30806     }
   30807     case SQLITE_LAST_ERRNO: {
   30808       *(int*)pArg = (int)((winFile*)id)->lastErrno;
   30809       return SQLITE_OK;
   30810     }
   30811     case SQLITE_FCNTL_CHUNK_SIZE: {
   30812       ((winFile*)id)->szChunk = *(int *)pArg;
   30813       return SQLITE_OK;
   30814     }
   30815     case SQLITE_FCNTL_SIZE_HINT: {
   30816       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
   30817       SimulateIOErrorBenign(1);
   30818       winTruncate(id, sz);
   30819       SimulateIOErrorBenign(0);
   30820       return SQLITE_OK;
   30821     }
   30822   }
   30823   return SQLITE_ERROR;
   30824 }
   30825 
   30826 /*
   30827 ** Return the sector size in bytes of the underlying block device for
   30828 ** the specified file. This is almost always 512 bytes, but may be
   30829 ** larger for some devices.
   30830 **
   30831 ** SQLite code assumes this function cannot fail. It also assumes that
   30832 ** if two files are created in the same file-system directory (i.e.
   30833 ** a database and its journal file) that the sector size will be the
   30834 ** same for both.
   30835 */
   30836 static int winSectorSize(sqlite3_file *id){
   30837   assert( id!=0 );
   30838   return (int)(((winFile*)id)->sectorSize);
   30839 }
   30840 
   30841 /*
   30842 ** Return a vector of device characteristics.
   30843 */
   30844 static int winDeviceCharacteristics(sqlite3_file *id){
   30845   UNUSED_PARAMETER(id);
   30846   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
   30847 }
   30848 
   30849 #ifndef SQLITE_OMIT_WAL
   30850 
   30851 /*
   30852 ** Windows will only let you create file view mappings
   30853 ** on allocation size granularity boundaries.
   30854 ** During sqlite3_os_init() we do a GetSystemInfo()
   30855 ** to get the granularity size.
   30856 */
   30857 SYSTEM_INFO winSysInfo;
   30858 
   30859 /*
   30860 ** Helper functions to obtain and relinquish the global mutex. The
   30861 ** global mutex is used to protect the winLockInfo objects used by
   30862 ** this file, all of which may be shared by multiple threads.
   30863 **
   30864 ** Function winShmMutexHeld() is used to assert() that the global mutex
   30865 ** is held when required. This function is only used as part of assert()
   30866 ** statements. e.g.
   30867 **
   30868 **   winShmEnterMutex()
   30869 **     assert( winShmMutexHeld() );
   30870 **   winShmLeaveMutex()
   30871 */
   30872 static void winShmEnterMutex(void){
   30873   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   30874 }
   30875 static void winShmLeaveMutex(void){
   30876   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   30877 }
   30878 #ifdef SQLITE_DEBUG
   30879 static int winShmMutexHeld(void) {
   30880   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   30881 }
   30882 #endif
   30883 
   30884 /*
   30885 ** Object used to represent a single file opened and mmapped to provide
   30886 ** shared memory.  When multiple threads all reference the same
   30887 ** log-summary, each thread has its own winFile object, but they all
   30888 ** point to a single instance of this object.  In other words, each
   30889 ** log-summary is opened only once per process.
   30890 **
   30891 ** winShmMutexHeld() must be true when creating or destroying
   30892 ** this object or while reading or writing the following fields:
   30893 **
   30894 **      nRef
   30895 **      pNext
   30896 **
   30897 ** The following fields are read-only after the object is created:
   30898 **
   30899 **      fid
   30900 **      zFilename
   30901 **
   30902 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
   30903 ** winShmMutexHeld() is true when reading or writing any other field
   30904 ** in this structure.
   30905 **
   30906 */
   30907 struct winShmNode {
   30908   sqlite3_mutex *mutex;      /* Mutex to access this object */
   30909   char *zFilename;           /* Name of the file */
   30910   winFile hFile;             /* File handle from winOpen */
   30911 
   30912   int szRegion;              /* Size of shared-memory regions */
   30913   int nRegion;               /* Size of array apRegion */
   30914   struct ShmRegion {
   30915     HANDLE hMap;             /* File handle from CreateFileMapping */
   30916     void *pMap;
   30917   } *aRegion;
   30918   DWORD lastErrno;           /* The Windows errno from the last I/O error */
   30919 
   30920   int nRef;                  /* Number of winShm objects pointing to this */
   30921   winShm *pFirst;            /* All winShm objects pointing to this */
   30922   winShmNode *pNext;         /* Next in list of all winShmNode objects */
   30923 #ifdef SQLITE_DEBUG
   30924   u8 nextShmId;              /* Next available winShm.id value */
   30925 #endif
   30926 };
   30927 
   30928 /*
   30929 ** A global array of all winShmNode objects.
   30930 **
   30931 ** The winShmMutexHeld() must be true while reading or writing this list.
   30932 */
   30933 static winShmNode *winShmNodeList = 0;
   30934 
   30935 /*
   30936 ** Structure used internally by this VFS to record the state of an
   30937 ** open shared memory connection.
   30938 **
   30939 ** The following fields are initialized when this object is created and
   30940 ** are read-only thereafter:
   30941 **
   30942 **    winShm.pShmNode
   30943 **    winShm.id
   30944 **
   30945 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
   30946 ** while accessing any read/write fields.
   30947 */
   30948 struct winShm {
   30949   winShmNode *pShmNode;      /* The underlying winShmNode object */
   30950   winShm *pNext;             /* Next winShm with the same winShmNode */
   30951   u8 hasMutex;               /* True if holding the winShmNode mutex */
   30952   u16 sharedMask;            /* Mask of shared locks held */
   30953   u16 exclMask;              /* Mask of exclusive locks held */
   30954 #ifdef SQLITE_DEBUG
   30955   u8 id;                     /* Id of this connection with its winShmNode */
   30956 #endif
   30957 };
   30958 
   30959 /*
   30960 ** Constants used for locking
   30961 */
   30962 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
   30963 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
   30964 
   30965 /*
   30966 ** Apply advisory locks for all n bytes beginning at ofst.
   30967 */
   30968 #define _SHM_UNLCK  1
   30969 #define _SHM_RDLCK  2
   30970 #define _SHM_WRLCK  3
   30971 static int winShmSystemLock(
   30972   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
   30973   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
   30974   int ofst,             /* Offset to first byte to be locked/unlocked */
   30975   int nByte             /* Number of bytes to lock or unlock */
   30976 ){
   30977   OVERLAPPED ovlp;
   30978   DWORD dwFlags;
   30979   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
   30980 
   30981   /* Access to the winShmNode object is serialized by the caller */
   30982   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
   30983 
   30984   /* Initialize the locking parameters */
   30985   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
   30986   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
   30987 
   30988   memset(&ovlp, 0, sizeof(OVERLAPPED));
   30989   ovlp.Offset = ofst;
   30990 
   30991   /* Release/Acquire the system-level lock */
   30992   if( lockType==_SHM_UNLCK ){
   30993     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
   30994   }else{
   30995     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
   30996   }
   30997 
   30998   if( rc!= 0 ){
   30999     rc = SQLITE_OK;
   31000   }else{
   31001     pFile->lastErrno =  GetLastError();
   31002     rc = SQLITE_BUSY;
   31003   }
   31004 
   31005   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
   31006            pFile->hFile.h,
   31007            rc==SQLITE_OK ? "ok" : "failed",
   31008            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
   31009            pFile->lastErrno));
   31010 
   31011   return rc;
   31012 }
   31013 
   31014 /* Forward references to VFS methods */
   31015 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
   31016 static int winDelete(sqlite3_vfs *,const char*,int);
   31017 
   31018 /*
   31019 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
   31020 **
   31021 ** This is not a VFS shared-memory method; it is a utility function called
   31022 ** by VFS shared-memory methods.
   31023 */
   31024 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
   31025   winShmNode **pp;
   31026   winShmNode *p;
   31027   BOOL bRc;
   31028   assert( winShmMutexHeld() );
   31029   pp = &winShmNodeList;
   31030   while( (p = *pp)!=0 ){
   31031     if( p->nRef==0 ){
   31032       int i;
   31033       if( p->mutex ) sqlite3_mutex_free(p->mutex);
   31034       for(i=0; i<p->nRegion; i++){
   31035         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
   31036         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
   31037                  (int)GetCurrentProcessId(), i,
   31038                  bRc ? "ok" : "failed"));
   31039         bRc = CloseHandle(p->aRegion[i].hMap);
   31040         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
   31041                  (int)GetCurrentProcessId(), i,
   31042                  bRc ? "ok" : "failed"));
   31043       }
   31044       if( p->hFile.h != INVALID_HANDLE_VALUE ){
   31045         SimulateIOErrorBenign(1);
   31046         winClose((sqlite3_file *)&p->hFile);
   31047         SimulateIOErrorBenign(0);
   31048       }
   31049       if( deleteFlag ){
   31050         SimulateIOErrorBenign(1);
   31051         winDelete(pVfs, p->zFilename, 0);
   31052         SimulateIOErrorBenign(0);
   31053       }
   31054       *pp = p->pNext;
   31055       sqlite3_free(p->aRegion);
   31056       sqlite3_free(p);
   31057     }else{
   31058       pp = &p->pNext;
   31059     }
   31060   }
   31061 }
   31062 
   31063 /*
   31064 ** Open the shared-memory area associated with database file pDbFd.
   31065 **
   31066 ** When opening a new shared-memory file, if no other instances of that
   31067 ** file are currently open, in this process or in other processes, then
   31068 ** the file must be truncated to zero length or have its header cleared.
   31069 */
   31070 static int winOpenSharedMemory(winFile *pDbFd){
   31071   struct winShm *p;                  /* The connection to be opened */
   31072   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
   31073   int rc;                            /* Result code */
   31074   struct winShmNode *pNew;           /* Newly allocated winShmNode */
   31075   int nName;                         /* Size of zName in bytes */
   31076 
   31077   assert( pDbFd->pShm==0 );    /* Not previously opened */
   31078 
   31079   /* Allocate space for the new sqlite3_shm object.  Also speculatively
   31080   ** allocate space for a new winShmNode and filename.
   31081   */
   31082   p = sqlite3_malloc( sizeof(*p) );
   31083   if( p==0 ) return SQLITE_NOMEM;
   31084   memset(p, 0, sizeof(*p));
   31085   nName = sqlite3Strlen30(pDbFd->zPath);
   31086   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
   31087   if( pNew==0 ){
   31088     sqlite3_free(p);
   31089     return SQLITE_NOMEM;
   31090   }
   31091   memset(pNew, 0, sizeof(*pNew));
   31092   pNew->zFilename = (char*)&pNew[1];
   31093   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
   31094 
   31095   /* Look to see if there is an existing winShmNode that can be used.
   31096   ** If no matching winShmNode currently exists, create a new one.
   31097   */
   31098   winShmEnterMutex();
   31099   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
   31100     /* TBD need to come up with better match here.  Perhaps
   31101     ** use FILE_ID_BOTH_DIR_INFO Structure.
   31102     */
   31103     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
   31104   }
   31105   if( pShmNode ){
   31106     sqlite3_free(pNew);
   31107   }else{
   31108     pShmNode = pNew;
   31109     pNew = 0;
   31110     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
   31111     pShmNode->pNext = winShmNodeList;
   31112     winShmNodeList = pShmNode;
   31113 
   31114     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
   31115     if( pShmNode->mutex==0 ){
   31116       rc = SQLITE_NOMEM;
   31117       goto shm_open_err;
   31118     }
   31119 
   31120     rc = winOpen(pDbFd->pVfs,
   31121                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
   31122                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
   31123                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
   31124                  0);
   31125     if( SQLITE_OK!=rc ){
   31126       rc = SQLITE_CANTOPEN_BKPT;
   31127       goto shm_open_err;
   31128     }
   31129 
   31130     /* Check to see if another process is holding the dead-man switch.
   31131     ** If not, truncate the file to zero length.
   31132     */
   31133     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
   31134       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
   31135       if( rc!=SQLITE_OK ){
   31136         rc = SQLITE_IOERR_SHMOPEN;
   31137       }
   31138     }
   31139     if( rc==SQLITE_OK ){
   31140       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   31141       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
   31142     }
   31143     if( rc ) goto shm_open_err;
   31144   }
   31145 
   31146   /* Make the new connection a child of the winShmNode */
   31147   p->pShmNode = pShmNode;
   31148 #ifdef SQLITE_DEBUG
   31149   p->id = pShmNode->nextShmId++;
   31150 #endif
   31151   pShmNode->nRef++;
   31152   pDbFd->pShm = p;
   31153   winShmLeaveMutex();
   31154 
   31155   /* The reference count on pShmNode has already been incremented under
   31156   ** the cover of the winShmEnterMutex() mutex and the pointer from the
   31157   ** new (struct winShm) object to the pShmNode has been set. All that is
   31158   ** left to do is to link the new object into the linked list starting
   31159   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
   31160   ** mutex.
   31161   */
   31162   sqlite3_mutex_enter(pShmNode->mutex);
   31163   p->pNext = pShmNode->pFirst;
   31164   pShmNode->pFirst = p;
   31165   sqlite3_mutex_leave(pShmNode->mutex);
   31166   return SQLITE_OK;
   31167 
   31168   /* Jump here on any error */
   31169 shm_open_err:
   31170   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
   31171   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
   31172   sqlite3_free(p);
   31173   sqlite3_free(pNew);
   31174   winShmLeaveMutex();
   31175   return rc;
   31176 }
   31177 
   31178 /*
   31179 ** Close a connection to shared-memory.  Delete the underlying
   31180 ** storage if deleteFlag is true.
   31181 */
   31182 static int winShmUnmap(
   31183   sqlite3_file *fd,          /* Database holding shared memory */
   31184   int deleteFlag             /* Delete after closing if true */
   31185 ){
   31186   winFile *pDbFd;       /* Database holding shared-memory */
   31187   winShm *p;            /* The connection to be closed */
   31188   winShmNode *pShmNode; /* The underlying shared-memory file */
   31189   winShm **pp;          /* For looping over sibling connections */
   31190 
   31191   pDbFd = (winFile*)fd;
   31192   p = pDbFd->pShm;
   31193   if( p==0 ) return SQLITE_OK;
   31194   pShmNode = p->pShmNode;
   31195 
   31196   /* Remove connection p from the set of connections associated
   31197   ** with pShmNode */
   31198   sqlite3_mutex_enter(pShmNode->mutex);
   31199   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
   31200   *pp = p->pNext;
   31201 
   31202   /* Free the connection p */
   31203   sqlite3_free(p);
   31204   pDbFd->pShm = 0;
   31205   sqlite3_mutex_leave(pShmNode->mutex);
   31206 
   31207   /* If pShmNode->nRef has reached 0, then close the underlying
   31208   ** shared-memory file, too */
   31209   winShmEnterMutex();
   31210   assert( pShmNode->nRef>0 );
   31211   pShmNode->nRef--;
   31212   if( pShmNode->nRef==0 ){
   31213     winShmPurge(pDbFd->pVfs, deleteFlag);
   31214   }
   31215   winShmLeaveMutex();
   31216 
   31217   return SQLITE_OK;
   31218 }
   31219 
   31220 /*
   31221 ** Change the lock state for a shared-memory segment.
   31222 */
   31223 static int winShmLock(
   31224   sqlite3_file *fd,          /* Database file holding the shared memory */
   31225   int ofst,                  /* First lock to acquire or release */
   31226   int n,                     /* Number of locks to acquire or release */
   31227   int flags                  /* What to do with the lock */
   31228 ){
   31229   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
   31230   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
   31231   winShm *pX;                           /* For looping over all siblings */
   31232   winShmNode *pShmNode = p->pShmNode;
   31233   int rc = SQLITE_OK;                   /* Result code */
   31234   u16 mask;                             /* Mask of locks to take or release */
   31235 
   31236   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
   31237   assert( n>=1 );
   31238   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
   31239        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
   31240        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
   31241        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
   31242   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
   31243 
   31244   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
   31245   assert( n>1 || mask==(1<<ofst) );
   31246   sqlite3_mutex_enter(pShmNode->mutex);
   31247   if( flags & SQLITE_SHM_UNLOCK ){
   31248     u16 allMask = 0; /* Mask of locks held by siblings */
   31249 
   31250     /* See if any siblings hold this same lock */
   31251     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   31252       if( pX==p ) continue;
   31253       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
   31254       allMask |= pX->sharedMask;
   31255     }
   31256 
   31257     /* Unlock the system-level locks */
   31258     if( (mask & allMask)==0 ){
   31259       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
   31260     }else{
   31261       rc = SQLITE_OK;
   31262     }
   31263 
   31264     /* Undo the local locks */
   31265     if( rc==SQLITE_OK ){
   31266       p->exclMask &= ~mask;
   31267       p->sharedMask &= ~mask;
   31268     }
   31269   }else if( flags & SQLITE_SHM_SHARED ){
   31270     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
   31271 
   31272     /* Find out which shared locks are already held by sibling connections.
   31273     ** If any sibling already holds an exclusive lock, go ahead and return
   31274     ** SQLITE_BUSY.
   31275     */
   31276     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   31277       if( (pX->exclMask & mask)!=0 ){
   31278         rc = SQLITE_BUSY;
   31279         break;
   31280       }
   31281       allShared |= pX->sharedMask;
   31282     }
   31283 
   31284     /* Get shared locks at the system level, if necessary */
   31285     if( rc==SQLITE_OK ){
   31286       if( (allShared & mask)==0 ){
   31287         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
   31288       }else{
   31289         rc = SQLITE_OK;
   31290       }
   31291     }
   31292 
   31293     /* Get the local shared locks */
   31294     if( rc==SQLITE_OK ){
   31295       p->sharedMask |= mask;
   31296     }
   31297   }else{
   31298     /* Make sure no sibling connections hold locks that will block this
   31299     ** lock.  If any do, return SQLITE_BUSY right away.
   31300     */
   31301     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
   31302       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
   31303         rc = SQLITE_BUSY;
   31304         break;
   31305       }
   31306     }
   31307 
   31308     /* Get the exclusive locks at the system level.  Then if successful
   31309     ** also mark the local connection as being locked.
   31310     */
   31311     if( rc==SQLITE_OK ){
   31312       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
   31313       if( rc==SQLITE_OK ){
   31314         assert( (p->sharedMask & mask)==0 );
   31315         p->exclMask |= mask;
   31316       }
   31317     }
   31318   }
   31319   sqlite3_mutex_leave(pShmNode->mutex);
   31320   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
   31321            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
   31322            rc ? "failed" : "ok"));
   31323   return rc;
   31324 }
   31325 
   31326 /*
   31327 ** Implement a memory barrier or memory fence on shared memory.
   31328 **
   31329 ** All loads and stores begun before the barrier must complete before
   31330 ** any load or store begun after the barrier.
   31331 */
   31332 static void winShmBarrier(
   31333   sqlite3_file *fd          /* Database holding the shared memory */
   31334 ){
   31335   UNUSED_PARAMETER(fd);
   31336   /* MemoryBarrier(); // does not work -- do not know why not */
   31337   winShmEnterMutex();
   31338   winShmLeaveMutex();
   31339 }
   31340 
   31341 /*
   31342 ** This function is called to obtain a pointer to region iRegion of the
   31343 ** shared-memory associated with the database file fd. Shared-memory regions
   31344 ** are numbered starting from zero. Each shared-memory region is szRegion
   31345 ** bytes in size.
   31346 **
   31347 ** If an error occurs, an error code is returned and *pp is set to NULL.
   31348 **
   31349 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
   31350 ** region has not been allocated (by any client, including one running in a
   31351 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
   31352 ** isWrite is non-zero and the requested shared-memory region has not yet
   31353 ** been allocated, it is allocated by this function.
   31354 **
   31355 ** If the shared-memory region has already been allocated or is allocated by
   31356 ** this call as described above, then it is mapped into this processes
   31357 ** address space (if it is not already), *pp is set to point to the mapped
   31358 ** memory and SQLITE_OK returned.
   31359 */
   31360 static int winShmMap(
   31361   sqlite3_file *fd,               /* Handle open on database file */
   31362   int iRegion,                    /* Region to retrieve */
   31363   int szRegion,                   /* Size of regions */
   31364   int isWrite,                    /* True to extend file if necessary */
   31365   void volatile **pp              /* OUT: Mapped memory */
   31366 ){
   31367   winFile *pDbFd = (winFile*)fd;
   31368   winShm *p = pDbFd->pShm;
   31369   winShmNode *pShmNode;
   31370   int rc = SQLITE_OK;
   31371 
   31372   if( !p ){
   31373     rc = winOpenSharedMemory(pDbFd);
   31374     if( rc!=SQLITE_OK ) return rc;
   31375     p = pDbFd->pShm;
   31376   }
   31377   pShmNode = p->pShmNode;
   31378 
   31379   sqlite3_mutex_enter(pShmNode->mutex);
   31380   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
   31381 
   31382   if( pShmNode->nRegion<=iRegion ){
   31383     struct ShmRegion *apNew;           /* New aRegion[] array */
   31384     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
   31385     sqlite3_int64 sz;                  /* Current size of wal-index file */
   31386 
   31387     pShmNode->szRegion = szRegion;
   31388 
   31389     /* The requested region is not mapped into this processes address space.
   31390     ** Check to see if it has been allocated (i.e. if the wal-index file is
   31391     ** large enough to contain the requested region).
   31392     */
   31393     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
   31394     if( rc!=SQLITE_OK ){
   31395       rc = SQLITE_IOERR_SHMSIZE;
   31396       goto shmpage_out;
   31397     }
   31398 
   31399     if( sz<nByte ){
   31400       /* The requested memory region does not exist. If isWrite is set to
   31401       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
   31402       **
   31403       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
   31404       ** the requested memory region.
   31405       */
   31406       if( !isWrite ) goto shmpage_out;
   31407       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
   31408       if( rc!=SQLITE_OK ){
   31409         rc = SQLITE_IOERR_SHMSIZE;
   31410         goto shmpage_out;
   31411       }
   31412     }
   31413 
   31414     /* Map the requested memory region into this processes address space. */
   31415     apNew = (struct ShmRegion *)sqlite3_realloc(
   31416         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
   31417     );
   31418     if( !apNew ){
   31419       rc = SQLITE_IOERR_NOMEM;
   31420       goto shmpage_out;
   31421     }
   31422     pShmNode->aRegion = apNew;
   31423 
   31424     while( pShmNode->nRegion<=iRegion ){
   31425       HANDLE hMap;                /* file-mapping handle */
   31426       void *pMap = 0;             /* Mapped memory region */
   31427 
   31428       hMap = CreateFileMapping(pShmNode->hFile.h,
   31429           NULL, PAGE_READWRITE, 0, nByte, NULL
   31430       );
   31431       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
   31432                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
   31433                hMap ? "ok" : "failed"));
   31434       if( hMap ){
   31435         int iOffset = pShmNode->nRegion*szRegion;
   31436         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   31437         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
   31438             0, iOffset - iOffsetShift, szRegion + iOffsetShift
   31439         );
   31440         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
   31441                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
   31442                  pMap ? "ok" : "failed"));
   31443       }
   31444       if( !pMap ){
   31445         pShmNode->lastErrno = GetLastError();
   31446         rc = SQLITE_IOERR;
   31447         if( hMap ) CloseHandle(hMap);
   31448         goto shmpage_out;
   31449       }
   31450 
   31451       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
   31452       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
   31453       pShmNode->nRegion++;
   31454     }
   31455   }
   31456 
   31457 shmpage_out:
   31458   if( pShmNode->nRegion>iRegion ){
   31459     int iOffset = iRegion*szRegion;
   31460     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
   31461     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
   31462     *pp = (void *)&p[iOffsetShift];
   31463   }else{
   31464     *pp = 0;
   31465   }
   31466   sqlite3_mutex_leave(pShmNode->mutex);
   31467   return rc;
   31468 }
   31469 
   31470 #else
   31471 # define winShmMap     0
   31472 # define winShmLock    0
   31473 # define winShmBarrier 0
   31474 # define winShmUnmap   0
   31475 #endif /* #ifndef SQLITE_OMIT_WAL */
   31476 
   31477 /*
   31478 ** Here ends the implementation of all sqlite3_file methods.
   31479 **
   31480 ********************** End sqlite3_file Methods *******************************
   31481 ******************************************************************************/
   31482 
   31483 /*
   31484 ** This vector defines all the methods that can operate on an
   31485 ** sqlite3_file for win32.
   31486 */
   31487 static const sqlite3_io_methods winIoMethod = {
   31488   2,                              /* iVersion */
   31489   winClose,                       /* xClose */
   31490   winRead,                        /* xRead */
   31491   winWrite,                       /* xWrite */
   31492   winTruncate,                    /* xTruncate */
   31493   winSync,                        /* xSync */
   31494   winFileSize,                    /* xFileSize */
   31495   winLock,                        /* xLock */
   31496   winUnlock,                      /* xUnlock */
   31497   winCheckReservedLock,           /* xCheckReservedLock */
   31498   winFileControl,                 /* xFileControl */
   31499   winSectorSize,                  /* xSectorSize */
   31500   winDeviceCharacteristics,       /* xDeviceCharacteristics */
   31501   winShmMap,                      /* xShmMap */
   31502   winShmLock,                     /* xShmLock */
   31503   winShmBarrier,                  /* xShmBarrier */
   31504   winShmUnmap                     /* xShmUnmap */
   31505 };
   31506 
   31507 /****************************************************************************
   31508 **************************** sqlite3_vfs methods ****************************
   31509 **
   31510 ** This division contains the implementation of methods on the
   31511 ** sqlite3_vfs object.
   31512 */
   31513 
   31514 /*
   31515 ** Convert a UTF-8 filename into whatever form the underlying
   31516 ** operating system wants filenames in.  Space to hold the result
   31517 ** is obtained from malloc and must be freed by the calling
   31518 ** function.
   31519 */
   31520 static void *convertUtf8Filename(const char *zFilename){
   31521   void *zConverted = 0;
   31522   if( isNT() ){
   31523     zConverted = utf8ToUnicode(zFilename);
   31524 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31525 */
   31526 #if SQLITE_OS_WINCE==0
   31527   }else{
   31528     zConverted = utf8ToMbcs(zFilename);
   31529 #endif
   31530   }
   31531   /* caller will handle out of memory */
   31532   return zConverted;
   31533 }
   31534 
   31535 /*
   31536 ** Create a temporary file name in zBuf.  zBuf must be big enough to
   31537 ** hold at pVfs->mxPathname characters.
   31538 */
   31539 static int getTempname(int nBuf, char *zBuf){
   31540   static char zChars[] =
   31541     "abcdefghijklmnopqrstuvwxyz"
   31542     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   31543     "0123456789";
   31544   size_t i, j;
   31545   char zTempPath[MAX_PATH+1];
   31546 
   31547   /* It's odd to simulate an io-error here, but really this is just
   31548   ** using the io-error infrastructure to test that SQLite handles this
   31549   ** function failing.
   31550   */
   31551   SimulateIOError( return SQLITE_IOERR );
   31552 
   31553   if( sqlite3_temp_directory ){
   31554     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
   31555   }else if( isNT() ){
   31556     char *zMulti;
   31557     WCHAR zWidePath[MAX_PATH];
   31558     GetTempPathW(MAX_PATH-30, zWidePath);
   31559     zMulti = unicodeToUtf8(zWidePath);
   31560     if( zMulti ){
   31561       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
   31562       free(zMulti);
   31563     }else{
   31564       return SQLITE_NOMEM;
   31565     }
   31566 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31567 ** Since the ASCII version of these Windows API do not exist for WINCE,
   31568 ** it's important to not reference them for WINCE builds.
   31569 */
   31570 #if SQLITE_OS_WINCE==0
   31571   }else{
   31572     char *zUtf8;
   31573     char zMbcsPath[MAX_PATH];
   31574     GetTempPathA(MAX_PATH-30, zMbcsPath);
   31575     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
   31576     if( zUtf8 ){
   31577       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
   31578       free(zUtf8);
   31579     }else{
   31580       return SQLITE_NOMEM;
   31581     }
   31582 #endif
   31583   }
   31584 
   31585   /* Check that the output buffer is large enough for the temporary file
   31586   ** name. If it is not, return SQLITE_ERROR.
   31587   */
   31588   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
   31589     return SQLITE_ERROR;
   31590   }
   31591 
   31592   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
   31593   zTempPath[i] = 0;
   31594 
   31595   sqlite3_snprintf(nBuf-17, zBuf,
   31596                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
   31597   j = sqlite3Strlen30(zBuf);
   31598   sqlite3_randomness(15, &zBuf[j]);
   31599   for(i=0; i<15; i++, j++){
   31600     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
   31601   }
   31602   zBuf[j] = 0;
   31603 
   31604   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
   31605   return SQLITE_OK;
   31606 }
   31607 
   31608 /*
   31609 ** The return value of getLastErrorMsg
   31610 ** is zero if the error message fits in the buffer, or non-zero
   31611 ** otherwise (if the message was truncated).
   31612 */
   31613 static int getLastErrorMsg(int nBuf, char *zBuf){
   31614   /* FormatMessage returns 0 on failure.  Otherwise it
   31615   ** returns the number of TCHARs written to the output
   31616   ** buffer, excluding the terminating null char.
   31617   */
   31618   DWORD error = GetLastError();
   31619   DWORD dwLen = 0;
   31620   char *zOut = 0;
   31621 
   31622   if( isNT() ){
   31623     WCHAR *zTempWide = NULL;
   31624     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   31625                            NULL,
   31626                            error,
   31627                            0,
   31628                            (LPWSTR) &zTempWide,
   31629                            0,
   31630                            0);
   31631     if( dwLen > 0 ){
   31632       /* allocate a buffer and convert to UTF8 */
   31633       zOut = unicodeToUtf8(zTempWide);
   31634       /* free the system buffer allocated by FormatMessage */
   31635       LocalFree(zTempWide);
   31636     }
   31637 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31638 ** Since the ASCII version of these Windows API do not exist for WINCE,
   31639 ** it's important to not reference them for WINCE builds.
   31640 */
   31641 #if SQLITE_OS_WINCE==0
   31642   }else{
   31643     char *zTemp = NULL;
   31644     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   31645                            NULL,
   31646                            error,
   31647                            0,
   31648                            (LPSTR) &zTemp,
   31649                            0,
   31650                            0);
   31651     if( dwLen > 0 ){
   31652       /* allocate a buffer and convert to UTF8 */
   31653       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   31654       /* free the system buffer allocated by FormatMessage */
   31655       LocalFree(zTemp);
   31656     }
   31657 #endif
   31658   }
   31659   if( 0 == dwLen ){
   31660     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
   31661   }else{
   31662     /* copy a maximum of nBuf chars to output buffer */
   31663     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   31664     /* free the UTF8 buffer */
   31665     free(zOut);
   31666   }
   31667   return 0;
   31668 }
   31669 
   31670 /*
   31671 ** Open a file.
   31672 */
   31673 static int winOpen(
   31674   sqlite3_vfs *pVfs,        /* Not used */
   31675   const char *zName,        /* Name of the file (UTF-8) */
   31676   sqlite3_file *id,         /* Write the SQLite file handle here */
   31677   int flags,                /* Open mode flags */
   31678   int *pOutFlags            /* Status return flags */
   31679 ){
   31680   HANDLE h;
   31681   DWORD dwDesiredAccess;
   31682   DWORD dwShareMode;
   31683   DWORD dwCreationDisposition;
   31684   DWORD dwFlagsAndAttributes = 0;
   31685 #if SQLITE_OS_WINCE
   31686   int isTemp = 0;
   31687 #endif
   31688   winFile *pFile = (winFile*)id;
   31689   void *zConverted;              /* Filename in OS encoding */
   31690   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
   31691 
   31692   /* If argument zPath is a NULL pointer, this function is required to open
   31693   ** a temporary file. Use this buffer to store the file name in.
   31694   */
   31695   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
   31696 
   31697   int rc = SQLITE_OK;            /* Function Return Code */
   31698 #if !defined(NDEBUG) || SQLITE_OS_WINCE
   31699   int eType = flags&0xFFFFFF00;  /* Type of file to open */
   31700 #endif
   31701 
   31702   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
   31703   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
   31704   int isCreate     = (flags & SQLITE_OPEN_CREATE);
   31705 #ifndef NDEBUG
   31706   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
   31707 #endif
   31708   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
   31709 
   31710 #ifndef NDEBUG
   31711   int isOpenJournal = (isCreate && (
   31712         eType==SQLITE_OPEN_MASTER_JOURNAL
   31713      || eType==SQLITE_OPEN_MAIN_JOURNAL
   31714      || eType==SQLITE_OPEN_WAL
   31715   ));
   31716 #endif
   31717 
   31718   /* Check the following statements are true:
   31719   **
   31720   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   31721   **   (b) if CREATE is set, then READWRITE must also be set, and
   31722   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   31723   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
   31724   */
   31725   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
   31726   assert(isCreate==0 || isReadWrite);
   31727   assert(isExclusive==0 || isCreate);
   31728   assert(isDelete==0 || isCreate);
   31729 
   31730   /* The main DB, main journal, WAL file and master journal are never
   31731   ** automatically deleted. Nor are they ever temporary files.  */
   31732   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   31733   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
   31734   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
   31735   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
   31736 
   31737   /* Assert that the upper layer has set one of the "file-type" flags. */
   31738   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
   31739        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
   31740        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
   31741        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   31742   );
   31743 
   31744   assert( id!=0 );
   31745   UNUSED_PARAMETER(pVfs);
   31746 
   31747   pFile->h = INVALID_HANDLE_VALUE;
   31748 
   31749   /* If the second argument to this function is NULL, generate a
   31750   ** temporary file name to use
   31751   */
   31752   if( !zUtf8Name ){
   31753     assert(isDelete && !isOpenJournal);
   31754     rc = getTempname(MAX_PATH+1, zTmpname);
   31755     if( rc!=SQLITE_OK ){
   31756       return rc;
   31757     }
   31758     zUtf8Name = zTmpname;
   31759   }
   31760 
   31761   /* Convert the filename to the system encoding. */
   31762   zConverted = convertUtf8Filename(zUtf8Name);
   31763   if( zConverted==0 ){
   31764     return SQLITE_NOMEM;
   31765   }
   31766 
   31767   if( isReadWrite ){
   31768     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
   31769   }else{
   31770     dwDesiredAccess = GENERIC_READ;
   31771   }
   31772 
   31773   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
   31774   ** created. SQLite doesn't use it to indicate "exclusive access"
   31775   ** as it is usually understood.
   31776   */
   31777   if( isExclusive ){
   31778     /* Creates a new file, only if it does not already exist. */
   31779     /* If the file exists, it fails. */
   31780     dwCreationDisposition = CREATE_NEW;
   31781   }else if( isCreate ){
   31782     /* Open existing file, or create if it doesn't exist */
   31783     dwCreationDisposition = OPEN_ALWAYS;
   31784   }else{
   31785     /* Opens a file, only if it exists. */
   31786     dwCreationDisposition = OPEN_EXISTING;
   31787   }
   31788 
   31789   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
   31790 
   31791   if( isDelete ){
   31792 #if SQLITE_OS_WINCE
   31793     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
   31794     isTemp = 1;
   31795 #else
   31796     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
   31797                                | FILE_ATTRIBUTE_HIDDEN
   31798                                | FILE_FLAG_DELETE_ON_CLOSE;
   31799 #endif
   31800   }else{
   31801     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
   31802   }
   31803   /* Reports from the internet are that performance is always
   31804   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
   31805 #if SQLITE_OS_WINCE
   31806   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
   31807 #endif
   31808 
   31809   if( isNT() ){
   31810     h = CreateFileW((WCHAR*)zConverted,
   31811        dwDesiredAccess,
   31812        dwShareMode,
   31813        NULL,
   31814        dwCreationDisposition,
   31815        dwFlagsAndAttributes,
   31816        NULL
   31817     );
   31818 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31819 ** Since the ASCII version of these Windows API do not exist for WINCE,
   31820 ** it's important to not reference them for WINCE builds.
   31821 */
   31822 #if SQLITE_OS_WINCE==0
   31823   }else{
   31824     h = CreateFileA((char*)zConverted,
   31825        dwDesiredAccess,
   31826        dwShareMode,
   31827        NULL,
   31828        dwCreationDisposition,
   31829        dwFlagsAndAttributes,
   31830        NULL
   31831     );
   31832 #endif
   31833   }
   31834 
   31835   OSTRACE(("OPEN %d %s 0x%lx %s\n",
   31836            h, zName, dwDesiredAccess,
   31837            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
   31838 
   31839   if( h==INVALID_HANDLE_VALUE ){
   31840     pFile->lastErrno = GetLastError();
   31841     free(zConverted);
   31842     if( isReadWrite ){
   31843       return winOpen(pVfs, zName, id,
   31844              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
   31845     }else{
   31846       return SQLITE_CANTOPEN_BKPT;
   31847     }
   31848   }
   31849 
   31850   if( pOutFlags ){
   31851     if( isReadWrite ){
   31852       *pOutFlags = SQLITE_OPEN_READWRITE;
   31853     }else{
   31854       *pOutFlags = SQLITE_OPEN_READONLY;
   31855     }
   31856   }
   31857 
   31858   memset(pFile, 0, sizeof(*pFile));
   31859   pFile->pMethod = &winIoMethod;
   31860   pFile->h = h;
   31861   pFile->lastErrno = NO_ERROR;
   31862   pFile->pVfs = pVfs;
   31863   pFile->pShm = 0;
   31864   pFile->zPath = zName;
   31865   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
   31866 
   31867 #if SQLITE_OS_WINCE
   31868   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
   31869        && !winceCreateLock(zName, pFile)
   31870   ){
   31871     CloseHandle(h);
   31872     free(zConverted);
   31873     return SQLITE_CANTOPEN_BKPT;
   31874   }
   31875   if( isTemp ){
   31876     pFile->zDeleteOnClose = zConverted;
   31877   }else
   31878 #endif
   31879   {
   31880     free(zConverted);
   31881   }
   31882 
   31883   OpenCounter(+1);
   31884   return rc;
   31885 }
   31886 
   31887 /*
   31888 ** Delete the named file.
   31889 **
   31890 ** Note that windows does not allow a file to be deleted if some other
   31891 ** process has it open.  Sometimes a virus scanner or indexing program
   31892 ** will open a journal file shortly after it is created in order to do
   31893 ** whatever it does.  While this other process is holding the
   31894 ** file open, we will be unable to delete it.  To work around this
   31895 ** problem, we delay 100 milliseconds and try to delete again.  Up
   31896 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
   31897 ** up and returning an error.
   31898 */
   31899 #define MX_DELETION_ATTEMPTS 5
   31900 static int winDelete(
   31901   sqlite3_vfs *pVfs,          /* Not used on win32 */
   31902   const char *zFilename,      /* Name of file to delete */
   31903   int syncDir                 /* Not used on win32 */
   31904 ){
   31905   int cnt = 0;
   31906   DWORD rc;
   31907   DWORD error = 0;
   31908   void *zConverted;
   31909   UNUSED_PARAMETER(pVfs);
   31910   UNUSED_PARAMETER(syncDir);
   31911 
   31912   SimulateIOError(return SQLITE_IOERR_DELETE);
   31913   zConverted = convertUtf8Filename(zFilename);
   31914   if( zConverted==0 ){
   31915     return SQLITE_NOMEM;
   31916   }
   31917   if( isNT() ){
   31918     do{
   31919       DeleteFileW(zConverted);
   31920     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
   31921                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
   31922            && (++cnt < MX_DELETION_ATTEMPTS)
   31923            && (Sleep(100), 1) );
   31924 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31925 ** Since the ASCII version of these Windows API do not exist for WINCE,
   31926 ** it's important to not reference them for WINCE builds.
   31927 */
   31928 #if SQLITE_OS_WINCE==0
   31929   }else{
   31930     do{
   31931       DeleteFileA(zConverted);
   31932     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
   31933                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
   31934            && (++cnt < MX_DELETION_ATTEMPTS)
   31935            && (Sleep(100), 1) );
   31936 #endif
   31937   }
   31938   free(zConverted);
   31939   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
   31940        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
   31941          "ok" : "failed" ));
   31942 
   31943   return (   (rc == INVALID_FILE_ATTRIBUTES)
   31944           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
   31945 }
   31946 
   31947 /*
   31948 ** Check the existance and status of a file.
   31949 */
   31950 static int winAccess(
   31951   sqlite3_vfs *pVfs,         /* Not used on win32 */
   31952   const char *zFilename,     /* Name of file to check */
   31953   int flags,                 /* Type of test to make on this file */
   31954   int *pResOut               /* OUT: Result */
   31955 ){
   31956   DWORD attr;
   31957   int rc = 0;
   31958   void *zConverted;
   31959   UNUSED_PARAMETER(pVfs);
   31960 
   31961   SimulateIOError( return SQLITE_IOERR_ACCESS; );
   31962   zConverted = convertUtf8Filename(zFilename);
   31963   if( zConverted==0 ){
   31964     return SQLITE_NOMEM;
   31965   }
   31966   if( isNT() ){
   31967     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
   31968     memset(&sAttrData, 0, sizeof(sAttrData));
   31969     if( GetFileAttributesExW((WCHAR*)zConverted,
   31970                              GetFileExInfoStandard,
   31971                              &sAttrData) ){
   31972       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
   31973       ** as if it does not exist.
   31974       */
   31975       if(    flags==SQLITE_ACCESS_EXISTS
   31976           && sAttrData.nFileSizeHigh==0
   31977           && sAttrData.nFileSizeLow==0 ){
   31978         attr = INVALID_FILE_ATTRIBUTES;
   31979       }else{
   31980         attr = sAttrData.dwFileAttributes;
   31981       }
   31982     }else{
   31983       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
   31984         free(zConverted);
   31985         return SQLITE_IOERR_ACCESS;
   31986       }else{
   31987         attr = INVALID_FILE_ATTRIBUTES;
   31988       }
   31989     }
   31990 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   31991 ** Since the ASCII version of these Windows API do not exist for WINCE,
   31992 ** it's important to not reference them for WINCE builds.
   31993 */
   31994 #if SQLITE_OS_WINCE==0
   31995   }else{
   31996     attr = GetFileAttributesA((char*)zConverted);
   31997 #endif
   31998   }
   31999   free(zConverted);
   32000   switch( flags ){
   32001     case SQLITE_ACCESS_READ:
   32002     case SQLITE_ACCESS_EXISTS:
   32003       rc = attr!=INVALID_FILE_ATTRIBUTES;
   32004       break;
   32005     case SQLITE_ACCESS_READWRITE:
   32006       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
   32007       break;
   32008     default:
   32009       assert(!"Invalid flags argument");
   32010   }
   32011   *pResOut = rc;
   32012   return SQLITE_OK;
   32013 }
   32014 
   32015 
   32016 /*
   32017 ** Turn a relative pathname into a full pathname.  Write the full
   32018 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
   32019 ** bytes in size.
   32020 */
   32021 static int winFullPathname(
   32022   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
   32023   const char *zRelative,        /* Possibly relative input path */
   32024   int nFull,                    /* Size of output buffer in bytes */
   32025   char *zFull                   /* Output buffer */
   32026 ){
   32027 
   32028 #if defined(__CYGWIN__)
   32029   SimulateIOError( return SQLITE_ERROR );
   32030   UNUSED_PARAMETER(nFull);
   32031   cygwin_conv_to_full_win32_path(zRelative, zFull);
   32032   return SQLITE_OK;
   32033 #endif
   32034 
   32035 #if SQLITE_OS_WINCE
   32036   SimulateIOError( return SQLITE_ERROR );
   32037   UNUSED_PARAMETER(nFull);
   32038   /* WinCE has no concept of a relative pathname, or so I am told. */
   32039   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
   32040   return SQLITE_OK;
   32041 #endif
   32042 
   32043 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
   32044   int nByte;
   32045   void *zConverted;
   32046   char *zOut;
   32047 
   32048   /* It's odd to simulate an io-error here, but really this is just
   32049   ** using the io-error infrastructure to test that SQLite handles this
   32050   ** function failing. This function could fail if, for example, the
   32051   ** current working directory has been unlinked.
   32052   */
   32053   SimulateIOError( return SQLITE_ERROR );
   32054   UNUSED_PARAMETER(nFull);
   32055   zConverted = convertUtf8Filename(zRelative);
   32056   if( isNT() ){
   32057     WCHAR *zTemp;
   32058     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
   32059     zTemp = malloc( nByte*sizeof(zTemp[0]) );
   32060     if( zTemp==0 ){
   32061       free(zConverted);
   32062       return SQLITE_NOMEM;
   32063     }
   32064     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
   32065     free(zConverted);
   32066     zOut = unicodeToUtf8(zTemp);
   32067     free(zTemp);
   32068 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   32069 ** Since the ASCII version of these Windows API do not exist for WINCE,
   32070 ** it's important to not reference them for WINCE builds.
   32071 */
   32072 #if SQLITE_OS_WINCE==0
   32073   }else{
   32074     char *zTemp;
   32075     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
   32076     zTemp = malloc( nByte*sizeof(zTemp[0]) );
   32077     if( zTemp==0 ){
   32078       free(zConverted);
   32079       return SQLITE_NOMEM;
   32080     }
   32081     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
   32082     free(zConverted);
   32083     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
   32084     free(zTemp);
   32085 #endif
   32086   }
   32087   if( zOut ){
   32088     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
   32089     free(zOut);
   32090     return SQLITE_OK;
   32091   }else{
   32092     return SQLITE_NOMEM;
   32093   }
   32094 #endif
   32095 }
   32096 
   32097 /*
   32098 ** Get the sector size of the device used to store
   32099 ** file.
   32100 */
   32101 static int getSectorSize(
   32102     sqlite3_vfs *pVfs,
   32103     const char *zRelative     /* UTF-8 file name */
   32104 ){
   32105   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
   32106   /* GetDiskFreeSpace is not supported under WINCE */
   32107 #if SQLITE_OS_WINCE
   32108   UNUSED_PARAMETER(pVfs);
   32109   UNUSED_PARAMETER(zRelative);
   32110 #else
   32111   char zFullpath[MAX_PATH+1];
   32112   int rc;
   32113   DWORD dwRet = 0;
   32114   DWORD dwDummy;
   32115 
   32116   /*
   32117   ** We need to get the full path name of the file
   32118   ** to get the drive letter to look up the sector
   32119   ** size.
   32120   */
   32121   SimulateIOErrorBenign(1);
   32122   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
   32123   SimulateIOErrorBenign(0);
   32124   if( rc == SQLITE_OK )
   32125   {
   32126     void *zConverted = convertUtf8Filename(zFullpath);
   32127     if( zConverted ){
   32128       if( isNT() ){
   32129         /* trim path to just drive reference */
   32130         WCHAR *p = zConverted;
   32131         for(;*p;p++){
   32132           if( *p == '\\' ){
   32133             *p = '\0';
   32134             break;
   32135           }
   32136         }
   32137         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
   32138                                   &dwDummy,
   32139                                   &bytesPerSector,
   32140                                   &dwDummy,
   32141                                   &dwDummy);
   32142       }else{
   32143         /* trim path to just drive reference */
   32144         char *p = (char *)zConverted;
   32145         for(;*p;p++){
   32146           if( *p == '\\' ){
   32147             *p = '\0';
   32148             break;
   32149           }
   32150         }
   32151         dwRet = GetDiskFreeSpaceA((char*)zConverted,
   32152                                   &dwDummy,
   32153                                   &bytesPerSector,
   32154                                   &dwDummy,
   32155                                   &dwDummy);
   32156       }
   32157       free(zConverted);
   32158     }
   32159     if( !dwRet ){
   32160       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
   32161     }
   32162   }
   32163 #endif
   32164   return (int) bytesPerSector;
   32165 }
   32166 
   32167 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   32168 /*
   32169 ** Interfaces for opening a shared library, finding entry points
   32170 ** within the shared library, and closing the shared library.
   32171 */
   32172 /*
   32173 ** Interfaces for opening a shared library, finding entry points
   32174 ** within the shared library, and closing the shared library.
   32175 */
   32176 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
   32177   HANDLE h;
   32178   void *zConverted = convertUtf8Filename(zFilename);
   32179   UNUSED_PARAMETER(pVfs);
   32180   if( zConverted==0 ){
   32181     return 0;
   32182   }
   32183   if( isNT() ){
   32184     h = LoadLibraryW((WCHAR*)zConverted);
   32185 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
   32186 ** Since the ASCII version of these Windows API do not exist for WINCE,
   32187 ** it's important to not reference them for WINCE builds.
   32188 */
   32189 #if SQLITE_OS_WINCE==0
   32190   }else{
   32191     h = LoadLibraryA((char*)zConverted);
   32192 #endif
   32193   }
   32194   free(zConverted);
   32195   return (void*)h;
   32196 }
   32197 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
   32198   UNUSED_PARAMETER(pVfs);
   32199   getLastErrorMsg(nBuf, zBufOut);
   32200 }
   32201 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
   32202   UNUSED_PARAMETER(pVfs);
   32203 #if SQLITE_OS_WINCE
   32204   /* The GetProcAddressA() routine is only available on wince. */
   32205   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
   32206 #else
   32207   /* All other windows platforms expect GetProcAddress() to take
   32208   ** an Ansi string regardless of the _UNICODE setting */
   32209   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
   32210 #endif
   32211 }
   32212 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
   32213   UNUSED_PARAMETER(pVfs);
   32214   FreeLibrary((HANDLE)pHandle);
   32215 }
   32216 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
   32217   #define winDlOpen  0
   32218   #define winDlError 0
   32219   #define winDlSym   0
   32220   #define winDlClose 0
   32221 #endif
   32222 
   32223 
   32224 /*
   32225 ** Write up to nBuf bytes of randomness into zBuf.
   32226 */
   32227 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   32228   int n = 0;
   32229   UNUSED_PARAMETER(pVfs);
   32230 #if defined(SQLITE_TEST)
   32231   n = nBuf;
   32232   memset(zBuf, 0, nBuf);
   32233 #else
   32234   if( sizeof(SYSTEMTIME)<=nBuf-n ){
   32235     SYSTEMTIME x;
   32236     GetSystemTime(&x);
   32237     memcpy(&zBuf[n], &x, sizeof(x));
   32238     n += sizeof(x);
   32239   }
   32240   if( sizeof(DWORD)<=nBuf-n ){
   32241     DWORD pid = GetCurrentProcessId();
   32242     memcpy(&zBuf[n], &pid, sizeof(pid));
   32243     n += sizeof(pid);
   32244   }
   32245   if( sizeof(DWORD)<=nBuf-n ){
   32246     DWORD cnt = GetTickCount();
   32247     memcpy(&zBuf[n], &cnt, sizeof(cnt));
   32248     n += sizeof(cnt);
   32249   }
   32250   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
   32251     LARGE_INTEGER i;
   32252     QueryPerformanceCounter(&i);
   32253     memcpy(&zBuf[n], &i, sizeof(i));
   32254     n += sizeof(i);
   32255   }
   32256 #endif
   32257   return n;
   32258 }
   32259 
   32260 
   32261 /*
   32262 ** Sleep for a little while.  Return the amount of time slept.
   32263 */
   32264 static int winSleep(sqlite3_vfs *pVfs, int microsec){
   32265   Sleep((microsec+999)/1000);
   32266   UNUSED_PARAMETER(pVfs);
   32267   return ((microsec+999)/1000)*1000;
   32268 }
   32269 
   32270 /*
   32271 ** The following variable, if set to a non-zero value, is interpreted as
   32272 ** the number of seconds since 1970 and is used to set the result of
   32273 ** sqlite3OsCurrentTime() during testing.
   32274 */
   32275 #ifdef SQLITE_TEST
   32276 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
   32277 #endif
   32278 
   32279 /*
   32280 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
   32281 ** the current time and date as a Julian Day number times 86_400_000.  In
   32282 ** other words, write into *piNow the number of milliseconds since the Julian
   32283 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
   32284 ** proleptic Gregorian calendar.
   32285 **
   32286 ** On success, return 0.  Return 1 if the time and date cannot be found.
   32287 */
   32288 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
   32289   /* FILETIME structure is a 64-bit value representing the number of
   32290      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
   32291   */
   32292   FILETIME ft;
   32293   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
   32294 #ifdef SQLITE_TEST
   32295   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
   32296 #endif
   32297   /* 2^32 - to avoid use of LL and warnings in gcc */
   32298   static const sqlite3_int64 max32BitValue =
   32299       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
   32300 
   32301 #if SQLITE_OS_WINCE
   32302   SYSTEMTIME time;
   32303   GetSystemTime(&time);
   32304   /* if SystemTimeToFileTime() fails, it returns zero. */
   32305   if (!SystemTimeToFileTime(&time,&ft)){
   32306     return 1;
   32307   }
   32308 #else
   32309   GetSystemTimeAsFileTime( &ft );
   32310 #endif
   32311 
   32312   *piNow = winFiletimeEpoch +
   32313             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
   32314                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
   32315 
   32316 #ifdef SQLITE_TEST
   32317   if( sqlite3_current_time ){
   32318     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
   32319   }
   32320 #endif
   32321   UNUSED_PARAMETER(pVfs);
   32322   return 0;
   32323 }
   32324 
   32325 /*
   32326 ** Find the current time (in Universal Coordinated Time).  Write the
   32327 ** current time and date as a Julian Day number into *prNow and
   32328 ** return 0.  Return 1 if the time and date cannot be found.
   32329 */
   32330 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
   32331   int rc;
   32332   sqlite3_int64 i;
   32333   rc = winCurrentTimeInt64(pVfs, &i);
   32334   if( !rc ){
   32335     *prNow = i/86400000.0;
   32336   }
   32337   return rc;
   32338 }
   32339 
   32340 /*
   32341 ** The idea is that this function works like a combination of
   32342 ** GetLastError() and FormatMessage() on windows (or errno and
   32343 ** strerror_r() on unix). After an error is returned by an OS
   32344 ** function, SQLite calls this function with zBuf pointing to
   32345 ** a buffer of nBuf bytes. The OS layer should populate the
   32346 ** buffer with a nul-terminated UTF-8 encoded error message
   32347 ** describing the last IO error to have occurred within the calling
   32348 ** thread.
   32349 **
   32350 ** If the error message is too large for the supplied buffer,
   32351 ** it should be truncated. The return value of xGetLastError
   32352 ** is zero if the error message fits in the buffer, or non-zero
   32353 ** otherwise (if the message was truncated). If non-zero is returned,
   32354 ** then it is not necessary to include the nul-terminator character
   32355 ** in the output buffer.
   32356 **
   32357 ** Not supplying an error message will have no adverse effect
   32358 ** on SQLite. It is fine to have an implementation that never
   32359 ** returns an error message:
   32360 **
   32361 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   32362 **     assert(zBuf[0]=='\0');
   32363 **     return 0;
   32364 **   }
   32365 **
   32366 ** However if an error message is supplied, it will be incorporated
   32367 ** by sqlite into the error message available to the user using
   32368 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
   32369 */
   32370 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
   32371   UNUSED_PARAMETER(pVfs);
   32372   return getLastErrorMsg(nBuf, zBuf);
   32373 }
   32374 
   32375 
   32376 
   32377 /*
   32378 ** Initialize and deinitialize the operating system interface.
   32379 */
   32380 SQLITE_API int sqlite3_os_init(void){
   32381   static sqlite3_vfs winVfs = {
   32382     2,                   /* iVersion */
   32383     sizeof(winFile),     /* szOsFile */
   32384     MAX_PATH,            /* mxPathname */
   32385     0,                   /* pNext */
   32386     "win32",             /* zName */
   32387     0,                   /* pAppData */
   32388     winOpen,             /* xOpen */
   32389     winDelete,           /* xDelete */
   32390     winAccess,           /* xAccess */
   32391     winFullPathname,     /* xFullPathname */
   32392     winDlOpen,           /* xDlOpen */
   32393     winDlError,          /* xDlError */
   32394     winDlSym,            /* xDlSym */
   32395     winDlClose,          /* xDlClose */
   32396     winRandomness,       /* xRandomness */
   32397     winSleep,            /* xSleep */
   32398     winCurrentTime,      /* xCurrentTime */
   32399     winGetLastError,     /* xGetLastError */
   32400     winCurrentTimeInt64, /* xCurrentTimeInt64 */
   32401   };
   32402 
   32403 #ifndef SQLITE_OMIT_WAL
   32404   /* get memory map allocation granularity */
   32405   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
   32406   GetSystemInfo(&winSysInfo);
   32407   assert(winSysInfo.dwAllocationGranularity > 0);
   32408 #endif
   32409 
   32410   sqlite3_vfs_register(&winVfs, 1);
   32411   return SQLITE_OK;
   32412 }
   32413 SQLITE_API int sqlite3_os_end(void){
   32414   return SQLITE_OK;
   32415 }
   32416 
   32417 #endif /* SQLITE_OS_WIN */
   32418 
   32419 /************** End of os_win.c **********************************************/
   32420 /************** Begin file bitvec.c ******************************************/
   32421 /*
   32422 ** 2008 February 16
   32423 **
   32424 ** The author disclaims copyright to this source code.  In place of
   32425 ** a legal notice, here is a blessing:
   32426 **
   32427 **    May you do good and not evil.
   32428 **    May you find forgiveness for yourself and forgive others.
   32429 **    May you share freely, never taking more than you give.
   32430 **
   32431 *************************************************************************
   32432 ** This file implements an object that represents a fixed-length
   32433 ** bitmap.  Bits are numbered starting with 1.
   32434 **
   32435 ** A bitmap is used to record which pages of a database file have been
   32436 ** journalled during a transaction, or which pages have the "dont-write"
   32437 ** property.  Usually only a few pages are meet either condition.
   32438 ** So the bitmap is usually sparse and has low cardinality.
   32439 ** But sometimes (for example when during a DROP of a large table) most
   32440 ** or all of the pages in a database can get journalled.  In those cases,
   32441 ** the bitmap becomes dense with high cardinality.  The algorithm needs
   32442 ** to handle both cases well.
   32443 **
   32444 ** The size of the bitmap is fixed when the object is created.
   32445 **
   32446 ** All bits are clear when the bitmap is created.  Individual bits
   32447 ** may be set or cleared one at a time.
   32448 **
   32449 ** Test operations are about 100 times more common that set operations.
   32450 ** Clear operations are exceedingly rare.  There are usually between
   32451 ** 5 and 500 set operations per Bitvec object, though the number of sets can
   32452 ** sometimes grow into tens of thousands or larger.  The size of the
   32453 ** Bitvec object is the number of pages in the database file at the
   32454 ** start of a transaction, and is thus usually less than a few thousand,
   32455 ** but can be as large as 2 billion for a really big database.
   32456 */
   32457 
   32458 /* Size of the Bitvec structure in bytes. */
   32459 #define BITVEC_SZ        512
   32460 
   32461 /* Round the union size down to the nearest pointer boundary, since that's how
   32462 ** it will be aligned within the Bitvec struct. */
   32463 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
   32464 
   32465 /* Type of the array "element" for the bitmap representation.
   32466 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
   32467 ** Setting this to the "natural word" size of your CPU may improve
   32468 ** performance. */
   32469 #define BITVEC_TELEM     u8
   32470 /* Size, in bits, of the bitmap element. */
   32471 #define BITVEC_SZELEM    8
   32472 /* Number of elements in a bitmap array. */
   32473 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
   32474 /* Number of bits in the bitmap array. */
   32475 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
   32476 
   32477 /* Number of u32 values in hash table. */
   32478 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
   32479 /* Maximum number of entries in hash table before
   32480 ** sub-dividing and re-hashing. */
   32481 #define BITVEC_MXHASH    (BITVEC_NINT/2)
   32482 /* Hashing function for the aHash representation.
   32483 ** Empirical testing showed that the *37 multiplier
   32484 ** (an arbitrary prime)in the hash function provided
   32485 ** no fewer collisions than the no-op *1. */
   32486 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
   32487 
   32488 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
   32489 
   32490 
   32491 /*
   32492 ** A bitmap is an instance of the following structure.
   32493 **
   32494 ** This bitmap records the existance of zero or more bits
   32495 ** with values between 1 and iSize, inclusive.
   32496 **
   32497 ** There are three possible representations of the bitmap.
   32498 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
   32499 ** bitmap.  The least significant bit is bit 1.
   32500 **
   32501 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
   32502 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
   32503 **
   32504 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
   32505 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
   32506 ** handles up to iDivisor separate values of i.  apSub[0] holds
   32507 ** values between 1 and iDivisor.  apSub[1] holds values between
   32508 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
   32509 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
   32510 ** to hold deal with values between 1 and iDivisor.
   32511 */
   32512 struct Bitvec {
   32513   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
   32514   u32 nSet;       /* Number of bits that are set - only valid for aHash
   32515                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
   32516                   ** this would be 125. */
   32517   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
   32518                   /* Should >=0 for apSub element. */
   32519                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
   32520                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
   32521   union {
   32522     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
   32523     u32 aHash[BITVEC_NINT];      /* Hash table representation */
   32524     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
   32525   } u;
   32526 };
   32527 
   32528 /*
   32529 ** Create a new bitmap object able to handle bits between 0 and iSize,
   32530 ** inclusive.  Return a pointer to the new object.  Return NULL if
   32531 ** malloc fails.
   32532 */
   32533 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
   32534   Bitvec *p;
   32535   assert( sizeof(*p)==BITVEC_SZ );
   32536   p = sqlite3MallocZero( sizeof(*p) );
   32537   if( p ){
   32538     p->iSize = iSize;
   32539   }
   32540   return p;
   32541 }
   32542 
   32543 /*
   32544 ** Check to see if the i-th bit is set.  Return true or false.
   32545 ** If p is NULL (if the bitmap has not been created) or if
   32546 ** i is out of range, then return false.
   32547 */
   32548 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
   32549   if( p==0 ) return 0;
   32550   if( i>p->iSize || i==0 ) return 0;
   32551   i--;
   32552   while( p->iDivisor ){
   32553     u32 bin = i/p->iDivisor;
   32554     i = i%p->iDivisor;
   32555     p = p->u.apSub[bin];
   32556     if (!p) {
   32557       return 0;
   32558     }
   32559   }
   32560   if( p->iSize<=BITVEC_NBIT ){
   32561     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
   32562   } else{
   32563     u32 h = BITVEC_HASH(i++);
   32564     while( p->u.aHash[h] ){
   32565       if( p->u.aHash[h]==i ) return 1;
   32566       h = (h+1) % BITVEC_NINT;
   32567     }
   32568     return 0;
   32569   }
   32570 }
   32571 
   32572 /*
   32573 ** Set the i-th bit.  Return 0 on success and an error code if
   32574 ** anything goes wrong.
   32575 **
   32576 ** This routine might cause sub-bitmaps to be allocated.  Failing
   32577 ** to get the memory needed to hold the sub-bitmap is the only
   32578 ** that can go wrong with an insert, assuming p and i are valid.
   32579 **
   32580 ** The calling function must ensure that p is a valid Bitvec object
   32581 ** and that the value for "i" is within range of the Bitvec object.
   32582 ** Otherwise the behavior is undefined.
   32583 */
   32584 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
   32585   u32 h;
   32586   if( p==0 ) return SQLITE_OK;
   32587   assert( i>0 );
   32588   assert( i<=p->iSize );
   32589   i--;
   32590   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
   32591     u32 bin = i/p->iDivisor;
   32592     i = i%p->iDivisor;
   32593     if( p->u.apSub[bin]==0 ){
   32594       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
   32595       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
   32596     }
   32597     p = p->u.apSub[bin];
   32598   }
   32599   if( p->iSize<=BITVEC_NBIT ){
   32600     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
   32601     return SQLITE_OK;
   32602   }
   32603   h = BITVEC_HASH(i++);
   32604   /* if there wasn't a hash collision, and this doesn't */
   32605   /* completely fill the hash, then just add it without */
   32606   /* worring about sub-dividing and re-hashing. */
   32607   if( !p->u.aHash[h] ){
   32608     if (p->nSet<(BITVEC_NINT-1)) {
   32609       goto bitvec_set_end;
   32610     } else {
   32611       goto bitvec_set_rehash;
   32612     }
   32613   }
   32614   /* there was a collision, check to see if it's already */
   32615   /* in hash, if not, try to find a spot for it */
   32616   do {
   32617     if( p->u.aHash[h]==i ) return SQLITE_OK;
   32618     h++;
   32619     if( h>=BITVEC_NINT ) h = 0;
   32620   } while( p->u.aHash[h] );
   32621   /* we didn't find it in the hash.  h points to the first */
   32622   /* available free spot. check to see if this is going to */
   32623   /* make our hash too "full".  */
   32624 bitvec_set_rehash:
   32625   if( p->nSet>=BITVEC_MXHASH ){
   32626     unsigned int j;
   32627     int rc;
   32628     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
   32629     if( aiValues==0 ){
   32630       return SQLITE_NOMEM;
   32631     }else{
   32632       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   32633       memset(p->u.apSub, 0, sizeof(p->u.apSub));
   32634       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
   32635       rc = sqlite3BitvecSet(p, i);
   32636       for(j=0; j<BITVEC_NINT; j++){
   32637         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
   32638       }
   32639       sqlite3StackFree(0, aiValues);
   32640       return rc;
   32641     }
   32642   }
   32643 bitvec_set_end:
   32644   p->nSet++;
   32645   p->u.aHash[h] = i;
   32646   return SQLITE_OK;
   32647 }
   32648 
   32649 /*
   32650 ** Clear the i-th bit.
   32651 **
   32652 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
   32653 ** that BitvecClear can use to rebuilt its hash table.
   32654 */
   32655 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
   32656   if( p==0 ) return;
   32657   assert( i>0 );
   32658   i--;
   32659   while( p->iDivisor ){
   32660     u32 bin = i/p->iDivisor;
   32661     i = i%p->iDivisor;
   32662     p = p->u.apSub[bin];
   32663     if (!p) {
   32664       return;
   32665     }
   32666   }
   32667   if( p->iSize<=BITVEC_NBIT ){
   32668     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
   32669   }else{
   32670     unsigned int j;
   32671     u32 *aiValues = pBuf;
   32672     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
   32673     memset(p->u.aHash, 0, sizeof(p->u.aHash));
   32674     p->nSet = 0;
   32675     for(j=0; j<BITVEC_NINT; j++){
   32676       if( aiValues[j] && aiValues[j]!=(i+1) ){
   32677         u32 h = BITVEC_HASH(aiValues[j]-1);
   32678         p->nSet++;
   32679         while( p->u.aHash[h] ){
   32680           h++;
   32681           if( h>=BITVEC_NINT ) h = 0;
   32682         }
   32683         p->u.aHash[h] = aiValues[j];
   32684       }
   32685     }
   32686   }
   32687 }
   32688 
   32689 /*
   32690 ** Destroy a bitmap object.  Reclaim all memory used.
   32691 */
   32692 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
   32693   if( p==0 ) return;
   32694   if( p->iDivisor ){
   32695     unsigned int i;
   32696     for(i=0; i<BITVEC_NPTR; i++){
   32697       sqlite3BitvecDestroy(p->u.apSub[i]);
   32698     }
   32699   }
   32700   sqlite3_free(p);
   32701 }
   32702 
   32703 /*
   32704 ** Return the value of the iSize parameter specified when Bitvec *p
   32705 ** was created.
   32706 */
   32707 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
   32708   return p->iSize;
   32709 }
   32710 
   32711 #ifndef SQLITE_OMIT_BUILTIN_TEST
   32712 /*
   32713 ** Let V[] be an array of unsigned characters sufficient to hold
   32714 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
   32715 ** Then the following macros can be used to set, clear, or test
   32716 ** individual bits within V.
   32717 */
   32718 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
   32719 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
   32720 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
   32721 
   32722 /*
   32723 ** This routine runs an extensive test of the Bitvec code.
   32724 **
   32725 ** The input is an array of integers that acts as a program
   32726 ** to test the Bitvec.  The integers are opcodes followed
   32727 ** by 0, 1, or 3 operands, depending on the opcode.  Another
   32728 ** opcode follows immediately after the last operand.
   32729 **
   32730 ** There are 6 opcodes numbered from 0 through 5.  0 is the
   32731 ** "halt" opcode and causes the test to end.
   32732 **
   32733 **    0          Halt and return the number of errors
   32734 **    1 N S X    Set N bits beginning with S and incrementing by X
   32735 **    2 N S X    Clear N bits beginning with S and incrementing by X
   32736 **    3 N        Set N randomly chosen bits
   32737 **    4 N        Clear N randomly chosen bits
   32738 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
   32739 **
   32740 ** The opcodes 1 through 4 perform set and clear operations are performed
   32741 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
   32742 ** Opcode 5 works on the linear array only, not on the Bitvec.
   32743 ** Opcode 5 is used to deliberately induce a fault in order to
   32744 ** confirm that error detection works.
   32745 **
   32746 ** At the conclusion of the test the linear array is compared
   32747 ** against the Bitvec object.  If there are any differences,
   32748 ** an error is returned.  If they are the same, zero is returned.
   32749 **
   32750 ** If a memory allocation error occurs, return -1.
   32751 */
   32752 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
   32753   Bitvec *pBitvec = 0;
   32754   unsigned char *pV = 0;
   32755   int rc = -1;
   32756   int i, nx, pc, op;
   32757   void *pTmpSpace;
   32758 
   32759   /* Allocate the Bitvec to be tested and a linear array of
   32760   ** bits to act as the reference */
   32761   pBitvec = sqlite3BitvecCreate( sz );
   32762   pV = sqlite3_malloc( (sz+7)/8 + 1 );
   32763   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
   32764   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
   32765   memset(pV, 0, (sz+7)/8 + 1);
   32766 
   32767   /* NULL pBitvec tests */
   32768   sqlite3BitvecSet(0, 1);
   32769   sqlite3BitvecClear(0, 1, pTmpSpace);
   32770 
   32771   /* Run the program */
   32772   pc = 0;
   32773   while( (op = aOp[pc])!=0 ){
   32774     switch( op ){
   32775       case 1:
   32776       case 2:
   32777       case 5: {
   32778         nx = 4;
   32779         i = aOp[pc+2] - 1;
   32780         aOp[pc+2] += aOp[pc+3];
   32781         break;
   32782       }
   32783       case 3:
   32784       case 4:
   32785       default: {
   32786         nx = 2;
   32787         sqlite3_randomness(sizeof(i), &i);
   32788         break;
   32789       }
   32790     }
   32791     if( (--aOp[pc+1]) > 0 ) nx = 0;
   32792     pc += nx;
   32793     i = (i & 0x7fffffff)%sz;
   32794     if( (op & 1)!=0 ){
   32795       SETBIT(pV, (i+1));
   32796       if( op!=5 ){
   32797         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
   32798       }
   32799     }else{
   32800       CLEARBIT(pV, (i+1));
   32801       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
   32802     }
   32803   }
   32804 
   32805   /* Test to make sure the linear array exactly matches the
   32806   ** Bitvec object.  Start with the assumption that they do
   32807   ** match (rc==0).  Change rc to non-zero if a discrepancy
   32808   ** is found.
   32809   */
   32810   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
   32811           + sqlite3BitvecTest(pBitvec, 0)
   32812           + (sqlite3BitvecSize(pBitvec) - sz);
   32813   for(i=1; i<=sz; i++){
   32814     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
   32815       rc = i;
   32816       break;
   32817     }
   32818   }
   32819 
   32820   /* Free allocated structure */
   32821 bitvec_end:
   32822   sqlite3_free(pTmpSpace);
   32823   sqlite3_free(pV);
   32824   sqlite3BitvecDestroy(pBitvec);
   32825   return rc;
   32826 }
   32827 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   32828 
   32829 /************** End of bitvec.c **********************************************/
   32830 /************** Begin file pcache.c ******************************************/
   32831 /*
   32832 ** 2008 August 05
   32833 **
   32834 ** The author disclaims copyright to this source code.  In place of
   32835 ** a legal notice, here is a blessing:
   32836 **
   32837 **    May you do good and not evil.
   32838 **    May you find forgiveness for yourself and forgive others.
   32839 **    May you share freely, never taking more than you give.
   32840 **
   32841 *************************************************************************
   32842 ** This file implements that page cache.
   32843 */
   32844 
   32845 /*
   32846 ** A complete page cache is an instance of this structure.
   32847 */
   32848 struct PCache {
   32849   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
   32850   PgHdr *pSynced;                     /* Last synced page in dirty page list */
   32851   int nRef;                           /* Number of referenced pages */
   32852   int nMax;                           /* Configured cache size */
   32853   int szPage;                         /* Size of every page in this cache */
   32854   int szExtra;                        /* Size of extra space for each page */
   32855   int bPurgeable;                     /* True if pages are on backing store */
   32856   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
   32857   void *pStress;                      /* Argument to xStress */
   32858   sqlite3_pcache *pCache;             /* Pluggable cache module */
   32859   PgHdr *pPage1;                      /* Reference to page 1 */
   32860 };
   32861 
   32862 /*
   32863 ** Some of the assert() macros in this code are too expensive to run
   32864 ** even during normal debugging.  Use them only rarely on long-running
   32865 ** tests.  Enable the expensive asserts using the
   32866 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
   32867 */
   32868 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   32869 # define expensive_assert(X)  assert(X)
   32870 #else
   32871 # define expensive_assert(X)
   32872 #endif
   32873 
   32874 /********************************** Linked List Management ********************/
   32875 
   32876 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
   32877 /*
   32878 ** Check that the pCache->pSynced variable is set correctly. If it
   32879 ** is not, either fail an assert or return zero. Otherwise, return
   32880 ** non-zero. This is only used in debugging builds, as follows:
   32881 **
   32882 **   expensive_assert( pcacheCheckSynced(pCache) );
   32883 */
   32884 static int pcacheCheckSynced(PCache *pCache){
   32885   PgHdr *p;
   32886   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
   32887     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
   32888   }
   32889   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
   32890 }
   32891 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
   32892 
   32893 /*
   32894 ** Remove page pPage from the list of dirty pages.
   32895 */
   32896 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
   32897   PCache *p = pPage->pCache;
   32898 
   32899   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
   32900   assert( pPage->pDirtyPrev || pPage==p->pDirty );
   32901 
   32902   /* Update the PCache1.pSynced variable if necessary. */
   32903   if( p->pSynced==pPage ){
   32904     PgHdr *pSynced = pPage->pDirtyPrev;
   32905     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
   32906       pSynced = pSynced->pDirtyPrev;
   32907     }
   32908     p->pSynced = pSynced;
   32909   }
   32910 
   32911   if( pPage->pDirtyNext ){
   32912     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
   32913   }else{
   32914     assert( pPage==p->pDirtyTail );
   32915     p->pDirtyTail = pPage->pDirtyPrev;
   32916   }
   32917   if( pPage->pDirtyPrev ){
   32918     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
   32919   }else{
   32920     assert( pPage==p->pDirty );
   32921     p->pDirty = pPage->pDirtyNext;
   32922   }
   32923   pPage->pDirtyNext = 0;
   32924   pPage->pDirtyPrev = 0;
   32925 
   32926   expensive_assert( pcacheCheckSynced(p) );
   32927 }
   32928 
   32929 /*
   32930 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
   32931 ** pPage).
   32932 */
   32933 static void pcacheAddToDirtyList(PgHdr *pPage){
   32934   PCache *p = pPage->pCache;
   32935 
   32936   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
   32937 
   32938   pPage->pDirtyNext = p->pDirty;
   32939   if( pPage->pDirtyNext ){
   32940     assert( pPage->pDirtyNext->pDirtyPrev==0 );
   32941     pPage->pDirtyNext->pDirtyPrev = pPage;
   32942   }
   32943   p->pDirty = pPage;
   32944   if( !p->pDirtyTail ){
   32945     p->pDirtyTail = pPage;
   32946   }
   32947   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
   32948     p->pSynced = pPage;
   32949   }
   32950   expensive_assert( pcacheCheckSynced(p) );
   32951 }
   32952 
   32953 /*
   32954 ** Wrapper around the pluggable caches xUnpin method. If the cache is
   32955 ** being used for an in-memory database, this function is a no-op.
   32956 */
   32957 static void pcacheUnpin(PgHdr *p){
   32958   PCache *pCache = p->pCache;
   32959   if( pCache->bPurgeable ){
   32960     if( p->pgno==1 ){
   32961       pCache->pPage1 = 0;
   32962     }
   32963     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
   32964   }
   32965 }
   32966 
   32967 /*************************************************** General Interfaces ******
   32968 **
   32969 ** Initialize and shutdown the page cache subsystem. Neither of these
   32970 ** functions are threadsafe.
   32971 */
   32972 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
   32973   if( sqlite3GlobalConfig.pcache.xInit==0 ){
   32974     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   32975     ** built-in default page cache is used instead of the application defined
   32976     ** page cache. */
   32977     sqlite3PCacheSetDefault();
   32978   }
   32979   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
   32980 }
   32981 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
   32982   if( sqlite3GlobalConfig.pcache.xShutdown ){
   32983     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   32984     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
   32985   }
   32986 }
   32987 
   32988 /*
   32989 ** Return the size in bytes of a PCache object.
   32990 */
   32991 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
   32992 
   32993 /*
   32994 ** Create a new PCache object. Storage space to hold the object
   32995 ** has already been allocated and is passed in as the p pointer.
   32996 ** The caller discovers how much space needs to be allocated by
   32997 ** calling sqlite3PcacheSize().
   32998 */
   32999 SQLITE_PRIVATE void sqlite3PcacheOpen(
   33000   int szPage,                  /* Size of every page */
   33001   int szExtra,                 /* Extra space associated with each page */
   33002   int bPurgeable,              /* True if pages are on backing store */
   33003   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
   33004   void *pStress,               /* Argument to xStress */
   33005   PCache *p                    /* Preallocated space for the PCache */
   33006 ){
   33007   memset(p, 0, sizeof(PCache));
   33008   p->szPage = szPage;
   33009   p->szExtra = szExtra;
   33010   p->bPurgeable = bPurgeable;
   33011   p->xStress = xStress;
   33012   p->pStress = pStress;
   33013   p->nMax = 100;
   33014 }
   33015 
   33016 /*
   33017 ** Change the page size for PCache object. The caller must ensure that there
   33018 ** are no outstanding page references when this function is called.
   33019 */
   33020 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   33021   assert( pCache->nRef==0 && pCache->pDirty==0 );
   33022   if( pCache->pCache ){
   33023     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
   33024     pCache->pCache = 0;
   33025     pCache->pPage1 = 0;
   33026   }
   33027   pCache->szPage = szPage;
   33028 }
   33029 
   33030 /*
   33031 ** Try to obtain a page from the cache.
   33032 */
   33033 SQLITE_PRIVATE int sqlite3PcacheFetch(
   33034   PCache *pCache,       /* Obtain the page from this cache */
   33035   Pgno pgno,            /* Page number to obtain */
   33036   int createFlag,       /* If true, create page if it does not exist already */
   33037   PgHdr **ppPage        /* Write the page here */
   33038 ){
   33039   PgHdr *pPage = 0;
   33040   int eCreate;
   33041 
   33042   assert( pCache!=0 );
   33043   assert( createFlag==1 || createFlag==0 );
   33044   assert( pgno>0 );
   33045 
   33046   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   33047   ** allocate it now.
   33048   */
   33049   if( !pCache->pCache && createFlag ){
   33050     sqlite3_pcache *p;
   33051     int nByte;
   33052     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
   33053     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
   33054     if( !p ){
   33055       return SQLITE_NOMEM;
   33056     }
   33057     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
   33058     pCache->pCache = p;
   33059   }
   33060 
   33061   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
   33062   if( pCache->pCache ){
   33063     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
   33064   }
   33065 
   33066   if( !pPage && eCreate==1 ){
   33067     PgHdr *pPg;
   33068 
   33069     /* Find a dirty page to write-out and recycle. First try to find a
   33070     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
   33071     ** cleared), but if that is not possible settle for any other
   33072     ** unreferenced dirty page.
   33073     */
   33074     expensive_assert( pcacheCheckSynced(pCache) );
   33075     for(pPg=pCache->pSynced;
   33076         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
   33077         pPg=pPg->pDirtyPrev
   33078     );
   33079     pCache->pSynced = pPg;
   33080     if( !pPg ){
   33081       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
   33082     }
   33083     if( pPg ){
   33084       int rc;
   33085       rc = pCache->xStress(pCache->pStress, pPg);
   33086       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   33087         return rc;
   33088       }
   33089     }
   33090 
   33091     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
   33092   }
   33093 
   33094   if( pPage ){
   33095     if( !pPage->pData ){
   33096       memset(pPage, 0, sizeof(PgHdr));
   33097       pPage->pData = (void *)&pPage[1];
   33098       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
   33099       memset(pPage->pExtra, 0, pCache->szExtra);
   33100       pPage->pCache = pCache;
   33101       pPage->pgno = pgno;
   33102     }
   33103     assert( pPage->pCache==pCache );
   33104     assert( pPage->pgno==pgno );
   33105     assert( pPage->pData==(void *)&pPage[1] );
   33106     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
   33107 
   33108     if( 0==pPage->nRef ){
   33109       pCache->nRef++;
   33110     }
   33111     pPage->nRef++;
   33112     if( pgno==1 ){
   33113       pCache->pPage1 = pPage;
   33114     }
   33115   }
   33116   *ppPage = pPage;
   33117   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   33118 }
   33119 
   33120 /*
   33121 ** Decrement the reference count on a page. If the page is clean and the
   33122 ** reference count drops to 0, then it is made elible for recycling.
   33123 */
   33124 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
   33125   assert( p->nRef>0 );
   33126   p->nRef--;
   33127   if( p->nRef==0 ){
   33128     PCache *pCache = p->pCache;
   33129     pCache->nRef--;
   33130     if( (p->flags&PGHDR_DIRTY)==0 ){
   33131       pcacheUnpin(p);
   33132     }else{
   33133       /* Move the page to the head of the dirty list. */
   33134       pcacheRemoveFromDirtyList(p);
   33135       pcacheAddToDirtyList(p);
   33136     }
   33137   }
   33138 }
   33139 
   33140 /*
   33141 ** Increase the reference count of a supplied page by 1.
   33142 */
   33143 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
   33144   assert(p->nRef>0);
   33145   p->nRef++;
   33146 }
   33147 
   33148 /*
   33149 ** Drop a page from the cache. There must be exactly one reference to the
   33150 ** page. This function deletes that reference, so after it returns the
   33151 ** page pointed to by p is invalid.
   33152 */
   33153 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
   33154   PCache *pCache;
   33155   assert( p->nRef==1 );
   33156   if( p->flags&PGHDR_DIRTY ){
   33157     pcacheRemoveFromDirtyList(p);
   33158   }
   33159   pCache = p->pCache;
   33160   pCache->nRef--;
   33161   if( p->pgno==1 ){
   33162     pCache->pPage1 = 0;
   33163   }
   33164   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
   33165 }
   33166 
   33167 /*
   33168 ** Make sure the page is marked as dirty. If it isn't dirty already,
   33169 ** make it so.
   33170 */
   33171 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
   33172   p->flags &= ~PGHDR_DONT_WRITE;
   33173   assert( p->nRef>0 );
   33174   if( 0==(p->flags & PGHDR_DIRTY) ){
   33175     p->flags |= PGHDR_DIRTY;
   33176     pcacheAddToDirtyList( p);
   33177   }
   33178 }
   33179 
   33180 /*
   33181 ** Make sure the page is marked as clean. If it isn't clean already,
   33182 ** make it so.
   33183 */
   33184 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
   33185   if( (p->flags & PGHDR_DIRTY) ){
   33186     pcacheRemoveFromDirtyList(p);
   33187     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
   33188     if( p->nRef==0 ){
   33189       pcacheUnpin(p);
   33190     }
   33191   }
   33192 }
   33193 
   33194 /*
   33195 ** Make every page in the cache clean.
   33196 */
   33197 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
   33198   PgHdr *p;
   33199   while( (p = pCache->pDirty)!=0 ){
   33200     sqlite3PcacheMakeClean(p);
   33201   }
   33202 }
   33203 
   33204 /*
   33205 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
   33206 */
   33207 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
   33208   PgHdr *p;
   33209   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   33210     p->flags &= ~PGHDR_NEED_SYNC;
   33211   }
   33212   pCache->pSynced = pCache->pDirtyTail;
   33213 }
   33214 
   33215 /*
   33216 ** Change the page number of page p to newPgno.
   33217 */
   33218 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   33219   PCache *pCache = p->pCache;
   33220   assert( p->nRef>0 );
   33221   assert( newPgno>0 );
   33222   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
   33223   p->pgno = newPgno;
   33224   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   33225     pcacheRemoveFromDirtyList(p);
   33226     pcacheAddToDirtyList(p);
   33227   }
   33228 }
   33229 
   33230 /*
   33231 ** Drop every cache entry whose page number is greater than "pgno". The
   33232 ** caller must ensure that there are no outstanding references to any pages
   33233 ** other than page 1 with a page number greater than pgno.
   33234 **
   33235 ** If there is a reference to page 1 and the pgno parameter passed to this
   33236 ** function is 0, then the data area associated with page 1 is zeroed, but
   33237 ** the page object is not dropped.
   33238 */
   33239 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
   33240   if( pCache->pCache ){
   33241     PgHdr *p;
   33242     PgHdr *pNext;
   33243     for(p=pCache->pDirty; p; p=pNext){
   33244       pNext = p->pDirtyNext;
   33245       /* This routine never gets call with a positive pgno except right
   33246       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
   33247       ** it must be that pgno==0.
   33248       */
   33249       assert( p->pgno>0 );
   33250       if( ALWAYS(p->pgno>pgno) ){
   33251         assert( p->flags&PGHDR_DIRTY );
   33252         sqlite3PcacheMakeClean(p);
   33253       }
   33254     }
   33255     if( pgno==0 && pCache->pPage1 ){
   33256       memset(pCache->pPage1->pData, 0, pCache->szPage);
   33257       pgno = 1;
   33258     }
   33259     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
   33260   }
   33261 }
   33262 
   33263 /*
   33264 ** Close a cache.
   33265 */
   33266 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   33267   if( pCache->pCache ){
   33268     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
   33269   }
   33270 }
   33271 
   33272 /*
   33273 ** Discard the contents of the cache.
   33274 */
   33275 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
   33276   sqlite3PcacheTruncate(pCache, 0);
   33277 }
   33278 
   33279 /*
   33280 ** Merge two lists of pages connected by pDirty and in pgno order.
   33281 ** Do not both fixing the pDirtyPrev pointers.
   33282 */
   33283 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
   33284   PgHdr result, *pTail;
   33285   pTail = &result;
   33286   while( pA && pB ){
   33287     if( pA->pgno<pB->pgno ){
   33288       pTail->pDirty = pA;
   33289       pTail = pA;
   33290       pA = pA->pDirty;
   33291     }else{
   33292       pTail->pDirty = pB;
   33293       pTail = pB;
   33294       pB = pB->pDirty;
   33295     }
   33296   }
   33297   if( pA ){
   33298     pTail->pDirty = pA;
   33299   }else if( pB ){
   33300     pTail->pDirty = pB;
   33301   }else{
   33302     pTail->pDirty = 0;
   33303   }
   33304   return result.pDirty;
   33305 }
   33306 
   33307 /*
   33308 ** Sort the list of pages in accending order by pgno.  Pages are
   33309 ** connected by pDirty pointers.  The pDirtyPrev pointers are
   33310 ** corrupted by this sort.
   33311 **
   33312 ** Since there cannot be more than 2^31 distinct pages in a database,
   33313 ** there cannot be more than 31 buckets required by the merge sorter.
   33314 ** One extra bucket is added to catch overflow in case something
   33315 ** ever changes to make the previous sentence incorrect.
   33316 */
   33317 #define N_SORT_BUCKET  32
   33318 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
   33319   PgHdr *a[N_SORT_BUCKET], *p;
   33320   int i;
   33321   memset(a, 0, sizeof(a));
   33322   while( pIn ){
   33323     p = pIn;
   33324     pIn = p->pDirty;
   33325     p->pDirty = 0;
   33326     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
   33327       if( a[i]==0 ){
   33328         a[i] = p;
   33329         break;
   33330       }else{
   33331         p = pcacheMergeDirtyList(a[i], p);
   33332         a[i] = 0;
   33333       }
   33334     }
   33335     if( NEVER(i==N_SORT_BUCKET-1) ){
   33336       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
   33337       ** the input list.  But that is impossible.
   33338       */
   33339       a[i] = pcacheMergeDirtyList(a[i], p);
   33340     }
   33341   }
   33342   p = a[0];
   33343   for(i=1; i<N_SORT_BUCKET; i++){
   33344     p = pcacheMergeDirtyList(p, a[i]);
   33345   }
   33346   return p;
   33347 }
   33348 
   33349 /*
   33350 ** Return a list of all dirty pages in the cache, sorted by page number.
   33351 */
   33352 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   33353   PgHdr *p;
   33354   for(p=pCache->pDirty; p; p=p->pDirtyNext){
   33355     p->pDirty = p->pDirtyNext;
   33356   }
   33357   return pcacheSortDirtyList(pCache->pDirty);
   33358 }
   33359 
   33360 /*
   33361 ** Return the total number of referenced pages held by the cache.
   33362 */
   33363 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
   33364   return pCache->nRef;
   33365 }
   33366 
   33367 /*
   33368 ** Return the number of references to the page supplied as an argument.
   33369 */
   33370 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   33371   return p->nRef;
   33372 }
   33373 
   33374 /*
   33375 ** Return the total number of pages in the cache.
   33376 */
   33377 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
   33378   int nPage = 0;
   33379   if( pCache->pCache ){
   33380     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
   33381   }
   33382   return nPage;
   33383 }
   33384 
   33385 #ifdef SQLITE_TEST
   33386 /*
   33387 ** Get the suggested cache-size value.
   33388 */
   33389 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
   33390   return pCache->nMax;
   33391 }
   33392 #endif
   33393 
   33394 /*
   33395 ** Set the suggested cache-size value.
   33396 */
   33397 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   33398   pCache->nMax = mxPage;
   33399   if( pCache->pCache ){
   33400     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
   33401   }
   33402 }
   33403 
   33404 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   33405 /*
   33406 ** For all dirty pages currently in the cache, invoke the specified
   33407 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
   33408 ** defined.
   33409 */
   33410 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
   33411   PgHdr *pDirty;
   33412   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
   33413     xIter(pDirty);
   33414   }
   33415 }
   33416 #endif
   33417 
   33418 /************** End of pcache.c **********************************************/
   33419 /************** Begin file pcache1.c *****************************************/
   33420 /*
   33421 ** 2008 November 05
   33422 **
   33423 ** The author disclaims copyright to this source code.  In place of
   33424 ** a legal notice, here is a blessing:
   33425 **
   33426 **    May you do good and not evil.
   33427 **    May you find forgiveness for yourself and forgive others.
   33428 **    May you share freely, never taking more than you give.
   33429 **
   33430 *************************************************************************
   33431 **
   33432 ** This file implements the default page cache implementation (the
   33433 ** sqlite3_pcache interface). It also contains part of the implementation
   33434 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
   33435 ** If the default page cache implementation is overriden, then neither of
   33436 ** these two features are available.
   33437 */
   33438 
   33439 
   33440 typedef struct PCache1 PCache1;
   33441 typedef struct PgHdr1 PgHdr1;
   33442 typedef struct PgFreeslot PgFreeslot;
   33443 
   33444 /* Each page cache is an instance of the following object.  Every
   33445 ** open database file (including each in-memory database and each
   33446 ** temporary or transient database) has a single page cache which
   33447 ** is an instance of this object.
   33448 **
   33449 ** Pointers to structures of this type are cast and returned as
   33450 ** opaque sqlite3_pcache* handles.
   33451 */
   33452 struct PCache1 {
   33453   /* Cache configuration parameters. Page size (szPage) and the purgeable
   33454   ** flag (bPurgeable) are set when the cache is created. nMax may be
   33455   ** modified at any time by a call to the pcache1CacheSize() method.
   33456   ** The global mutex must be held when accessing nMax.
   33457   */
   33458   int szPage;                         /* Size of allocated pages in bytes */
   33459   int bPurgeable;                     /* True if cache is purgeable */
   33460   unsigned int nMin;                  /* Minimum number of pages reserved */
   33461   unsigned int nMax;                  /* Configured "cache_size" value */
   33462 
   33463   /* Hash table of all pages. The following variables may only be accessed
   33464   ** when the accessor is holding the global mutex (see pcache1EnterMutex()
   33465   ** and pcache1LeaveMutex()).
   33466   */
   33467   unsigned int nRecyclable;           /* Number of pages in the LRU list */
   33468   unsigned int nPage;                 /* Total number of pages in apHash */
   33469   unsigned int nHash;                 /* Number of slots in apHash[] */
   33470   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
   33471 
   33472   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
   33473 };
   33474 
   33475 /*
   33476 ** Each cache entry is represented by an instance of the following
   33477 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
   33478 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
   33479 ** macro below).
   33480 */
   33481 struct PgHdr1 {
   33482   unsigned int iKey;             /* Key value (page number) */
   33483   PgHdr1 *pNext;                 /* Next in hash table chain */
   33484   PCache1 *pCache;               /* Cache that currently owns this page */
   33485   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   33486   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   33487 };
   33488 
   33489 /*
   33490 ** Free slots in the allocator used to divide up the buffer provided using
   33491 ** the SQLITE_CONFIG_PAGECACHE mechanism.
   33492 */
   33493 struct PgFreeslot {
   33494   PgFreeslot *pNext;  /* Next free slot */
   33495 };
   33496 
   33497 /*
   33498 ** Global data used by this cache.
   33499 */
   33500 static SQLITE_WSD struct PCacheGlobal {
   33501   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
   33502 
   33503   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
   33504   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
   33505   int nCurrentPage;                   /* Number of purgeable pages allocated */
   33506   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
   33507 
   33508   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
   33509   int szSlot;                         /* Size of each free slot */
   33510   int nSlot;                          /* The number of pcache slots */
   33511   int nFreeSlot;                      /* Number of unused pcache slots */
   33512   int nReserve;                       /* Try to keep nFreeSlot above this */
   33513   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
   33514   PgFreeslot *pFree;                  /* Free page blocks */
   33515   int isInit;                         /* True if initialized */
   33516 } pcache1_g;
   33517 
   33518 /*
   33519 ** All code in this file should access the global structure above via the
   33520 ** alias "pcache1". This ensures that the WSD emulation is used when
   33521 ** compiling for systems that do not support real WSD.
   33522 */
   33523 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   33524 
   33525 /*
   33526 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
   33527 ** bytes of data are located directly before it in memory (i.e. the total
   33528 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
   33529 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
   33530 ** an argument and returns a pointer to the associated block of szPage
   33531 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
   33532 ** a pointer to a block of szPage bytes of data and the return value is
   33533 ** a pointer to the associated PgHdr1 structure.
   33534 **
   33535 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
   33536 */
   33537 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
   33538 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
   33539 
   33540 /*
   33541 ** Macros to enter and leave the global LRU mutex.
   33542 */
   33543 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
   33544 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
   33545 
   33546 /******************************************************************************/
   33547 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
   33548 
   33549 /*
   33550 ** This function is called during initialization if a static buffer is
   33551 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
   33552 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
   33553 ** enough to contain 'n' buffers of 'sz' bytes each.
   33554 */
   33555 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
   33556   if( pcache1.isInit ){
   33557     PgFreeslot *p;
   33558     sz = ROUNDDOWN8(sz);
   33559     pcache1.szSlot = sz;
   33560     pcache1.nSlot = pcache1.nFreeSlot = n;
   33561     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
   33562     pcache1.pStart = pBuf;
   33563     pcache1.pFree = 0;
   33564     while( n-- ){
   33565       p = (PgFreeslot*)pBuf;
   33566       p->pNext = pcache1.pFree;
   33567       pcache1.pFree = p;
   33568       pBuf = (void*)&((char*)pBuf)[sz];
   33569     }
   33570     pcache1.pEnd = pBuf;
   33571   }
   33572 }
   33573 
   33574 /*
   33575 ** Malloc function used within this file to allocate space from the buffer
   33576 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
   33577 ** such buffer exists or there is no space left in it, this function falls
   33578 ** back to sqlite3Malloc().
   33579 */
   33580 static void *pcache1Alloc(int nByte){
   33581   void *p;
   33582   assert( sqlite3_mutex_held(pcache1.mutex) );
   33583   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
   33584   if( nByte<=pcache1.szSlot && pcache1.pFree ){
   33585     assert( pcache1.isInit );
   33586     p = (PgHdr1 *)pcache1.pFree;
   33587     pcache1.pFree = pcache1.pFree->pNext;
   33588     pcache1.nFreeSlot--;
   33589     assert( pcache1.nFreeSlot>=0 );
   33590     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
   33591   }else{
   33592 
   33593     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
   33594     ** global pcache mutex and unlock the pager-cache object pCache. This is
   33595     ** so that if the attempt to allocate a new buffer causes the the
   33596     ** configured soft-heap-limit to be breached, it will be possible to
   33597     ** reclaim memory from this pager-cache.
   33598     */
   33599     pcache1LeaveMutex();
   33600     p = sqlite3Malloc(nByte);
   33601     pcache1EnterMutex();
   33602     if( p ){
   33603       int sz = sqlite3MallocSize(p);
   33604       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
   33605     }
   33606     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   33607   }
   33608   return p;
   33609 }
   33610 
   33611 /*
   33612 ** Free an allocated buffer obtained from pcache1Alloc().
   33613 */
   33614 static void pcache1Free(void *p){
   33615   assert( sqlite3_mutex_held(pcache1.mutex) );
   33616   if( p==0 ) return;
   33617   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   33618     PgFreeslot *pSlot;
   33619     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   33620     pSlot = (PgFreeslot*)p;
   33621     pSlot->pNext = pcache1.pFree;
   33622     pcache1.pFree = pSlot;
   33623     pcache1.nFreeSlot++;
   33624     assert( pcache1.nFreeSlot<=pcache1.nSlot );
   33625   }else{
   33626     int iSize;
   33627     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   33628     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   33629     iSize = sqlite3MallocSize(p);
   33630     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
   33631     sqlite3_free(p);
   33632   }
   33633 }
   33634 
   33635 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   33636 /*
   33637 ** Return the size of a pcache allocation
   33638 */
   33639 static int pcache1MemSize(void *p){
   33640   assert( sqlite3_mutex_held(pcache1.mutex) );
   33641   if( p>=pcache1.pStart && p<pcache1.pEnd ){
   33642     return pcache1.szSlot;
   33643   }else{
   33644     int iSize;
   33645     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   33646     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   33647     iSize = sqlite3MallocSize(p);
   33648     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
   33649     return iSize;
   33650   }
   33651 }
   33652 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   33653 
   33654 /*
   33655 ** Allocate a new page object initially associated with cache pCache.
   33656 */
   33657 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   33658   int nByte = sizeof(PgHdr1) + pCache->szPage;
   33659   void *pPg = pcache1Alloc(nByte);
   33660   PgHdr1 *p;
   33661   if( pPg ){
   33662     p = PAGE_TO_PGHDR1(pCache, pPg);
   33663     if( pCache->bPurgeable ){
   33664       pcache1.nCurrentPage++;
   33665     }
   33666   }else{
   33667     p = 0;
   33668   }
   33669   return p;
   33670 }
   33671 
   33672 /*
   33673 ** Free a page object allocated by pcache1AllocPage().
   33674 **
   33675 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   33676 ** that the current implementation happens to never call this routine
   33677 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   33678 */
   33679 static void pcache1FreePage(PgHdr1 *p){
   33680   if( ALWAYS(p) ){
   33681     if( p->pCache->bPurgeable ){
   33682       pcache1.nCurrentPage--;
   33683     }
   33684     pcache1Free(PGHDR1_TO_PAGE(p));
   33685   }
   33686 }
   33687 
   33688 /*
   33689 ** Malloc function used by SQLite to obtain space from the buffer configured
   33690 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
   33691 ** exists, this function falls back to sqlite3Malloc().
   33692 */
   33693 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
   33694   void *p;
   33695   pcache1EnterMutex();
   33696   p = pcache1Alloc(sz);
   33697   pcache1LeaveMutex();
   33698   return p;
   33699 }
   33700 
   33701 /*
   33702 ** Free an allocated buffer obtained from sqlite3PageMalloc().
   33703 */
   33704 SQLITE_PRIVATE void sqlite3PageFree(void *p){
   33705   pcache1EnterMutex();
   33706   pcache1Free(p);
   33707   pcache1LeaveMutex();
   33708 }
   33709 
   33710 
   33711 /*
   33712 ** Return true if it desirable to avoid allocating a new page cache
   33713 ** entry.
   33714 **
   33715 ** If memory was allocated specifically to the page cache using
   33716 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
   33717 ** it is desirable to avoid allocating a new page cache entry because
   33718 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
   33719 ** for all page cache needs and we should not need to spill the
   33720 ** allocation onto the heap.
   33721 **
   33722 ** Or, the heap is used for all page cache memory put the heap is
   33723 ** under memory pressure, then again it is desirable to avoid
   33724 ** allocating a new page cache entry in order to avoid stressing
   33725 ** the heap even further.
   33726 */
   33727 static int pcache1UnderMemoryPressure(PCache1 *pCache){
   33728   assert( sqlite3_mutex_held(pcache1.mutex) );
   33729   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
   33730     return pcache1.nFreeSlot<pcache1.nReserve;
   33731   }else{
   33732     return sqlite3HeapNearlyFull();
   33733   }
   33734 }
   33735 
   33736 /******************************************************************************/
   33737 /******** General Implementation Functions ************************************/
   33738 
   33739 /*
   33740 ** This function is used to resize the hash table used by the cache passed
   33741 ** as the first argument.
   33742 **
   33743 ** The global mutex must be held when this function is called.
   33744 */
   33745 static int pcache1ResizeHash(PCache1 *p){
   33746   PgHdr1 **apNew;
   33747   unsigned int nNew;
   33748   unsigned int i;
   33749 
   33750   assert( sqlite3_mutex_held(pcache1.mutex) );
   33751 
   33752   nNew = p->nHash*2;
   33753   if( nNew<256 ){
   33754     nNew = 256;
   33755   }
   33756 
   33757   pcache1LeaveMutex();
   33758   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
   33759   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
   33760   if( p->nHash ){ sqlite3EndBenignMalloc(); }
   33761   pcache1EnterMutex();
   33762   if( apNew ){
   33763     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
   33764     for(i=0; i<p->nHash; i++){
   33765       PgHdr1 *pPage;
   33766       PgHdr1 *pNext = p->apHash[i];
   33767       while( (pPage = pNext)!=0 ){
   33768         unsigned int h = pPage->iKey % nNew;
   33769         pNext = pPage->pNext;
   33770         pPage->pNext = apNew[h];
   33771         apNew[h] = pPage;
   33772       }
   33773     }
   33774     sqlite3_free(p->apHash);
   33775     p->apHash = apNew;
   33776     p->nHash = nNew;
   33777   }
   33778 
   33779   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
   33780 }
   33781 
   33782 /*
   33783 ** This function is used internally to remove the page pPage from the
   33784 ** global LRU list, if is part of it. If pPage is not part of the global
   33785 ** LRU list, then this function is a no-op.
   33786 **
   33787 ** The global mutex must be held when this function is called.
   33788 */
   33789 static void pcache1PinPage(PgHdr1 *pPage){
   33790   assert( sqlite3_mutex_held(pcache1.mutex) );
   33791   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
   33792     if( pPage->pLruPrev ){
   33793       pPage->pLruPrev->pLruNext = pPage->pLruNext;
   33794     }
   33795     if( pPage->pLruNext ){
   33796       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
   33797     }
   33798     if( pcache1.pLruHead==pPage ){
   33799       pcache1.pLruHead = pPage->pLruNext;
   33800     }
   33801     if( pcache1.pLruTail==pPage ){
   33802       pcache1.pLruTail = pPage->pLruPrev;
   33803     }
   33804     pPage->pLruNext = 0;
   33805     pPage->pLruPrev = 0;
   33806     pPage->pCache->nRecyclable--;
   33807   }
   33808 }
   33809 
   33810 
   33811 /*
   33812 ** Remove the page supplied as an argument from the hash table
   33813 ** (PCache1.apHash structure) that it is currently stored in.
   33814 **
   33815 ** The global mutex must be held when this function is called.
   33816 */
   33817 static void pcache1RemoveFromHash(PgHdr1 *pPage){
   33818   unsigned int h;
   33819   PCache1 *pCache = pPage->pCache;
   33820   PgHdr1 **pp;
   33821 
   33822   h = pPage->iKey % pCache->nHash;
   33823   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
   33824   *pp = (*pp)->pNext;
   33825 
   33826   pCache->nPage--;
   33827 }
   33828 
   33829 /*
   33830 ** If there are currently more than pcache.nMaxPage pages allocated, try
   33831 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
   33832 */
   33833 static void pcache1EnforceMaxPage(void){
   33834   assert( sqlite3_mutex_held(pcache1.mutex) );
   33835   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
   33836     PgHdr1 *p = pcache1.pLruTail;
   33837     pcache1PinPage(p);
   33838     pcache1RemoveFromHash(p);
   33839     pcache1FreePage(p);
   33840   }
   33841 }
   33842 
   33843 /*
   33844 ** Discard all pages from cache pCache with a page number (key value)
   33845 ** greater than or equal to iLimit. Any pinned pages that meet this
   33846 ** criteria are unpinned before they are discarded.
   33847 **
   33848 ** The global mutex must be held when this function is called.
   33849 */
   33850 static void pcache1TruncateUnsafe(
   33851   PCache1 *pCache,
   33852   unsigned int iLimit
   33853 ){
   33854   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
   33855   unsigned int h;
   33856   assert( sqlite3_mutex_held(pcache1.mutex) );
   33857   for(h=0; h<pCache->nHash; h++){
   33858     PgHdr1 **pp = &pCache->apHash[h];
   33859     PgHdr1 *pPage;
   33860     while( (pPage = *pp)!=0 ){
   33861       if( pPage->iKey>=iLimit ){
   33862         pCache->nPage--;
   33863         *pp = pPage->pNext;
   33864         pcache1PinPage(pPage);
   33865         pcache1FreePage(pPage);
   33866       }else{
   33867         pp = &pPage->pNext;
   33868         TESTONLY( nPage++; )
   33869       }
   33870     }
   33871   }
   33872   assert( pCache->nPage==nPage );
   33873 }
   33874 
   33875 /******************************************************************************/
   33876 /******** sqlite3_pcache Methods **********************************************/
   33877 
   33878 /*
   33879 ** Implementation of the sqlite3_pcache.xInit method.
   33880 */
   33881 static int pcache1Init(void *NotUsed){
   33882   UNUSED_PARAMETER(NotUsed);
   33883   assert( pcache1.isInit==0 );
   33884   memset(&pcache1, 0, sizeof(pcache1));
   33885   if( sqlite3GlobalConfig.bCoreMutex ){
   33886     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
   33887   }
   33888   pcache1.isInit = 1;
   33889   return SQLITE_OK;
   33890 }
   33891 
   33892 /*
   33893 ** Implementation of the sqlite3_pcache.xShutdown method.
   33894 ** Note that the static mutex allocated in xInit does
   33895 ** not need to be freed.
   33896 */
   33897 static void pcache1Shutdown(void *NotUsed){
   33898   UNUSED_PARAMETER(NotUsed);
   33899   assert( pcache1.isInit!=0 );
   33900   memset(&pcache1, 0, sizeof(pcache1));
   33901 }
   33902 
   33903 /*
   33904 ** Implementation of the sqlite3_pcache.xCreate method.
   33905 **
   33906 ** Allocate a new cache.
   33907 */
   33908 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
   33909   PCache1 *pCache;
   33910 
   33911   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
   33912   if( pCache ){
   33913     memset(pCache, 0, sizeof(PCache1));
   33914     pCache->szPage = szPage;
   33915     pCache->bPurgeable = (bPurgeable ? 1 : 0);
   33916     if( bPurgeable ){
   33917       pCache->nMin = 10;
   33918       pcache1EnterMutex();
   33919       pcache1.nMinPage += pCache->nMin;
   33920       pcache1LeaveMutex();
   33921     }
   33922   }
   33923   return (sqlite3_pcache *)pCache;
   33924 }
   33925 
   33926 /*
   33927 ** Implementation of the sqlite3_pcache.xCachesize method.
   33928 **
   33929 ** Configure the cache_size limit for a cache.
   33930 */
   33931 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
   33932   PCache1 *pCache = (PCache1 *)p;
   33933   if( pCache->bPurgeable ){
   33934     pcache1EnterMutex();
   33935     pcache1.nMaxPage += (nMax - pCache->nMax);
   33936     pCache->nMax = nMax;
   33937     pcache1EnforceMaxPage();
   33938     pcache1LeaveMutex();
   33939   }
   33940 }
   33941 
   33942 /*
   33943 ** Implementation of the sqlite3_pcache.xPagecount method.
   33944 */
   33945 static int pcache1Pagecount(sqlite3_pcache *p){
   33946   int n;
   33947   pcache1EnterMutex();
   33948   n = ((PCache1 *)p)->nPage;
   33949   pcache1LeaveMutex();
   33950   return n;
   33951 }
   33952 
   33953 /*
   33954 ** Implementation of the sqlite3_pcache.xFetch method.
   33955 **
   33956 ** Fetch a page by key value.
   33957 **
   33958 ** Whether or not a new page may be allocated by this function depends on
   33959 ** the value of the createFlag argument.  0 means do not allocate a new
   33960 ** page.  1 means allocate a new page if space is easily available.  2
   33961 ** means to try really hard to allocate a new page.
   33962 **
   33963 ** For a non-purgeable cache (a cache used as the storage for an in-memory
   33964 ** database) there is really no difference between createFlag 1 and 2.  So
   33965 ** the calling function (pcache.c) will never have a createFlag of 1 on
   33966 ** a non-purgable cache.
   33967 **
   33968 ** There are three different approaches to obtaining space for a page,
   33969 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
   33970 **
   33971 **   1. Regardless of the value of createFlag, the cache is searched for a
   33972 **      copy of the requested page. If one is found, it is returned.
   33973 **
   33974 **   2. If createFlag==0 and the page is not already in the cache, NULL is
   33975 **      returned.
   33976 **
   33977 **   3. If createFlag is 1, and the page is not already in the cache, then
   33978 **      return NULL (do not allocate a new page) if any of the following
   33979 **      conditions are true:
   33980 **
   33981 **       (a) the number of pages pinned by the cache is greater than
   33982 **           PCache1.nMax, or
   33983 **
   33984 **       (b) the number of pages pinned by the cache is greater than
   33985 **           the sum of nMax for all purgeable caches, less the sum of
   33986 **           nMin for all other purgeable caches, or
   33987 **
   33988 **   4. If none of the first three conditions apply and the cache is marked
   33989 **      as purgeable, and if one of the following is true:
   33990 **
   33991 **       (a) The number of pages allocated for the cache is already
   33992 **           PCache1.nMax, or
   33993 **
   33994 **       (b) The number of pages allocated for all purgeable caches is
   33995 **           already equal to or greater than the sum of nMax for all
   33996 **           purgeable caches,
   33997 **
   33998 **       (c) The system is under memory pressure and wants to avoid
   33999 **           unnecessary pages cache entry allocations
   34000 **
   34001 **      then attempt to recycle a page from the LRU list. If it is the right
   34002 **      size, return the recycled buffer. Otherwise, free the buffer and
   34003 **      proceed to step 5.
   34004 **
   34005 **   5. Otherwise, allocate and return a new page buffer.
   34006 */
   34007 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
   34008   unsigned int nPinned;
   34009   PCache1 *pCache = (PCache1 *)p;
   34010   PgHdr1 *pPage = 0;
   34011 
   34012   assert( pCache->bPurgeable || createFlag!=1 );
   34013   pcache1EnterMutex();
   34014   if( createFlag==1 ) sqlite3BeginBenignMalloc();
   34015 
   34016   /* Search the hash table for an existing entry. */
   34017   if( pCache->nHash>0 ){
   34018     unsigned int h = iKey % pCache->nHash;
   34019     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
   34020   }
   34021 
   34022   if( pPage || createFlag==0 ){
   34023     pcache1PinPage(pPage);
   34024     goto fetch_out;
   34025   }
   34026 
   34027   /* Step 3 of header comment. */
   34028   nPinned = pCache->nPage - pCache->nRecyclable;
   34029   if( createFlag==1 && (
   34030         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
   34031      || nPinned>=(pCache->nMax * 9 / 10)
   34032      || pcache1UnderMemoryPressure(pCache)
   34033   )){
   34034     goto fetch_out;
   34035   }
   34036 
   34037   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   34038     goto fetch_out;
   34039   }
   34040 
   34041   /* Step 4. Try to recycle a page buffer if appropriate. */
   34042   if( pCache->bPurgeable && pcache1.pLruTail && (
   34043          (pCache->nPage+1>=pCache->nMax)
   34044       || pcache1.nCurrentPage>=pcache1.nMaxPage
   34045       || pcache1UnderMemoryPressure(pCache)
   34046   )){
   34047     pPage = pcache1.pLruTail;
   34048     pcache1RemoveFromHash(pPage);
   34049     pcache1PinPage(pPage);
   34050     if( pPage->pCache->szPage!=pCache->szPage ){
   34051       pcache1FreePage(pPage);
   34052       pPage = 0;
   34053     }else{
   34054       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
   34055     }
   34056   }
   34057 
   34058   /* Step 5. If a usable page buffer has still not been found,
   34059   ** attempt to allocate a new one.
   34060   */
   34061   if( !pPage ){
   34062     pPage = pcache1AllocPage(pCache);
   34063   }
   34064 
   34065   if( pPage ){
   34066     unsigned int h = iKey % pCache->nHash;
   34067     pCache->nPage++;
   34068     pPage->iKey = iKey;
   34069     pPage->pNext = pCache->apHash[h];
   34070     pPage->pCache = pCache;
   34071     pPage->pLruPrev = 0;
   34072     pPage->pLruNext = 0;
   34073     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
   34074     pCache->apHash[h] = pPage;
   34075   }
   34076 
   34077 fetch_out:
   34078   if( pPage && iKey>pCache->iMaxKey ){
   34079     pCache->iMaxKey = iKey;
   34080   }
   34081   if( createFlag==1 ) sqlite3EndBenignMalloc();
   34082   pcache1LeaveMutex();
   34083   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
   34084 }
   34085 
   34086 
   34087 /*
   34088 ** Implementation of the sqlite3_pcache.xUnpin method.
   34089 **
   34090 ** Mark a page as unpinned (eligible for asynchronous recycling).
   34091 */
   34092 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
   34093   PCache1 *pCache = (PCache1 *)p;
   34094   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
   34095 
   34096   assert( pPage->pCache==pCache );
   34097   pcache1EnterMutex();
   34098 
   34099   /* It is an error to call this function if the page is already
   34100   ** part of the global LRU list.
   34101   */
   34102   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
   34103   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
   34104 
   34105   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
   34106     pcache1RemoveFromHash(pPage);
   34107     pcache1FreePage(pPage);
   34108   }else{
   34109     /* Add the page to the global LRU list. Normally, the page is added to
   34110     ** the head of the list (last page to be recycled). However, if the
   34111     ** reuseUnlikely flag passed to this function is true, the page is added
   34112     ** to the tail of the list (first page to be recycled).
   34113     */
   34114     if( pcache1.pLruHead ){
   34115       pcache1.pLruHead->pLruPrev = pPage;
   34116       pPage->pLruNext = pcache1.pLruHead;
   34117       pcache1.pLruHead = pPage;
   34118     }else{
   34119       pcache1.pLruTail = pPage;
   34120       pcache1.pLruHead = pPage;
   34121     }
   34122     pCache->nRecyclable++;
   34123   }
   34124 
   34125   pcache1LeaveMutex();
   34126 }
   34127 
   34128 /*
   34129 ** Implementation of the sqlite3_pcache.xRekey method.
   34130 */
   34131 static void pcache1Rekey(
   34132   sqlite3_pcache *p,
   34133   void *pPg,
   34134   unsigned int iOld,
   34135   unsigned int iNew
   34136 ){
   34137   PCache1 *pCache = (PCache1 *)p;
   34138   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
   34139   PgHdr1 **pp;
   34140   unsigned int h;
   34141   assert( pPage->iKey==iOld );
   34142   assert( pPage->pCache==pCache );
   34143 
   34144   pcache1EnterMutex();
   34145 
   34146   h = iOld%pCache->nHash;
   34147   pp = &pCache->apHash[h];
   34148   while( (*pp)!=pPage ){
   34149     pp = &(*pp)->pNext;
   34150   }
   34151   *pp = pPage->pNext;
   34152 
   34153   h = iNew%pCache->nHash;
   34154   pPage->iKey = iNew;
   34155   pPage->pNext = pCache->apHash[h];
   34156   pCache->apHash[h] = pPage;
   34157   if( iNew>pCache->iMaxKey ){
   34158     pCache->iMaxKey = iNew;
   34159   }
   34160 
   34161   pcache1LeaveMutex();
   34162 }
   34163 
   34164 /*
   34165 ** Implementation of the sqlite3_pcache.xTruncate method.
   34166 **
   34167 ** Discard all unpinned pages in the cache with a page number equal to
   34168 ** or greater than parameter iLimit. Any pinned pages with a page number
   34169 ** equal to or greater than iLimit are implicitly unpinned.
   34170 */
   34171 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
   34172   PCache1 *pCache = (PCache1 *)p;
   34173   pcache1EnterMutex();
   34174   if( iLimit<=pCache->iMaxKey ){
   34175     pcache1TruncateUnsafe(pCache, iLimit);
   34176     pCache->iMaxKey = iLimit-1;
   34177   }
   34178   pcache1LeaveMutex();
   34179 }
   34180 
   34181 /*
   34182 ** Implementation of the sqlite3_pcache.xDestroy method.
   34183 **
   34184 ** Destroy a cache allocated using pcache1Create().
   34185 */
   34186 static void pcache1Destroy(sqlite3_pcache *p){
   34187   PCache1 *pCache = (PCache1 *)p;
   34188   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   34189   pcache1EnterMutex();
   34190   pcache1TruncateUnsafe(pCache, 0);
   34191   pcache1.nMaxPage -= pCache->nMax;
   34192   pcache1.nMinPage -= pCache->nMin;
   34193   pcache1EnforceMaxPage();
   34194   pcache1LeaveMutex();
   34195   sqlite3_free(pCache->apHash);
   34196   sqlite3_free(pCache);
   34197 }
   34198 
   34199 /*
   34200 ** This function is called during initialization (sqlite3_initialize()) to
   34201 ** install the default pluggable cache module, assuming the user has not
   34202 ** already provided an alternative.
   34203 */
   34204 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
   34205   static const sqlite3_pcache_methods defaultMethods = {
   34206     0,                       /* pArg */
   34207     pcache1Init,             /* xInit */
   34208     pcache1Shutdown,         /* xShutdown */
   34209     pcache1Create,           /* xCreate */
   34210     pcache1Cachesize,        /* xCachesize */
   34211     pcache1Pagecount,        /* xPagecount */
   34212     pcache1Fetch,            /* xFetch */
   34213     pcache1Unpin,            /* xUnpin */
   34214     pcache1Rekey,            /* xRekey */
   34215     pcache1Truncate,         /* xTruncate */
   34216     pcache1Destroy           /* xDestroy */
   34217   };
   34218   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
   34219 }
   34220 
   34221 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   34222 /*
   34223 ** This function is called to free superfluous dynamically allocated memory
   34224 ** held by the pager system. Memory in use by any SQLite pager allocated
   34225 ** by the current thread may be sqlite3_free()ed.
   34226 **
   34227 ** nReq is the number of bytes of memory required. Once this much has
   34228 ** been released, the function returns. The return value is the total number
   34229 ** of bytes of memory released.
   34230 */
   34231 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
   34232   int nFree = 0;
   34233   if( pcache1.pStart==0 ){
   34234     PgHdr1 *p;
   34235     pcache1EnterMutex();
   34236     while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
   34237       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
   34238       pcache1PinPage(p);
   34239       pcache1RemoveFromHash(p);
   34240       pcache1FreePage(p);
   34241     }
   34242     pcache1LeaveMutex();
   34243   }
   34244   return nFree;
   34245 }
   34246 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   34247 
   34248 #ifdef SQLITE_TEST
   34249 /*
   34250 ** This function is used by test procedures to inspect the internal state
   34251 ** of the global cache.
   34252 */
   34253 SQLITE_PRIVATE void sqlite3PcacheStats(
   34254   int *pnCurrent,      /* OUT: Total number of pages cached */
   34255   int *pnMax,          /* OUT: Global maximum cache size */
   34256   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
   34257   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
   34258 ){
   34259   PgHdr1 *p;
   34260   int nRecyclable = 0;
   34261   for(p=pcache1.pLruHead; p; p=p->pLruNext){
   34262     nRecyclable++;
   34263   }
   34264   *pnCurrent = pcache1.nCurrentPage;
   34265   *pnMax = pcache1.nMaxPage;
   34266   *pnMin = pcache1.nMinPage;
   34267   *pnRecyclable = nRecyclable;
   34268 }
   34269 #endif
   34270 
   34271 /************** End of pcache1.c *********************************************/
   34272 /************** Begin file rowset.c ******************************************/
   34273 /*
   34274 ** 2008 December 3
   34275 **
   34276 ** The author disclaims copyright to this source code.  In place of
   34277 ** a legal notice, here is a blessing:
   34278 **
   34279 **    May you do good and not evil.
   34280 **    May you find forgiveness for yourself and forgive others.
   34281 **    May you share freely, never taking more than you give.
   34282 **
   34283 *************************************************************************
   34284 **
   34285 ** This module implements an object we call a "RowSet".
   34286 **
   34287 ** The RowSet object is a collection of rowids.  Rowids
   34288 ** are inserted into the RowSet in an arbitrary order.  Inserts
   34289 ** can be intermixed with tests to see if a given rowid has been
   34290 ** previously inserted into the RowSet.
   34291 **
   34292 ** After all inserts are finished, it is possible to extract the
   34293 ** elements of the RowSet in sorted order.  Once this extraction
   34294 ** process has started, no new elements may be inserted.
   34295 **
   34296 ** Hence, the primitive operations for a RowSet are:
   34297 **
   34298 **    CREATE
   34299 **    INSERT
   34300 **    TEST
   34301 **    SMALLEST
   34302 **    DESTROY
   34303 **
   34304 ** The CREATE and DESTROY primitives are the constructor and destructor,
   34305 ** obviously.  The INSERT primitive adds a new element to the RowSet.
   34306 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
   34307 ** extracts the least value from the RowSet.
   34308 **
   34309 ** The INSERT primitive might allocate additional memory.  Memory is
   34310 ** allocated in chunks so most INSERTs do no allocation.  There is an
   34311 ** upper bound on the size of allocated memory.  No memory is freed
   34312 ** until DESTROY.
   34313 **
   34314 ** The TEST primitive includes a "batch" number.  The TEST primitive
   34315 ** will only see elements that were inserted before the last change
   34316 ** in the batch number.  In other words, if an INSERT occurs between
   34317 ** two TESTs where the TESTs have the same batch nubmer, then the
   34318 ** value added by the INSERT will not be visible to the second TEST.
   34319 ** The initial batch number is zero, so if the very first TEST contains
   34320 ** a non-zero batch number, it will see all prior INSERTs.
   34321 **
   34322 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
   34323 ** that is attempted.
   34324 **
   34325 ** The cost of an INSERT is roughly constant.  (Sometime new memory
   34326 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
   34327 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
   34328 ** The cost of a TEST using the same batch number is O(logN).  The cost
   34329 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
   34330 ** primitives are constant time.  The cost of DESTROY is O(N).
   34331 **
   34332 ** There is an added cost of O(N) when switching between TEST and
   34333 ** SMALLEST primitives.
   34334 */
   34335 
   34336 
   34337 /*
   34338 ** Target size for allocation chunks.
   34339 */
   34340 #define ROWSET_ALLOCATION_SIZE 1024
   34341 
   34342 /*
   34343 ** The number of rowset entries per allocation chunk.
   34344 */
   34345 #define ROWSET_ENTRY_PER_CHUNK  \
   34346                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
   34347 
   34348 /*
   34349 ** Each entry in a RowSet is an instance of the following object.
   34350 */
   34351 struct RowSetEntry {
   34352   i64 v;                        /* ROWID value for this entry */
   34353   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   34354   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
   34355 };
   34356 
   34357 /*
   34358 ** RowSetEntry objects are allocated in large chunks (instances of the
   34359 ** following structure) to reduce memory allocation overhead.  The
   34360 ** chunks are kept on a linked list so that they can be deallocated
   34361 ** when the RowSet is destroyed.
   34362 */
   34363 struct RowSetChunk {
   34364   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
   34365   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
   34366 };
   34367 
   34368 /*
   34369 ** A RowSet in an instance of the following structure.
   34370 **
   34371 ** A typedef of this structure if found in sqliteInt.h.
   34372 */
   34373 struct RowSet {
   34374   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
   34375   sqlite3 *db;                   /* The database connection */
   34376   struct RowSetEntry *pEntry;    /* List of entries using pRight */
   34377   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
   34378   struct RowSetEntry *pFresh;    /* Source of new entry objects */
   34379   struct RowSetEntry *pTree;     /* Binary tree of entries */
   34380   u16 nFresh;                    /* Number of objects on pFresh */
   34381   u8 isSorted;                   /* True if pEntry is sorted */
   34382   u8 iBatch;                     /* Current insert batch */
   34383 };
   34384 
   34385 /*
   34386 ** Turn bulk memory into a RowSet object.  N bytes of memory
   34387 ** are available at pSpace.  The db pointer is used as a memory context
   34388 ** for any subsequent allocations that need to occur.
   34389 ** Return a pointer to the new RowSet object.
   34390 **
   34391 ** It must be the case that N is sufficient to make a Rowset.  If not
   34392 ** an assertion fault occurs.
   34393 **
   34394 ** If N is larger than the minimum, use the surplus as an initial
   34395 ** allocation of entries available to be filled.
   34396 */
   34397 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
   34398   RowSet *p;
   34399   assert( N >= ROUND8(sizeof(*p)) );
   34400   p = pSpace;
   34401   p->pChunk = 0;
   34402   p->db = db;
   34403   p->pEntry = 0;
   34404   p->pLast = 0;
   34405   p->pTree = 0;
   34406   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
   34407   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
   34408   p->isSorted = 1;
   34409   p->iBatch = 0;
   34410   return p;
   34411 }
   34412 
   34413 /*
   34414 ** Deallocate all chunks from a RowSet.  This frees all memory that
   34415 ** the RowSet has allocated over its lifetime.  This routine is
   34416 ** the destructor for the RowSet.
   34417 */
   34418 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
   34419   struct RowSetChunk *pChunk, *pNextChunk;
   34420   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
   34421     pNextChunk = pChunk->pNextChunk;
   34422     sqlite3DbFree(p->db, pChunk);
   34423   }
   34424   p->pChunk = 0;
   34425   p->nFresh = 0;
   34426   p->pEntry = 0;
   34427   p->pLast = 0;
   34428   p->pTree = 0;
   34429   p->isSorted = 1;
   34430 }
   34431 
   34432 /*
   34433 ** Insert a new value into a RowSet.
   34434 **
   34435 ** The mallocFailed flag of the database connection is set if a
   34436 ** memory allocation fails.
   34437 */
   34438 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
   34439   struct RowSetEntry *pEntry;  /* The new entry */
   34440   struct RowSetEntry *pLast;   /* The last prior entry */
   34441   assert( p!=0 );
   34442   if( p->nFresh==0 ){
   34443     struct RowSetChunk *pNew;
   34444     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
   34445     if( pNew==0 ){
   34446       return;
   34447     }
   34448     pNew->pNextChunk = p->pChunk;
   34449     p->pChunk = pNew;
   34450     p->pFresh = pNew->aEntry;
   34451     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
   34452   }
   34453   pEntry = p->pFresh++;
   34454   p->nFresh--;
   34455   pEntry->v = rowid;
   34456   pEntry->pRight = 0;
   34457   pLast = p->pLast;
   34458   if( pLast ){
   34459     if( p->isSorted && rowid<=pLast->v ){
   34460       p->isSorted = 0;
   34461     }
   34462     pLast->pRight = pEntry;
   34463   }else{
   34464     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
   34465     p->pEntry = pEntry;
   34466   }
   34467   p->pLast = pEntry;
   34468 }
   34469 
   34470 /*
   34471 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
   34472 **
   34473 ** The input lists are connected via pRight pointers and are
   34474 ** assumed to each already be in sorted order.
   34475 */
   34476 static struct RowSetEntry *rowSetMerge(
   34477   struct RowSetEntry *pA,    /* First sorted list to be merged */
   34478   struct RowSetEntry *pB     /* Second sorted list to be merged */
   34479 ){
   34480   struct RowSetEntry head;
   34481   struct RowSetEntry *pTail;
   34482 
   34483   pTail = &head;
   34484   while( pA && pB ){
   34485     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   34486     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
   34487     if( pA->v<pB->v ){
   34488       pTail->pRight = pA;
   34489       pA = pA->pRight;
   34490       pTail = pTail->pRight;
   34491     }else if( pB->v<pA->v ){
   34492       pTail->pRight = pB;
   34493       pB = pB->pRight;
   34494       pTail = pTail->pRight;
   34495     }else{
   34496       pA = pA->pRight;
   34497     }
   34498   }
   34499   if( pA ){
   34500     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
   34501     pTail->pRight = pA;
   34502   }else{
   34503     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
   34504     pTail->pRight = pB;
   34505   }
   34506   return head.pRight;
   34507 }
   34508 
   34509 /*
   34510 ** Sort all elements on the pEntry list of the RowSet into ascending order.
   34511 */
   34512 static void rowSetSort(RowSet *p){
   34513   unsigned int i;
   34514   struct RowSetEntry *pEntry;
   34515   struct RowSetEntry *aBucket[40];
   34516 
   34517   assert( p->isSorted==0 );
   34518   memset(aBucket, 0, sizeof(aBucket));
   34519   while( p->pEntry ){
   34520     pEntry = p->pEntry;
   34521     p->pEntry = pEntry->pRight;
   34522     pEntry->pRight = 0;
   34523     for(i=0; aBucket[i]; i++){
   34524       pEntry = rowSetMerge(aBucket[i], pEntry);
   34525       aBucket[i] = 0;
   34526     }
   34527     aBucket[i] = pEntry;
   34528   }
   34529   pEntry = 0;
   34530   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
   34531     pEntry = rowSetMerge(pEntry, aBucket[i]);
   34532   }
   34533   p->pEntry = pEntry;
   34534   p->pLast = 0;
   34535   p->isSorted = 1;
   34536 }
   34537 
   34538 
   34539 /*
   34540 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
   34541 ** Convert this tree into a linked list connected by the pRight pointers
   34542 ** and return pointers to the first and last elements of the new list.
   34543 */
   34544 static void rowSetTreeToList(
   34545   struct RowSetEntry *pIn,         /* Root of the input tree */
   34546   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
   34547   struct RowSetEntry **ppLast      /* Write tail of the output list here */
   34548 ){
   34549   assert( pIn!=0 );
   34550   if( pIn->pLeft ){
   34551     struct RowSetEntry *p;
   34552     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
   34553     p->pRight = pIn;
   34554   }else{
   34555     *ppFirst = pIn;
   34556   }
   34557   if( pIn->pRight ){
   34558     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
   34559   }else{
   34560     *ppLast = pIn;
   34561   }
   34562   assert( (*ppLast)->pRight==0 );
   34563 }
   34564 
   34565 
   34566 /*
   34567 ** Convert a sorted list of elements (connected by pRight) into a binary
   34568 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
   34569 ** node taken from the head of *ppList.  A depth of 2 means a tree with
   34570 ** three nodes.  And so forth.
   34571 **
   34572 ** Use as many entries from the input list as required and update the
   34573 ** *ppList to point to the unused elements of the list.  If the input
   34574 ** list contains too few elements, then construct an incomplete tree
   34575 ** and leave *ppList set to NULL.
   34576 **
   34577 ** Return a pointer to the root of the constructed binary tree.
   34578 */
   34579 static struct RowSetEntry *rowSetNDeepTree(
   34580   struct RowSetEntry **ppList,
   34581   int iDepth
   34582 ){
   34583   struct RowSetEntry *p;         /* Root of the new tree */
   34584   struct RowSetEntry *pLeft;     /* Left subtree */
   34585   if( *ppList==0 ){
   34586     return 0;
   34587   }
   34588   if( iDepth==1 ){
   34589     p = *ppList;
   34590     *ppList = p->pRight;
   34591     p->pLeft = p->pRight = 0;
   34592     return p;
   34593   }
   34594   pLeft = rowSetNDeepTree(ppList, iDepth-1);
   34595   p = *ppList;
   34596   if( p==0 ){
   34597     return pLeft;
   34598   }
   34599   p->pLeft = pLeft;
   34600   *ppList = p->pRight;
   34601   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
   34602   return p;
   34603 }
   34604 
   34605 /*
   34606 ** Convert a sorted list of elements into a binary tree. Make the tree
   34607 ** as deep as it needs to be in order to contain the entire list.
   34608 */
   34609 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
   34610   int iDepth;           /* Depth of the tree so far */
   34611   struct RowSetEntry *p;       /* Current tree root */
   34612   struct RowSetEntry *pLeft;   /* Left subtree */
   34613 
   34614   assert( pList!=0 );
   34615   p = pList;
   34616   pList = p->pRight;
   34617   p->pLeft = p->pRight = 0;
   34618   for(iDepth=1; pList; iDepth++){
   34619     pLeft = p;
   34620     p = pList;
   34621     pList = p->pRight;
   34622     p->pLeft = pLeft;
   34623     p->pRight = rowSetNDeepTree(&pList, iDepth);
   34624   }
   34625   return p;
   34626 }
   34627 
   34628 /*
   34629 ** Convert the list in p->pEntry into a sorted list if it is not
   34630 ** sorted already.  If there is a binary tree on p->pTree, then
   34631 ** convert it into a list too and merge it into the p->pEntry list.
   34632 */
   34633 static void rowSetToList(RowSet *p){
   34634   if( !p->isSorted ){
   34635     rowSetSort(p);
   34636   }
   34637   if( p->pTree ){
   34638     struct RowSetEntry *pHead, *pTail;
   34639     rowSetTreeToList(p->pTree, &pHead, &pTail);
   34640     p->pTree = 0;
   34641     p->pEntry = rowSetMerge(p->pEntry, pHead);
   34642   }
   34643 }
   34644 
   34645 /*
   34646 ** Extract the smallest element from the RowSet.
   34647 ** Write the element into *pRowid.  Return 1 on success.  Return
   34648 ** 0 if the RowSet is already empty.
   34649 **
   34650 ** After this routine has been called, the sqlite3RowSetInsert()
   34651 ** routine may not be called again.
   34652 */
   34653 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
   34654   rowSetToList(p);
   34655   if( p->pEntry ){
   34656     *pRowid = p->pEntry->v;
   34657     p->pEntry = p->pEntry->pRight;
   34658     if( p->pEntry==0 ){
   34659       sqlite3RowSetClear(p);
   34660     }
   34661     return 1;
   34662   }else{
   34663     return 0;
   34664   }
   34665 }
   34666 
   34667 /*
   34668 ** Check to see if element iRowid was inserted into the the rowset as
   34669 ** part of any insert batch prior to iBatch.  Return 1 or 0.
   34670 */
   34671 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
   34672   struct RowSetEntry *p;
   34673   if( iBatch!=pRowSet->iBatch ){
   34674     if( pRowSet->pEntry ){
   34675       rowSetToList(pRowSet);
   34676       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
   34677       pRowSet->pEntry = 0;
   34678       pRowSet->pLast = 0;
   34679     }
   34680     pRowSet->iBatch = iBatch;
   34681   }
   34682   p = pRowSet->pTree;
   34683   while( p ){
   34684     if( p->v<iRowid ){
   34685       p = p->pRight;
   34686     }else if( p->v>iRowid ){
   34687       p = p->pLeft;
   34688     }else{
   34689       return 1;
   34690     }
   34691   }
   34692   return 0;
   34693 }
   34694 
   34695 /************** End of rowset.c **********************************************/
   34696 /************** Begin file pager.c *******************************************/
   34697 /*
   34698 ** 2001 September 15
   34699 **
   34700 ** The author disclaims copyright to this source code.  In place of
   34701 ** a legal notice, here is a blessing:
   34702 **
   34703 **    May you do good and not evil.
   34704 **    May you find forgiveness for yourself and forgive others.
   34705 **    May you share freely, never taking more than you give.
   34706 **
   34707 *************************************************************************
   34708 ** This is the implementation of the page cache subsystem or "pager".
   34709 **
   34710 ** The pager is used to access a database disk file.  It implements
   34711 ** atomic commit and rollback through the use of a journal file that
   34712 ** is separate from the database file.  The pager also implements file
   34713 ** locking to prevent two processes from writing the same database
   34714 ** file simultaneously, or one process from reading the database while
   34715 ** another is writing.
   34716 */
   34717 #ifndef SQLITE_OMIT_DISKIO
   34718 /************** Include wal.h in the middle of pager.c ***********************/
   34719 /************** Begin file wal.h *********************************************/
   34720 /*
   34721 ** 2010 February 1
   34722 **
   34723 ** The author disclaims copyright to this source code.  In place of
   34724 ** a legal notice, here is a blessing:
   34725 **
   34726 **    May you do good and not evil.
   34727 **    May you find forgiveness for yourself and forgive others.
   34728 **    May you share freely, never taking more than you give.
   34729 **
   34730 *************************************************************************
   34731 ** This header file defines the interface to the write-ahead logging
   34732 ** system. Refer to the comments below and the header comment attached to
   34733 ** the implementation of each function in log.c for further details.
   34734 */
   34735 
   34736 #ifndef _WAL_H_
   34737 #define _WAL_H_
   34738 
   34739 
   34740 #ifdef SQLITE_OMIT_WAL
   34741 # define sqlite3WalOpen(x,y,z)                 0
   34742 # define sqlite3WalClose(w,x,y,z)              0
   34743 # define sqlite3WalBeginReadTransaction(y,z)   0
   34744 # define sqlite3WalEndReadTransaction(z)
   34745 # define sqlite3WalRead(v,w,x,y,z)             0
   34746 # define sqlite3WalDbsize(y)                   0
   34747 # define sqlite3WalBeginWriteTransaction(y)    0
   34748 # define sqlite3WalEndWriteTransaction(x)      0
   34749 # define sqlite3WalUndo(x,y,z)                 0
   34750 # define sqlite3WalSavepoint(y,z)
   34751 # define sqlite3WalSavepointUndo(y,z)          0
   34752 # define sqlite3WalFrames(u,v,w,x,y,z)         0
   34753 # define sqlite3WalCheckpoint(u,v,w,x)         0
   34754 # define sqlite3WalCallback(z)                 0
   34755 # define sqlite3WalExclusiveMode(y,z)          0
   34756 # define sqlite3WalHeapMemory(z)               0
   34757 #else
   34758 
   34759 #define WAL_SAVEPOINT_NDATA 4
   34760 
   34761 /* Connection to a write-ahead log (WAL) file.
   34762 ** There is one object of this type for each pager.
   34763 */
   34764 typedef struct Wal Wal;
   34765 
   34766 /* Open and close a connection to a write-ahead log. */
   34767 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
   34768 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
   34769 
   34770 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
   34771 ** snapshot is like a read-transaction.  It is the state of the database
   34772 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
   34773 ** preserves the current state even if the other threads or processes
   34774 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
   34775 ** transaction and releases the lock.
   34776 */
   34777 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
   34778 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
   34779 
   34780 /* Read a page from the write-ahead log, if it is present. */
   34781 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
   34782 
   34783 /* If the WAL is not empty, return the size of the database. */
   34784 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
   34785 
   34786 /* Obtain or release the WRITER lock. */
   34787 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
   34788 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
   34789 
   34790 /* Undo any frames written (but not committed) to the log */
   34791 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
   34792 
   34793 /* Return an integer that records the current (uncommitted) write
   34794 ** position in the WAL */
   34795 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
   34796 
   34797 /* Move the write position of the WAL back to iFrame.  Called in
   34798 ** response to a ROLLBACK TO command. */
   34799 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
   34800 
   34801 /* Write a frame or frames to the log. */
   34802 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
   34803 
   34804 /* Copy pages from the log to the database file */
   34805 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   34806   Wal *pWal,                      /* Write-ahead log connection */
   34807   int sync_flags,                 /* Flags to sync db file with (or 0) */
   34808   int nBuf,                       /* Size of buffer nBuf */
   34809   u8 *zBuf                        /* Temporary buffer to use */
   34810 );
   34811 
   34812 /* Return the value to pass to a sqlite3_wal_hook callback, the
   34813 ** number of frames in the WAL at the point of the last commit since
   34814 ** sqlite3WalCallback() was called.  If no commits have occurred since
   34815 ** the last call, then return 0.
   34816 */
   34817 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
   34818 
   34819 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
   34820 ** by the pager layer on the database file.
   34821 */
   34822 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
   34823 
   34824 /* Return true if the argument is non-NULL and the WAL module is using
   34825 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   34826 ** WAL module is using shared-memory, return false.
   34827 */
   34828 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
   34829 
   34830 #endif /* ifndef SQLITE_OMIT_WAL */
   34831 #endif /* _WAL_H_ */
   34832 
   34833 /************** End of wal.h *************************************************/
   34834 /************** Continuing where we left off in pager.c **********************/
   34835 
   34836 
   34837 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
   34838 **
   34839 ** This comment block describes invariants that hold when using a rollback
   34840 ** journal.  These invariants do not apply for journal_mode=WAL,
   34841 ** journal_mode=MEMORY, or journal_mode=OFF.
   34842 **
   34843 ** Within this comment block, a page is deemed to have been synced
   34844 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
   34845 ** Otherwise, the page is not synced until the xSync method of the VFS
   34846 ** is called successfully on the file containing the page.
   34847 **
   34848 ** Definition:  A page of the database file is said to be "overwriteable" if
   34849 ** one or more of the following are true about the page:
   34850 **
   34851 **     (a)  The original content of the page as it was at the beginning of
   34852 **          the transaction has been written into the rollback journal and
   34853 **          synced.
   34854 **
   34855 **     (b)  The page was a freelist leaf page at the start of the transaction.
   34856 **
   34857 **     (c)  The page number is greater than the largest page that existed in
   34858 **          the database file at the start of the transaction.
   34859 **
   34860 ** (1) A page of the database file is never overwritten unless one of the
   34861 **     following are true:
   34862 **
   34863 **     (a) The page and all other pages on the same sector are overwriteable.
   34864 **
   34865 **     (b) The atomic page write optimization is enabled, and the entire
   34866 **         transaction other than the update of the transaction sequence
   34867 **         number consists of a single page change.
   34868 **
   34869 ** (2) The content of a page written into the rollback journal exactly matches
   34870 **     both the content in the database when the rollback journal was written
   34871 **     and the content in the database at the beginning of the current
   34872 **     transaction.
   34873 **
   34874 ** (3) Writes to the database file are an integer multiple of the page size
   34875 **     in length and are aligned on a page boundary.
   34876 **
   34877 ** (4) Reads from the database file are either aligned on a page boundary and
   34878 **     an integer multiple of the page size in length or are taken from the
   34879 **     first 100 bytes of the database file.
   34880 **
   34881 ** (5) All writes to the database file are synced prior to the rollback journal
   34882 **     being deleted, truncated, or zeroed.
   34883 **
   34884 ** (6) If a master journal file is used, then all writes to the database file
   34885 **     are synced prior to the master journal being deleted.
   34886 **
   34887 ** Definition: Two databases (or the same database at two points it time)
   34888 ** are said to be "logically equivalent" if they give the same answer to
   34889 ** all queries.  Note in particular the the content of freelist leaf
   34890 ** pages can be changed arbitarily without effecting the logical equivalence
   34891 ** of the database.
   34892 **
   34893 ** (7) At any time, if any subset, including the empty set and the total set,
   34894 **     of the unsynced changes to a rollback journal are removed and the
   34895 **     journal is rolled back, the resulting database file will be logical
   34896 **     equivalent to the database file at the beginning of the transaction.
   34897 **
   34898 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
   34899 **     is called to restore the database file to the same size it was at
   34900 **     the beginning of the transaction.  (In some VFSes, the xTruncate
   34901 **     method is a no-op, but that does not change the fact the SQLite will
   34902 **     invoke it.)
   34903 **
   34904 ** (9) Whenever the database file is modified, at least one bit in the range
   34905 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
   34906 **     the EXCLUSIVE lock, thus signaling other connections on the same
   34907 **     database to flush their caches.
   34908 **
   34909 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
   34910 **      than one billion transactions.
   34911 **
   34912 ** (11) A database file is well-formed at the beginning and at the conclusion
   34913 **      of every transaction.
   34914 **
   34915 ** (12) An EXCLUSIVE lock is held on the database file when writing to
   34916 **      the database file.
   34917 **
   34918 ** (13) A SHARED lock is held on the database file while reading any
   34919 **      content out of the database file.
   34920 **
   34921 ******************************************************************************/
   34922 
   34923 /*
   34924 ** Macros for troubleshooting.  Normally turned off
   34925 */
   34926 #if 0
   34927 int sqlite3PagerTrace=1;  /* True to enable tracing */
   34928 #define sqlite3DebugPrintf printf
   34929 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
   34930 #else
   34931 #define PAGERTRACE(X)
   34932 #endif
   34933 
   34934 /*
   34935 ** The following two macros are used within the PAGERTRACE() macros above
   34936 ** to print out file-descriptors.
   34937 **
   34938 ** PAGERID() takes a pointer to a Pager struct as its argument. The
   34939 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
   34940 ** struct as its argument.
   34941 */
   34942 #define PAGERID(p) ((int)(p->fd))
   34943 #define FILEHANDLEID(fd) ((int)fd)
   34944 
   34945 /*
   34946 ** The Pager.eState variable stores the current 'state' of a pager. A
   34947 ** pager may be in any one of the seven states shown in the following
   34948 ** state diagram.
   34949 **
   34950 **                            OPEN <------+------+
   34951 **                              |         |      |
   34952 **                              V         |      |
   34953 **               +---------> READER-------+      |
   34954 **               |              |                |
   34955 **               |              V                |
   34956 **               |<-------WRITER_LOCKED------> ERROR
   34957 **               |              |                ^
   34958 **               |              V                |
   34959 **               |<------WRITER_CACHEMOD-------->|
   34960 **               |              |                |
   34961 **               |              V                |
   34962 **               |<-------WRITER_DBMOD---------->|
   34963 **               |              |                |
   34964 **               |              V                |
   34965 **               +<------WRITER_FINISHED-------->+
   34966 **
   34967 **
   34968 ** List of state transitions and the C [function] that performs each:
   34969 **
   34970 **   OPEN              -> READER              [sqlite3PagerSharedLock]
   34971 **   READER            -> OPEN                [pager_unlock]
   34972 **
   34973 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
   34974 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
   34975 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
   34976 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
   34977 **   WRITER_***        -> READER              [pager_end_transaction]
   34978 **
   34979 **   WRITER_***        -> ERROR               [pager_error]
   34980 **   ERROR             -> OPEN                [pager_unlock]
   34981 **
   34982 **
   34983 **  OPEN:
   34984 **
   34985 **    The pager starts up in this state. Nothing is guaranteed in this
   34986 **    state - the file may or may not be locked and the database size is
   34987 **    unknown. The database may not be read or written.
   34988 **
   34989 **    * No read or write transaction is active.
   34990 **    * Any lock, or no lock at all, may be held on the database file.
   34991 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
   34992 **
   34993 **  READER:
   34994 **
   34995 **    In this state all the requirements for reading the database in
   34996 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
   34997 **    was) in exclusive-locking mode, a user-level read transaction is
   34998 **    open. The database size is known in this state.
   34999 **
   35000 **    A connection running with locking_mode=normal enters this state when
   35001 **    it opens a read-transaction on the database and returns to state
   35002 **    OPEN after the read-transaction is completed. However a connection
   35003 **    running in locking_mode=exclusive (including temp databases) remains in
   35004 **    this state even after the read-transaction is closed. The only way
   35005 **    a locking_mode=exclusive connection can transition from READER to OPEN
   35006 **    is via the ERROR state (see below).
   35007 **
   35008 **    * A read transaction may be active (but a write-transaction cannot).
   35009 **    * A SHARED or greater lock is held on the database file.
   35010 **    * The dbSize variable may be trusted (even if a user-level read
   35011 **      transaction is not active). The dbOrigSize and dbFileSize variables
   35012 **      may not be trusted at this point.
   35013 **    * If the database is a WAL database, then the WAL connection is open.
   35014 **    * Even if a read-transaction is not open, it is guaranteed that
   35015 **      there is no hot-journal in the file-system.
   35016 **
   35017 **  WRITER_LOCKED:
   35018 **
   35019 **    The pager moves to this state from READER when a write-transaction
   35020 **    is first opened on the database. In WRITER_LOCKED state, all locks
   35021 **    required to start a write-transaction are held, but no actual
   35022 **    modifications to the cache or database have taken place.
   35023 **
   35024 **    In rollback mode, a RESERVED or (if the transaction was opened with
   35025 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
   35026 **    moving to this state, but the journal file is not written to or opened
   35027 **    to in this state. If the transaction is committed or rolled back while
   35028 **    in WRITER_LOCKED state, all that is required is to unlock the database
   35029 **    file.
   35030 **
   35031 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
   35032 **    If the connection is running with locking_mode=exclusive, an attempt
   35033 **    is made to obtain an EXCLUSIVE lock on the database file.
   35034 **
   35035 **    * A write transaction is active.
   35036 **    * If the connection is open in rollback-mode, a RESERVED or greater
   35037 **      lock is held on the database file.
   35038 **    * If the connection is open in WAL-mode, a WAL write transaction
   35039 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
   35040 **      called).
   35041 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
   35042 **    * The contents of the pager cache have not been modified.
   35043 **    * The journal file may or may not be open.
   35044 **    * Nothing (not even the first header) has been written to the journal.
   35045 **
   35046 **  WRITER_CACHEMOD:
   35047 **
   35048 **    A pager moves from WRITER_LOCKED state to this state when a page is
   35049 **    first modified by the upper layer. In rollback mode the journal file
   35050 **    is opened (if it is not already open) and a header written to the
   35051 **    start of it. The database file on disk has not been modified.
   35052 **
   35053 **    * A write transaction is active.
   35054 **    * A RESERVED or greater lock is held on the database file.
   35055 **    * The journal file is open and the first header has been written
   35056 **      to it, but the header has not been synced to disk.
   35057 **    * The contents of the page cache have been modified.
   35058 **
   35059 **  WRITER_DBMOD:
   35060 **
   35061 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
   35062 **    when it modifies the contents of the database file. WAL connections
   35063 **    never enter this state (since they do not modify the database file,
   35064 **    just the log file).
   35065 **
   35066 **    * A write transaction is active.
   35067 **    * An EXCLUSIVE or greater lock is held on the database file.
   35068 **    * The journal file is open and the first header has been written
   35069 **      and synced to disk.
   35070 **    * The contents of the page cache have been modified (and possibly
   35071 **      written to disk).
   35072 **
   35073 **  WRITER_FINISHED:
   35074 **
   35075 **    It is not possible for a WAL connection to enter this state.
   35076 **
   35077 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
   35078 **    state after the entire transaction has been successfully written into the
   35079 **    database file. In this state the transaction may be committed simply
   35080 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
   35081 **    not possible to modify the database further. At this point, the upper
   35082 **    layer must either commit or rollback the transaction.
   35083 **
   35084 **    * A write transaction is active.
   35085 **    * An EXCLUSIVE or greater lock is held on the database file.
   35086 **    * All writing and syncing of journal and database data has finished.
   35087 **      If no error occured, all that remains is to finalize the journal to
   35088 **      commit the transaction. If an error did occur, the caller will need
   35089 **      to rollback the transaction.
   35090 **
   35091 **  ERROR:
   35092 **
   35093 **    The ERROR state is entered when an IO or disk-full error (including
   35094 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
   35095 **    difficult to be sure that the in-memory pager state (cache contents,
   35096 **    db size etc.) are consistent with the contents of the file-system.
   35097 **
   35098 **    Temporary pager files may enter the ERROR state, but in-memory pagers
   35099 **    cannot.
   35100 **
   35101 **    For example, if an IO error occurs while performing a rollback,
   35102 **    the contents of the page-cache may be left in an inconsistent state.
   35103 **    At this point it would be dangerous to change back to READER state
   35104 **    (as usually happens after a rollback). Any subsequent readers might
   35105 **    report database corruption (due to the inconsistent cache), and if
   35106 **    they upgrade to writers, they may inadvertently corrupt the database
   35107 **    file. To avoid this hazard, the pager switches into the ERROR state
   35108 **    instead of READER following such an error.
   35109 **
   35110 **    Once it has entered the ERROR state, any attempt to use the pager
   35111 **    to read or write data returns an error. Eventually, once all
   35112 **    outstanding transactions have been abandoned, the pager is able to
   35113 **    transition back to OPEN state, discarding the contents of the
   35114 **    page-cache and any other in-memory state at the same time. Everything
   35115 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
   35116 **    when a read-transaction is next opened on the pager (transitioning
   35117 **    the pager into READER state). At that point the system has recovered
   35118 **    from the error.
   35119 **
   35120 **    Specifically, the pager jumps into the ERROR state if:
   35121 **
   35122 **      1. An error occurs while attempting a rollback. This happens in
   35123 **         function sqlite3PagerRollback().
   35124 **
   35125 **      2. An error occurs while attempting to finalize a journal file
   35126 **         following a commit in function sqlite3PagerCommitPhaseTwo().
   35127 **
   35128 **      3. An error occurs while attempting to write to the journal or
   35129 **         database file in function pagerStress() in order to free up
   35130 **         memory.
   35131 **
   35132 **    In other cases, the error is returned to the b-tree layer. The b-tree
   35133 **    layer then attempts a rollback operation. If the error condition
   35134 **    persists, the pager enters the ERROR state via condition (1) above.
   35135 **
   35136 **    Condition (3) is necessary because it can be triggered by a read-only
   35137 **    statement executed within a transaction. In this case, if the error
   35138 **    code were simply returned to the user, the b-tree layer would not
   35139 **    automatically attempt a rollback, as it assumes that an error in a
   35140 **    read-only statement cannot leave the pager in an internally inconsistent
   35141 **    state.
   35142 **
   35143 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
   35144 **    * There are one or more outstanding references to pages (after the
   35145 **      last reference is dropped the pager should move back to OPEN state).
   35146 **    * The pager is not an in-memory pager.
   35147 **
   35148 **
   35149 ** Notes:
   35150 **
   35151 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
   35152 **     connection is open in WAL mode. A WAL connection is always in one
   35153 **     of the first four states.
   35154 **
   35155 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
   35156 **     state. There are two exceptions: immediately after exclusive-mode has
   35157 **     been turned on (and before any read or write transactions are
   35158 **     executed), and when the pager is leaving the "error state".
   35159 **
   35160 **   * See also: assert_pager_state().
   35161 */
   35162 #define PAGER_OPEN                  0
   35163 #define PAGER_READER                1
   35164 #define PAGER_WRITER_LOCKED         2
   35165 #define PAGER_WRITER_CACHEMOD       3
   35166 #define PAGER_WRITER_DBMOD          4
   35167 #define PAGER_WRITER_FINISHED       5
   35168 #define PAGER_ERROR                 6
   35169 
   35170 /*
   35171 ** The Pager.eLock variable is almost always set to one of the
   35172 ** following locking-states, according to the lock currently held on
   35173 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   35174 ** This variable is kept up to date as locks are taken and released by
   35175 ** the pagerLockDb() and pagerUnlockDb() wrappers.
   35176 **
   35177 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
   35178 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
   35179 ** the operation was successful. In these circumstances pagerLockDb() and
   35180 ** pagerUnlockDb() take a conservative approach - eLock is always updated
   35181 ** when unlocking the file, and only updated when locking the file if the
   35182 ** VFS call is successful. This way, the Pager.eLock variable may be set
   35183 ** to a less exclusive (lower) value than the lock that is actually held
   35184 ** at the system level, but it is never set to a more exclusive value.
   35185 **
   35186 ** This is usually safe. If an xUnlock fails or appears to fail, there may
   35187 ** be a few redundant xLock() calls or a lock may be held for longer than
   35188 ** required, but nothing really goes wrong.
   35189 **
   35190 ** The exception is when the database file is unlocked as the pager moves
   35191 ** from ERROR to OPEN state. At this point there may be a hot-journal file
   35192 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
   35193 ** transition, by the same pager or any other). If the call to xUnlock()
   35194 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
   35195 ** can confuse the call to xCheckReservedLock() call made later as part
   35196 ** of hot-journal detection.
   35197 **
   35198 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
   35199 ** lock held by this process or any others". So xCheckReservedLock may
   35200 ** return true because the caller itself is holding an EXCLUSIVE lock (but
   35201 ** doesn't know it because of a previous error in xUnlock). If this happens
   35202 ** a hot-journal may be mistaken for a journal being created by an active
   35203 ** transaction in another process, causing SQLite to read from the database
   35204 ** without rolling it back.
   35205 **
   35206 ** To work around this, if a call to xUnlock() fails when unlocking the
   35207 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
   35208 ** is only changed back to a real locking state after a successful call
   35209 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
   35210 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
   35211 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
   35212 ** lock on the database file before attempting to roll it back. See function
   35213 ** PagerSharedLock() for more detail.
   35214 **
   35215 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
   35216 ** PAGER_OPEN state.
   35217 */
   35218 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
   35219 
   35220 /*
   35221 ** A macro used for invoking the codec if there is one
   35222 */
   35223 #ifdef SQLITE_HAS_CODEC
   35224 # define CODEC1(P,D,N,X,E) \
   35225     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
   35226 # define CODEC2(P,D,N,X,E,O) \
   35227     if( P->xCodec==0 ){ O=(char*)D; }else \
   35228     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
   35229 #else
   35230 # define CODEC1(P,D,N,X,E)   /* NO-OP */
   35231 # define CODEC2(P,D,N,X,E,O) O=(char*)D
   35232 #endif
   35233 
   35234 /*
   35235 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
   35236 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
   35237 ** This could conceivably cause corruption following a power failure on
   35238 ** such a system. This is currently an undocumented limit.
   35239 */
   35240 #define MAX_SECTOR_SIZE 0x10000
   35241 
   35242 /*
   35243 ** An instance of the following structure is allocated for each active
   35244 ** savepoint and statement transaction in the system. All such structures
   35245 ** are stored in the Pager.aSavepoint[] array, which is allocated and
   35246 ** resized using sqlite3Realloc().
   35247 **
   35248 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
   35249 ** set to 0. If a journal-header is written into the main journal while
   35250 ** the savepoint is active, then iHdrOffset is set to the byte offset
   35251 ** immediately following the last journal record written into the main
   35252 ** journal before the journal-header. This is required during savepoint
   35253 ** rollback (see pagerPlaybackSavepoint()).
   35254 */
   35255 typedef struct PagerSavepoint PagerSavepoint;
   35256 struct PagerSavepoint {
   35257   i64 iOffset;                 /* Starting offset in main journal */
   35258   i64 iHdrOffset;              /* See above */
   35259   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
   35260   Pgno nOrig;                  /* Original number of pages in file */
   35261   Pgno iSubRec;                /* Index of first record in sub-journal */
   35262 #ifndef SQLITE_OMIT_WAL
   35263   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
   35264 #endif
   35265 };
   35266 
   35267 /*
   35268 ** A open page cache is an instance of struct Pager. A description of
   35269 ** some of the more important member variables follows:
   35270 **
   35271 ** eState
   35272 **
   35273 **   The current 'state' of the pager object. See the comment and state
   35274 **   diagram above for a description of the pager state.
   35275 **
   35276 ** eLock
   35277 **
   35278 **   For a real on-disk database, the current lock held on the database file -
   35279 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
   35280 **
   35281 **   For a temporary or in-memory database (neither of which require any
   35282 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
   35283 **   databases always have Pager.exclusiveMode==1, this tricks the pager
   35284 **   logic into thinking that it already has all the locks it will ever
   35285 **   need (and no reason to release them).
   35286 **
   35287 **   In some (obscure) circumstances, this variable may also be set to
   35288 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
   35289 **   details.
   35290 **
   35291 ** changeCountDone
   35292 **
   35293 **   This boolean variable is used to make sure that the change-counter
   35294 **   (the 4-byte header field at byte offset 24 of the database file) is
   35295 **   not updated more often than necessary.
   35296 **
   35297 **   It is set to true when the change-counter field is updated, which
   35298 **   can only happen if an exclusive lock is held on the database file.
   35299 **   It is cleared (set to false) whenever an exclusive lock is
   35300 **   relinquished on the database file. Each time a transaction is committed,
   35301 **   The changeCountDone flag is inspected. If it is true, the work of
   35302 **   updating the change-counter is omitted for the current transaction.
   35303 **
   35304 **   This mechanism means that when running in exclusive mode, a connection
   35305 **   need only update the change-counter once, for the first transaction
   35306 **   committed.
   35307 **
   35308 ** setMaster
   35309 **
   35310 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
   35311 **   (or may not) specify a master-journal name to be written into the
   35312 **   journal file before it is synced to disk.
   35313 **
   35314 **   Whether or not a journal file contains a master-journal pointer affects
   35315 **   the way in which the journal file is finalized after the transaction is
   35316 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
   35317 **   If a journal file does not contain a master-journal pointer, it is
   35318 **   finalized by overwriting the first journal header with zeroes. If
   35319 **   it does contain a master-journal pointer the journal file is finalized
   35320 **   by truncating it to zero bytes, just as if the connection were
   35321 **   running in "journal_mode=truncate" mode.
   35322 **
   35323 **   Journal files that contain master journal pointers cannot be finalized
   35324 **   simply by overwriting the first journal-header with zeroes, as the
   35325 **   master journal pointer could interfere with hot-journal rollback of any
   35326 **   subsequently interrupted transaction that reuses the journal file.
   35327 **
   35328 **   The flag is cleared as soon as the journal file is finalized (either
   35329 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
   35330 **   journal file from being successfully finalized, the setMaster flag
   35331 **   is cleared anyway (and the pager will move to ERROR state).
   35332 **
   35333 ** doNotSpill, doNotSyncSpill
   35334 **
   35335 **   These two boolean variables control the behaviour of cache-spills
   35336 **   (calls made by the pcache module to the pagerStress() routine to
   35337 **   write cached data to the file-system in order to free up memory).
   35338 **
   35339 **   When doNotSpill is non-zero, writing to the database from pagerStress()
   35340 **   is disabled altogether. This is done in a very obscure case that
   35341 **   comes up during savepoint rollback that requires the pcache module
   35342 **   to allocate a new page to prevent the journal file from being written
   35343 **   while it is being traversed by code in pager_playback().
   35344 **
   35345 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
   35346 **   is permitted, but syncing the journal file is not. This flag is set
   35347 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
   35348 **   the database page-size in order to prevent a journal sync from happening
   35349 **   in between the journalling of two pages on the same sector.
   35350 **
   35351 ** subjInMemory
   35352 **
   35353 **   This is a boolean variable. If true, then any required sub-journal
   35354 **   is opened as an in-memory journal file. If false, then in-memory
   35355 **   sub-journals are only used for in-memory pager files.
   35356 **
   35357 **   This variable is updated by the upper layer each time a new
   35358 **   write-transaction is opened.
   35359 **
   35360 ** dbSize, dbOrigSize, dbFileSize
   35361 **
   35362 **   Variable dbSize is set to the number of pages in the database file.
   35363 **   It is valid in PAGER_READER and higher states (all states except for
   35364 **   OPEN and ERROR).
   35365 **
   35366 **   dbSize is set based on the size of the database file, which may be
   35367 **   larger than the size of the database (the value stored at offset
   35368 **   28 of the database header by the btree). If the size of the file
   35369 **   is not an integer multiple of the page-size, the value stored in
   35370 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
   35371 **   Except, any file that is greater than 0 bytes in size is considered
   35372 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
   35373 **   to dbSize==1).
   35374 **
   35375 **   During a write-transaction, if pages with page-numbers greater than
   35376 **   dbSize are modified in the cache, dbSize is updated accordingly.
   35377 **   Similarly, if the database is truncated using PagerTruncateImage(),
   35378 **   dbSize is updated.
   35379 **
   35380 **   Variables dbOrigSize and dbFileSize are valid in states
   35381 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
   35382 **   variable at the start of the transaction. It is used during rollback,
   35383 **   and to determine whether or not pages need to be journalled before
   35384 **   being modified.
   35385 **
   35386 **   Throughout a write-transaction, dbFileSize contains the size of
   35387 **   the file on disk in pages. It is set to a copy of dbSize when the
   35388 **   write-transaction is first opened, and updated when VFS calls are made
   35389 **   to write or truncate the database file on disk.
   35390 **
   35391 **   The only reason the dbFileSize variable is required is to suppress
   35392 **   unnecessary calls to xTruncate() after committing a transaction. If,
   35393 **   when a transaction is committed, the dbFileSize variable indicates
   35394 **   that the database file is larger than the database image (Pager.dbSize),
   35395 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
   35396 **   to measure the database file on disk, and then truncates it if required.
   35397 **   dbFileSize is not used when rolling back a transaction. In this case
   35398 **   pager_truncate() is called unconditionally (which means there may be
   35399 **   a call to xFilesize() that is not strictly required). In either case,
   35400 **   pager_truncate() may cause the file to become smaller or larger.
   35401 **
   35402 ** dbHintSize
   35403 **
   35404 **   The dbHintSize variable is used to limit the number of calls made to
   35405 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
   35406 **
   35407 **   dbHintSize is set to a copy of the dbSize variable when a
   35408 **   write-transaction is opened (at the same time as dbFileSize and
   35409 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
   35410 **   dbHintSize is increased to the number of pages that correspond to the
   35411 **   size-hint passed to the method call. See pager_write_pagelist() for
   35412 **   details.
   35413 **
   35414 ** errCode
   35415 **
   35416 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
   35417 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
   35418 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
   35419 **   sub-codes.
   35420 */
   35421 struct Pager {
   35422   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
   35423   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   35424   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   35425   u8 useJournal;              /* Use a rollback journal on this file */
   35426   u8 noReadlock;              /* Do not bother to obtain readlocks */
   35427   u8 noSync;                  /* Do not sync the journal if true */
   35428   u8 fullSync;                /* Do extra syncs of the journal for robustness */
   35429   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
   35430   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   35431   u8 tempFile;                /* zFilename is a temporary file */
   35432   u8 readOnly;                /* True for a read-only database */
   35433   u8 memDb;                   /* True to inhibit all file I/O */
   35434 
   35435   /**************************************************************************
   35436   ** The following block contains those class members that change during
   35437   ** routine opertion.  Class members not in this block are either fixed
   35438   ** when the pager is first created or else only change when there is a
   35439   ** significant mode change (such as changing the page_size, locking_mode,
   35440   ** or the journal_mode).  From another view, these class members describe
   35441   ** the "state" of the pager, while other class members describe the
   35442   ** "configuration" of the pager.
   35443   */
   35444   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   35445   u8 eLock;                   /* Current lock held on database file */
   35446   u8 changeCountDone;         /* Set after incrementing the change-counter */
   35447   u8 setMaster;               /* True if a m-j name has been written to jrnl */
   35448   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   35449   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
   35450   u8 subjInMemory;            /* True to use in-memory sub-journals */
   35451   Pgno dbSize;                /* Number of pages in the database */
   35452   Pgno dbOrigSize;            /* dbSize before the current transaction */
   35453   Pgno dbFileSize;            /* Number of pages in the database file */
   35454   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
   35455   int errCode;                /* One of several kinds of errors */
   35456   int nRec;                   /* Pages journalled since last j-header written */
   35457   u32 cksumInit;              /* Quasi-random value added to every checksum */
   35458   u32 nSubRec;                /* Number of records written to sub-journal */
   35459   Bitvec *pInJournal;         /* One bit for each page in the database file */
   35460   sqlite3_file *fd;           /* File descriptor for database */
   35461   sqlite3_file *jfd;          /* File descriptor for main journal */
   35462   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
   35463   i64 journalOff;             /* Current write offset in the journal file */
   35464   i64 journalHdr;             /* Byte offset to previous journal header */
   35465   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
   35466   PagerSavepoint *aSavepoint; /* Array of active savepoints */
   35467   int nSavepoint;             /* Number of elements in aSavepoint[] */
   35468   char dbFileVers[16];        /* Changes whenever database file changes */
   35469   /*
   35470   ** End of the routinely-changing class members
   35471   ***************************************************************************/
   35472 
   35473   u16 nExtra;                 /* Add this many bytes to each in-memory page */
   35474   i16 nReserve;               /* Number of unused bytes at end of each page */
   35475   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
   35476   u32 sectorSize;             /* Assumed sector size during rollback */
   35477   int pageSize;               /* Number of bytes in a page */
   35478   Pgno mxPgno;                /* Maximum allowed size of the database */
   35479   i64 journalSizeLimit;       /* Size limit for persistent journal files */
   35480   char *zFilename;            /* Name of the database file */
   35481   char *zJournal;             /* Name of the journal file */
   35482   int (*xBusyHandler)(void*); /* Function to call when busy */
   35483   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
   35484 #ifdef SQLITE_TEST
   35485   int nHit, nMiss;            /* Cache hits and missing */
   35486   int nRead, nWrite;          /* Database pages read/written */
   35487 #endif
   35488   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   35489 #ifdef SQLITE_HAS_CODEC
   35490   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
   35491   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
   35492   void (*xCodecFree)(void*);             /* Destructor for the codec */
   35493   void *pCodec;               /* First argument to xCodec... methods */
   35494 #endif
   35495   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   35496   PCache *pPCache;            /* Pointer to page cache object */
   35497 #ifndef SQLITE_OMIT_WAL
   35498   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
   35499   char *zWal;                 /* File name for write-ahead log */
   35500 #endif
   35501 };
   35502 
   35503 /*
   35504 ** The following global variables hold counters used for
   35505 ** testing purposes only.  These variables do not exist in
   35506 ** a non-testing build.  These variables are not thread-safe.
   35507 */
   35508 #ifdef SQLITE_TEST
   35509 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
   35510 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
   35511 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
   35512 # define PAGER_INCR(v)  v++
   35513 #else
   35514 # define PAGER_INCR(v)
   35515 #endif
   35516 
   35517 
   35518 
   35519 /*
   35520 ** Journal files begin with the following magic string.  The data
   35521 ** was obtained from /dev/random.  It is used only as a sanity check.
   35522 **
   35523 ** Since version 2.8.0, the journal format contains additional sanity
   35524 ** checking information.  If the power fails while the journal is being
   35525 ** written, semi-random garbage data might appear in the journal
   35526 ** file after power is restored.  If an attempt is then made
   35527 ** to roll the journal back, the database could be corrupted.  The additional
   35528 ** sanity checking data is an attempt to discover the garbage in the
   35529 ** journal and ignore it.
   35530 **
   35531 ** The sanity checking information for the new journal format consists
   35532 ** of a 32-bit checksum on each page of data.  The checksum covers both
   35533 ** the page number and the pPager->pageSize bytes of data for the page.
   35534 ** This cksum is initialized to a 32-bit random value that appears in the
   35535 ** journal file right after the header.  The random initializer is important,
   35536 ** because garbage data that appears at the end of a journal is likely
   35537 ** data that was once in other files that have now been deleted.  If the
   35538 ** garbage data came from an obsolete journal file, the checksums might
   35539 ** be correct.  But by initializing the checksum to random value which
   35540 ** is different for every journal, we minimize that risk.
   35541 */
   35542 static const unsigned char aJournalMagic[] = {
   35543   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
   35544 };
   35545 
   35546 /*
   35547 ** The size of the of each page record in the journal is given by
   35548 ** the following macro.
   35549 */
   35550 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
   35551 
   35552 /*
   35553 ** The journal header size for this pager. This is usually the same
   35554 ** size as a single disk sector. See also setSectorSize().
   35555 */
   35556 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
   35557 
   35558 /*
   35559 ** The macro MEMDB is true if we are dealing with an in-memory database.
   35560 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
   35561 ** the value of MEMDB will be a constant and the compiler will optimize
   35562 ** out code that would never execute.
   35563 */
   35564 #ifdef SQLITE_OMIT_MEMORYDB
   35565 # define MEMDB 0
   35566 #else
   35567 # define MEMDB pPager->memDb
   35568 #endif
   35569 
   35570 /*
   35571 ** The maximum legal page number is (2^31 - 1).
   35572 */
   35573 #define PAGER_MAX_PGNO 2147483647
   35574 
   35575 /*
   35576 ** The argument to this macro is a file descriptor (type sqlite3_file*).
   35577 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
   35578 **
   35579 ** This is so that expressions can be written as:
   35580 **
   35581 **   if( isOpen(pPager->jfd) ){ ...
   35582 **
   35583 ** instead of
   35584 **
   35585 **   if( pPager->jfd->pMethods ){ ...
   35586 */
   35587 #define isOpen(pFd) ((pFd)->pMethods)
   35588 
   35589 /*
   35590 ** Return true if this pager uses a write-ahead log instead of the usual
   35591 ** rollback journal. Otherwise false.
   35592 */
   35593 #ifndef SQLITE_OMIT_WAL
   35594 static int pagerUseWal(Pager *pPager){
   35595   return (pPager->pWal!=0);
   35596 }
   35597 #else
   35598 # define pagerUseWal(x) 0
   35599 # define pagerRollbackWal(x) 0
   35600 # define pagerWalFrames(v,w,x,y,z) 0
   35601 # define pagerOpenWalIfPresent(z) SQLITE_OK
   35602 # define pagerBeginReadTransaction(z) SQLITE_OK
   35603 #endif
   35604 
   35605 #ifndef NDEBUG
   35606 /*
   35607 ** Usage:
   35608 **
   35609 **   assert( assert_pager_state(pPager) );
   35610 **
   35611 ** This function runs many asserts to try to find inconsistencies in
   35612 ** the internal state of the Pager object.
   35613 */
   35614 static int assert_pager_state(Pager *p){
   35615   Pager *pPager = p;
   35616 
   35617   /* State must be valid. */
   35618   assert( p->eState==PAGER_OPEN
   35619        || p->eState==PAGER_READER
   35620        || p->eState==PAGER_WRITER_LOCKED
   35621        || p->eState==PAGER_WRITER_CACHEMOD
   35622        || p->eState==PAGER_WRITER_DBMOD
   35623        || p->eState==PAGER_WRITER_FINISHED
   35624        || p->eState==PAGER_ERROR
   35625   );
   35626 
   35627   /* Regardless of the current state, a temp-file connection always behaves
   35628   ** as if it has an exclusive lock on the database file. It never updates
   35629   ** the change-counter field, so the changeCountDone flag is always set.
   35630   */
   35631   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   35632   assert( p->tempFile==0 || pPager->changeCountDone );
   35633 
   35634   /* If the useJournal flag is clear, the journal-mode must be "OFF".
   35635   ** And if the journal-mode is "OFF", the journal file must not be open.
   35636   */
   35637   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   35638   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
   35639 
   35640   /* Check that MEMDB implies noSync. And an in-memory journal. Since
   35641   ** this means an in-memory pager performs no IO at all, it cannot encounter
   35642   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
   35643   ** a journal file. (although the in-memory journal implementation may
   35644   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
   35645   ** is therefore not possible for an in-memory pager to enter the ERROR
   35646   ** state.
   35647   */
   35648   if( MEMDB ){
   35649     assert( p->noSync );
   35650     assert( p->journalMode==PAGER_JOURNALMODE_OFF
   35651          || p->journalMode==PAGER_JOURNALMODE_MEMORY
   35652     );
   35653     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
   35654     assert( pagerUseWal(p)==0 );
   35655   }
   35656 
   35657   /* If changeCountDone is set, a RESERVED lock or greater must be held
   35658   ** on the file.
   35659   */
   35660   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
   35661   assert( p->eLock!=PENDING_LOCK );
   35662 
   35663   switch( p->eState ){
   35664     case PAGER_OPEN:
   35665       assert( !MEMDB );
   35666       assert( pPager->errCode==SQLITE_OK );
   35667       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
   35668       break;
   35669 
   35670     case PAGER_READER:
   35671       assert( pPager->errCode==SQLITE_OK );
   35672       assert( p->eLock!=UNKNOWN_LOCK );
   35673       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
   35674       break;
   35675 
   35676     case PAGER_WRITER_LOCKED:
   35677       assert( p->eLock!=UNKNOWN_LOCK );
   35678       assert( pPager->errCode==SQLITE_OK );
   35679       if( !pagerUseWal(pPager) ){
   35680         assert( p->eLock>=RESERVED_LOCK );
   35681       }
   35682       assert( pPager->dbSize==pPager->dbOrigSize );
   35683       assert( pPager->dbOrigSize==pPager->dbFileSize );
   35684       assert( pPager->dbOrigSize==pPager->dbHintSize );
   35685       assert( pPager->setMaster==0 );
   35686       break;
   35687 
   35688     case PAGER_WRITER_CACHEMOD:
   35689       assert( p->eLock!=UNKNOWN_LOCK );
   35690       assert( pPager->errCode==SQLITE_OK );
   35691       if( !pagerUseWal(pPager) ){
   35692         /* It is possible that if journal_mode=wal here that neither the
   35693         ** journal file nor the WAL file are open. This happens during
   35694         ** a rollback transaction that switches from journal_mode=off
   35695         ** to journal_mode=wal.
   35696         */
   35697         assert( p->eLock>=RESERVED_LOCK );
   35698         assert( isOpen(p->jfd)
   35699              || p->journalMode==PAGER_JOURNALMODE_OFF
   35700              || p->journalMode==PAGER_JOURNALMODE_WAL
   35701         );
   35702       }
   35703       assert( pPager->dbOrigSize==pPager->dbFileSize );
   35704       assert( pPager->dbOrigSize==pPager->dbHintSize );
   35705       break;
   35706 
   35707     case PAGER_WRITER_DBMOD:
   35708       assert( p->eLock==EXCLUSIVE_LOCK );
   35709       assert( pPager->errCode==SQLITE_OK );
   35710       assert( !pagerUseWal(pPager) );
   35711       assert( p->eLock>=EXCLUSIVE_LOCK );
   35712       assert( isOpen(p->jfd)
   35713            || p->journalMode==PAGER_JOURNALMODE_OFF
   35714            || p->journalMode==PAGER_JOURNALMODE_WAL
   35715       );
   35716       assert( pPager->dbOrigSize<=pPager->dbHintSize );
   35717       break;
   35718 
   35719     case PAGER_WRITER_FINISHED:
   35720       assert( p->eLock==EXCLUSIVE_LOCK );
   35721       assert( pPager->errCode==SQLITE_OK );
   35722       assert( !pagerUseWal(pPager) );
   35723       assert( isOpen(p->jfd)
   35724            || p->journalMode==PAGER_JOURNALMODE_OFF
   35725            || p->journalMode==PAGER_JOURNALMODE_WAL
   35726       );
   35727       break;
   35728 
   35729     case PAGER_ERROR:
   35730       /* There must be at least one outstanding reference to the pager if
   35731       ** in ERROR state. Otherwise the pager should have already dropped
   35732       ** back to OPEN state.
   35733       */
   35734       assert( pPager->errCode!=SQLITE_OK );
   35735       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
   35736       break;
   35737   }
   35738 
   35739   return 1;
   35740 }
   35741 #endif /* ifndef NDEBUG */
   35742 
   35743 #ifdef SQLITE_DEBUG
   35744 /*
   35745 ** Return a pointer to a human readable string in a static buffer
   35746 ** containing the state of the Pager object passed as an argument. This
   35747 ** is intended to be used within debuggers. For example, as an alternative
   35748 ** to "print *pPager" in gdb:
   35749 **
   35750 ** (gdb) printf "%s", print_pager_state(pPager)
   35751 */
   35752 static char *print_pager_state(Pager *p){
   35753   static char zRet[1024];
   35754 
   35755   sqlite3_snprintf(1024, zRet,
   35756       "Filename:      %s\n"
   35757       "State:         %s errCode=%d\n"
   35758       "Lock:          %s\n"
   35759       "Locking mode:  locking_mode=%s\n"
   35760       "Journal mode:  journal_mode=%s\n"
   35761       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
   35762       "Journal:       journalOff=%lld journalHdr=%lld\n"
   35763       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
   35764       , p->zFilename
   35765       , p->eState==PAGER_OPEN            ? "OPEN" :
   35766         p->eState==PAGER_READER          ? "READER" :
   35767         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
   35768         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
   35769         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
   35770         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
   35771         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
   35772       , (int)p->errCode
   35773       , p->eLock==NO_LOCK         ? "NO_LOCK" :
   35774         p->eLock==RESERVED_LOCK   ? "RESERVED" :
   35775         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
   35776         p->eLock==SHARED_LOCK     ? "SHARED" :
   35777         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
   35778       , p->exclusiveMode ? "exclusive" : "normal"
   35779       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
   35780         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
   35781         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
   35782         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
   35783         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
   35784         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
   35785       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
   35786       , p->journalOff, p->journalHdr
   35787       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
   35788   );
   35789 
   35790   return zRet;
   35791 }
   35792 #endif
   35793 
   35794 /*
   35795 ** Return true if it is necessary to write page *pPg into the sub-journal.
   35796 ** A page needs to be written into the sub-journal if there exists one
   35797 ** or more open savepoints for which:
   35798 **
   35799 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
   35800 **   * The bit corresponding to the page-number is not set in
   35801 **     PagerSavepoint.pInSavepoint.
   35802 */
   35803 static int subjRequiresPage(PgHdr *pPg){
   35804   Pgno pgno = pPg->pgno;
   35805   Pager *pPager = pPg->pPager;
   35806   int i;
   35807   for(i=0; i<pPager->nSavepoint; i++){
   35808     PagerSavepoint *p = &pPager->aSavepoint[i];
   35809     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
   35810       return 1;
   35811     }
   35812   }
   35813   return 0;
   35814 }
   35815 
   35816 /*
   35817 ** Return true if the page is already in the journal file.
   35818 */
   35819 static int pageInJournal(PgHdr *pPg){
   35820   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
   35821 }
   35822 
   35823 /*
   35824 ** Read a 32-bit integer from the given file descriptor.  Store the integer
   35825 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
   35826 ** error code is something goes wrong.
   35827 **
   35828 ** All values are stored on disk as big-endian.
   35829 */
   35830 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
   35831   unsigned char ac[4];
   35832   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
   35833   if( rc==SQLITE_OK ){
   35834     *pRes = sqlite3Get4byte(ac);
   35835   }
   35836   return rc;
   35837 }
   35838 
   35839 /*
   35840 ** Write a 32-bit integer into a string buffer in big-endian byte order.
   35841 */
   35842 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
   35843 
   35844 
   35845 /*
   35846 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
   35847 ** on success or an error code is something goes wrong.
   35848 */
   35849 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
   35850   char ac[4];
   35851   put32bits(ac, val);
   35852   return sqlite3OsWrite(fd, ac, 4, offset);
   35853 }
   35854 
   35855 /*
   35856 ** Unlock the database file to level eLock, which must be either NO_LOCK
   35857 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
   35858 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
   35859 **
   35860 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   35861 ** called, do not modify it. See the comment above the #define of
   35862 ** UNKNOWN_LOCK for an explanation of this.
   35863 */
   35864 static int pagerUnlockDb(Pager *pPager, int eLock){
   35865   int rc = SQLITE_OK;
   35866 
   35867   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
   35868   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
   35869   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
   35870   if( isOpen(pPager->fd) ){
   35871     assert( pPager->eLock>=eLock );
   35872     rc = sqlite3OsUnlock(pPager->fd, eLock);
   35873     if( pPager->eLock!=UNKNOWN_LOCK ){
   35874       pPager->eLock = (u8)eLock;
   35875     }
   35876     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   35877   }
   35878   return rc;
   35879 }
   35880 
   35881 /*
   35882 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
   35883 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
   35884 ** Pager.eLock variable to the new locking state.
   35885 **
   35886 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
   35887 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
   35888 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
   35889 ** of this.
   35890 */
   35891 static int pagerLockDb(Pager *pPager, int eLock){
   35892   int rc = SQLITE_OK;
   35893 
   35894   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
   35895   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
   35896     rc = sqlite3OsLock(pPager->fd, eLock);
   35897     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
   35898       pPager->eLock = (u8)eLock;
   35899       IOTRACE(("LOCK %p %d\n", pPager, eLock))
   35900     }
   35901   }
   35902   return rc;
   35903 }
   35904 
   35905 /*
   35906 ** This function determines whether or not the atomic-write optimization
   35907 ** can be used with this pager. The optimization can be used if:
   35908 **
   35909 **  (a) the value returned by OsDeviceCharacteristics() indicates that
   35910 **      a database page may be written atomically, and
   35911 **  (b) the value returned by OsSectorSize() is less than or equal
   35912 **      to the page size.
   35913 **
   35914 ** The optimization is also always enabled for temporary files. It is
   35915 ** an error to call this function if pPager is opened on an in-memory
   35916 ** database.
   35917 **
   35918 ** If the optimization cannot be used, 0 is returned. If it can be used,
   35919 ** then the value returned is the size of the journal file when it
   35920 ** contains rollback data for exactly one page.
   35921 */
   35922 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   35923 static int jrnlBufferSize(Pager *pPager){
   35924   assert( !MEMDB );
   35925   if( !pPager->tempFile ){
   35926     int dc;                           /* Device characteristics */
   35927     int nSector;                      /* Sector size */
   35928     int szPage;                       /* Page size */
   35929 
   35930     assert( isOpen(pPager->fd) );
   35931     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
   35932     nSector = pPager->sectorSize;
   35933     szPage = pPager->pageSize;
   35934 
   35935     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   35936     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   35937     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
   35938       return 0;
   35939     }
   35940   }
   35941 
   35942   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
   35943 }
   35944 #endif
   35945 
   35946 /*
   35947 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
   35948 ** on the cache using a hash function.  This is used for testing
   35949 ** and debugging only.
   35950 */
   35951 #ifdef SQLITE_CHECK_PAGES
   35952 /*
   35953 ** Return a 32-bit hash of the page data for pPage.
   35954 */
   35955 static u32 pager_datahash(int nByte, unsigned char *pData){
   35956   u32 hash = 0;
   35957   int i;
   35958   for(i=0; i<nByte; i++){
   35959     hash = (hash*1039) + pData[i];
   35960   }
   35961   return hash;
   35962 }
   35963 static u32 pager_pagehash(PgHdr *pPage){
   35964   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
   35965 }
   35966 static void pager_set_pagehash(PgHdr *pPage){
   35967   pPage->pageHash = pager_pagehash(pPage);
   35968 }
   35969 
   35970 /*
   35971 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
   35972 ** is defined, and NDEBUG is not defined, an assert() statement checks
   35973 ** that the page is either dirty or still matches the calculated page-hash.
   35974 */
   35975 #define CHECK_PAGE(x) checkPage(x)
   35976 static void checkPage(PgHdr *pPg){
   35977   Pager *pPager = pPg->pPager;
   35978   assert( pPager->eState!=PAGER_ERROR );
   35979   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
   35980 }
   35981 
   35982 #else
   35983 #define pager_datahash(X,Y)  0
   35984 #define pager_pagehash(X)  0
   35985 #define pager_set_pagehash(X)
   35986 #define CHECK_PAGE(x)
   35987 #endif  /* SQLITE_CHECK_PAGES */
   35988 
   35989 /*
   35990 ** When this is called the journal file for pager pPager must be open.
   35991 ** This function attempts to read a master journal file name from the
   35992 ** end of the file and, if successful, copies it into memory supplied
   35993 ** by the caller. See comments above writeMasterJournal() for the format
   35994 ** used to store a master journal file name at the end of a journal file.
   35995 **
   35996 ** zMaster must point to a buffer of at least nMaster bytes allocated by
   35997 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
   35998 ** enough space to write the master journal name). If the master journal
   35999 ** name in the journal is longer than nMaster bytes (including a
   36000 ** nul-terminator), then this is handled as if no master journal name
   36001 ** were present in the journal.
   36002 **
   36003 ** If a master journal file name is present at the end of the journal
   36004 ** file, then it is copied into the buffer pointed to by zMaster. A
   36005 ** nul-terminator byte is appended to the buffer following the master
   36006 ** journal file name.
   36007 **
   36008 ** If it is determined that no master journal file name is present
   36009 ** zMaster[0] is set to 0 and SQLITE_OK returned.
   36010 **
   36011 ** If an error occurs while reading from the journal file, an SQLite
   36012 ** error code is returned.
   36013 */
   36014 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
   36015   int rc;                    /* Return code */
   36016   u32 len;                   /* Length in bytes of master journal name */
   36017   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   36018   u32 cksum;                 /* MJ checksum value read from journal */
   36019   u32 u;                     /* Unsigned loop counter */
   36020   unsigned char aMagic[8];   /* A buffer to hold the magic header */
   36021   zMaster[0] = '\0';
   36022 
   36023   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   36024    || szJ<16
   36025    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
   36026    || len>=nMaster
   36027    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
   36028    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   36029    || memcmp(aMagic, aJournalMagic, 8)
   36030    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
   36031   ){
   36032     return rc;
   36033   }
   36034 
   36035   /* See if the checksum matches the master journal name */
   36036   for(u=0; u<len; u++){
   36037     cksum -= zMaster[u];
   36038   }
   36039   if( cksum ){
   36040     /* If the checksum doesn't add up, then one or more of the disk sectors
   36041     ** containing the master journal filename is corrupted. This means
   36042     ** definitely roll back, so just return SQLITE_OK and report a (nul)
   36043     ** master-journal filename.
   36044     */
   36045     len = 0;
   36046   }
   36047   zMaster[len] = '\0';
   36048 
   36049   return SQLITE_OK;
   36050 }
   36051 
   36052 /*
   36053 ** Return the offset of the sector boundary at or immediately
   36054 ** following the value in pPager->journalOff, assuming a sector
   36055 ** size of pPager->sectorSize bytes.
   36056 **
   36057 ** i.e for a sector size of 512:
   36058 **
   36059 **   Pager.journalOff          Return value
   36060 **   ---------------------------------------
   36061 **   0                         0
   36062 **   512                       512
   36063 **   100                       512
   36064 **   2000                      2048
   36065 **
   36066 */
   36067 static i64 journalHdrOffset(Pager *pPager){
   36068   i64 offset = 0;
   36069   i64 c = pPager->journalOff;
   36070   if( c ){
   36071     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
   36072   }
   36073   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
   36074   assert( offset>=c );
   36075   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
   36076   return offset;
   36077 }
   36078 
   36079 /*
   36080 ** The journal file must be open when this function is called.
   36081 **
   36082 ** This function is a no-op if the journal file has not been written to
   36083 ** within the current transaction (i.e. if Pager.journalOff==0).
   36084 **
   36085 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
   36086 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
   36087 ** zero the 28-byte header at the start of the journal file. In either case,
   36088 ** if the pager is not in no-sync mode, sync the journal file immediately
   36089 ** after writing or truncating it.
   36090 **
   36091 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
   36092 ** following the truncation or zeroing described above the size of the
   36093 ** journal file in bytes is larger than this value, then truncate the
   36094 ** journal file to Pager.journalSizeLimit bytes. The journal file does
   36095 ** not need to be synced following this operation.
   36096 **
   36097 ** If an IO error occurs, abandon processing and return the IO error code.
   36098 ** Otherwise, return SQLITE_OK.
   36099 */
   36100 static int zeroJournalHdr(Pager *pPager, int doTruncate){
   36101   int rc = SQLITE_OK;                               /* Return code */
   36102   assert( isOpen(pPager->jfd) );
   36103   if( pPager->journalOff ){
   36104     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
   36105 
   36106     IOTRACE(("JZEROHDR %p\n", pPager))
   36107     if( doTruncate || iLimit==0 ){
   36108       rc = sqlite3OsTruncate(pPager->jfd, 0);
   36109     }else{
   36110       static const char zeroHdr[28] = {0};
   36111       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
   36112     }
   36113     if( rc==SQLITE_OK && !pPager->noSync ){
   36114       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
   36115     }
   36116 
   36117     /* At this point the transaction is committed but the write lock
   36118     ** is still held on the file. If there is a size limit configured for
   36119     ** the persistent journal and the journal file currently consumes more
   36120     ** space than that limit allows for, truncate it now. There is no need
   36121     ** to sync the file following this operation.
   36122     */
   36123     if( rc==SQLITE_OK && iLimit>0 ){
   36124       i64 sz;
   36125       rc = sqlite3OsFileSize(pPager->jfd, &sz);
   36126       if( rc==SQLITE_OK && sz>iLimit ){
   36127         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
   36128       }
   36129     }
   36130   }
   36131   return rc;
   36132 }
   36133 
   36134 /*
   36135 ** The journal file must be open when this routine is called. A journal
   36136 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
   36137 ** current location.
   36138 **
   36139 ** The format for the journal header is as follows:
   36140 ** - 8 bytes: Magic identifying journal format.
   36141 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
   36142 ** - 4 bytes: Random number used for page hash.
   36143 ** - 4 bytes: Initial database page count.
   36144 ** - 4 bytes: Sector size used by the process that wrote this journal.
   36145 ** - 4 bytes: Database page size.
   36146 **
   36147 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
   36148 */
   36149 static int writeJournalHdr(Pager *pPager){
   36150   int rc = SQLITE_OK;                 /* Return code */
   36151   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
   36152   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
   36153   u32 nWrite;                         /* Bytes of header sector written */
   36154   int ii;                             /* Loop counter */
   36155 
   36156   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   36157 
   36158   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
   36159     nHeader = JOURNAL_HDR_SZ(pPager);
   36160   }
   36161 
   36162   /* If there are active savepoints and any of them were created
   36163   ** since the most recent journal header was written, update the
   36164   ** PagerSavepoint.iHdrOffset fields now.
   36165   */
   36166   for(ii=0; ii<pPager->nSavepoint; ii++){
   36167     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
   36168       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
   36169     }
   36170   }
   36171 
   36172   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
   36173 
   36174   /*
   36175   ** Write the nRec Field - the number of page records that follow this
   36176   ** journal header. Normally, zero is written to this value at this time.
   36177   ** After the records are added to the journal (and the journal synced,
   36178   ** if in full-sync mode), the zero is overwritten with the true number
   36179   ** of records (see syncJournal()).
   36180   **
   36181   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
   36182   ** reading the journal this value tells SQLite to assume that the
   36183   ** rest of the journal file contains valid page records. This assumption
   36184   ** is dangerous, as if a failure occurred whilst writing to the journal
   36185   ** file it may contain some garbage data. There are two scenarios
   36186   ** where this risk can be ignored:
   36187   **
   36188   **   * When the pager is in no-sync mode. Corruption can follow a
   36189   **     power failure in this case anyway.
   36190   **
   36191   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
   36192   **     that garbage data is never appended to the journal file.
   36193   */
   36194   assert( isOpen(pPager->fd) || pPager->noSync );
   36195   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   36196    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   36197   ){
   36198     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   36199     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
   36200   }else{
   36201     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   36202   }
   36203 
   36204   /* The random check-hash initialiser */
   36205   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   36206   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   36207   /* The initial database size */
   36208   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
   36209   /* The assumed sector size for this process */
   36210   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
   36211 
   36212   /* The page size */
   36213   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
   36214 
   36215   /* Initializing the tail of the buffer is not necessary.  Everything
   36216   ** works find if the following memset() is omitted.  But initializing
   36217   ** the memory prevents valgrind from complaining, so we are willing to
   36218   ** take the performance hit.
   36219   */
   36220   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
   36221          nHeader-(sizeof(aJournalMagic)+20));
   36222 
   36223   /* In theory, it is only necessary to write the 28 bytes that the
   36224   ** journal header consumes to the journal file here. Then increment the
   36225   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   36226   ** record is written to the following sector (leaving a gap in the file
   36227   ** that will be implicitly filled in by the OS).
   36228   **
   36229   ** However it has been discovered that on some systems this pattern can
   36230   ** be significantly slower than contiguously writing data to the file,
   36231   ** even if that means explicitly writing data to the block of
   36232   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
   36233   ** is done.
   36234   **
   36235   ** The loop is required here in case the sector-size is larger than the
   36236   ** database page size. Since the zHeader buffer is only Pager.pageSize
   36237   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   36238   ** to populate the entire journal header sector.
   36239   */
   36240   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
   36241     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
   36242     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
   36243     assert( pPager->journalHdr <= pPager->journalOff );
   36244     pPager->journalOff += nHeader;
   36245   }
   36246 
   36247   return rc;
   36248 }
   36249 
   36250 /*
   36251 ** The journal file must be open when this is called. A journal header file
   36252 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
   36253 ** file. The current location in the journal file is given by
   36254 ** pPager->journalOff. See comments above function writeJournalHdr() for
   36255 ** a description of the journal header format.
   36256 **
   36257 ** If the header is read successfully, *pNRec is set to the number of
   36258 ** page records following this header and *pDbSize is set to the size of the
   36259 ** database before the transaction began, in pages. Also, pPager->cksumInit
   36260 ** is set to the value read from the journal header. SQLITE_OK is returned
   36261 ** in this case.
   36262 **
   36263 ** If the journal header file appears to be corrupted, SQLITE_DONE is
   36264 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
   36265 ** cannot be read from the journal file an error code is returned.
   36266 */
   36267 static int readJournalHdr(
   36268   Pager *pPager,               /* Pager object */
   36269   int isHot,
   36270   i64 journalSize,             /* Size of the open journal file in bytes */
   36271   u32 *pNRec,                  /* OUT: Value read from the nRec field */
   36272   u32 *pDbSize                 /* OUT: Value of original database size field */
   36273 ){
   36274   int rc;                      /* Return code */
   36275   unsigned char aMagic[8];     /* A buffer to hold the magic header */
   36276   i64 iHdrOff;                 /* Offset of journal header being read */
   36277 
   36278   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
   36279 
   36280   /* Advance Pager.journalOff to the start of the next sector. If the
   36281   ** journal file is too small for there to be a header stored at this
   36282   ** point, return SQLITE_DONE.
   36283   */
   36284   pPager->journalOff = journalHdrOffset(pPager);
   36285   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
   36286     return SQLITE_DONE;
   36287   }
   36288   iHdrOff = pPager->journalOff;
   36289 
   36290   /* Read in the first 8 bytes of the journal header. If they do not match
   36291   ** the  magic string found at the start of each journal header, return
   36292   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
   36293   ** proceed.
   36294   */
   36295   if( isHot || iHdrOff!=pPager->journalHdr ){
   36296     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
   36297     if( rc ){
   36298       return rc;
   36299     }
   36300     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
   36301       return SQLITE_DONE;
   36302     }
   36303   }
   36304 
   36305   /* Read the first three 32-bit fields of the journal header: The nRec
   36306   ** field, the checksum-initializer and the database size at the start
   36307   ** of the transaction. Return an error code if anything goes wrong.
   36308   */
   36309   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
   36310    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   36311    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
   36312   ){
   36313     return rc;
   36314   }
   36315 
   36316   if( pPager->journalOff==0 ){
   36317     u32 iPageSize;               /* Page-size field of journal header */
   36318     u32 iSectorSize;             /* Sector-size field of journal header */
   36319 
   36320     /* Read the page-size and sector-size journal header fields. */
   36321     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
   36322      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
   36323     ){
   36324       return rc;
   36325     }
   36326 
   36327     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
   36328     ** journal header to zero. In this case, assume that the Pager.pageSize
   36329     ** variable is already set to the correct page size.
   36330     */
   36331     if( iPageSize==0 ){
   36332       iPageSize = pPager->pageSize;
   36333     }
   36334 
   36335     /* Check that the values read from the page-size and sector-size fields
   36336     ** are within range. To be 'in range', both values need to be a power
   36337     ** of two greater than or equal to 512 or 32, and not greater than their
   36338     ** respective compile time maximum limits.
   36339     */
   36340     if( iPageSize<512                  || iSectorSize<32
   36341      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
   36342      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
   36343     ){
   36344       /* If the either the page-size or sector-size in the journal-header is
   36345       ** invalid, then the process that wrote the journal-header must have
   36346       ** crashed before the header was synced. In this case stop reading
   36347       ** the journal file here.
   36348       */
   36349       return SQLITE_DONE;
   36350     }
   36351 
   36352     /* Update the page-size to match the value read from the journal.
   36353     ** Use a testcase() macro to make sure that malloc failure within
   36354     ** PagerSetPagesize() is tested.
   36355     */
   36356     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
   36357     testcase( rc!=SQLITE_OK );
   36358 
   36359     /* Update the assumed sector-size to match the value used by
   36360     ** the process that created this journal. If this journal was
   36361     ** created by a process other than this one, then this routine
   36362     ** is being called from within pager_playback(). The local value
   36363     ** of Pager.sectorSize is restored at the end of that routine.
   36364     */
   36365     pPager->sectorSize = iSectorSize;
   36366   }
   36367 
   36368   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
   36369   return rc;
   36370 }
   36371 
   36372 
   36373 /*
   36374 ** Write the supplied master journal name into the journal file for pager
   36375 ** pPager at the current location. The master journal name must be the last
   36376 ** thing written to a journal file. If the pager is in full-sync mode, the
   36377 ** journal file descriptor is advanced to the next sector boundary before
   36378 ** anything is written. The format is:
   36379 **
   36380 **   + 4 bytes: PAGER_MJ_PGNO.
   36381 **   + N bytes: Master journal filename in utf-8.
   36382 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
   36383 **   + 4 bytes: Master journal name checksum.
   36384 **   + 8 bytes: aJournalMagic[].
   36385 **
   36386 ** The master journal page checksum is the sum of the bytes in the master
   36387 ** journal name, where each byte is interpreted as a signed 8-bit integer.
   36388 **
   36389 ** If zMaster is a NULL pointer (occurs for a single database transaction),
   36390 ** this call is a no-op.
   36391 */
   36392 static int writeMasterJournal(Pager *pPager, const char *zMaster){
   36393   int rc;                          /* Return code */
   36394   int nMaster;                     /* Length of string zMaster */
   36395   i64 iHdrOff;                     /* Offset of header in journal file */
   36396   i64 jrnlSize;                    /* Size of journal file on disk */
   36397   u32 cksum = 0;                   /* Checksum of string zMaster */
   36398 
   36399   assert( pPager->setMaster==0 );
   36400   assert( !pagerUseWal(pPager) );
   36401 
   36402   if( !zMaster
   36403    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   36404    || pPager->journalMode==PAGER_JOURNALMODE_OFF
   36405   ){
   36406     return SQLITE_OK;
   36407   }
   36408   pPager->setMaster = 1;
   36409   assert( isOpen(pPager->jfd) );
   36410   assert( pPager->journalHdr <= pPager->journalOff );
   36411 
   36412   /* Calculate the length in bytes and the checksum of zMaster */
   36413   for(nMaster=0; zMaster[nMaster]; nMaster++){
   36414     cksum += zMaster[nMaster];
   36415   }
   36416 
   36417   /* If in full-sync mode, advance to the next disk sector before writing
   36418   ** the master journal name. This is in case the previous page written to
   36419   ** the journal has already been synced.
   36420   */
   36421   if( pPager->fullSync ){
   36422     pPager->journalOff = journalHdrOffset(pPager);
   36423   }
   36424   iHdrOff = pPager->journalOff;
   36425 
   36426   /* Write the master journal data to the end of the journal file. If
   36427   ** an error occurs, return the error code to the caller.
   36428   */
   36429   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
   36430    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
   36431    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
   36432    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
   36433    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
   36434   ){
   36435     return rc;
   36436   }
   36437   pPager->journalOff += (nMaster+20);
   36438 
   36439   /* If the pager is in peristent-journal mode, then the physical
   36440   ** journal-file may extend past the end of the master-journal name
   36441   ** and 8 bytes of magic data just written to the file. This is
   36442   ** dangerous because the code to rollback a hot-journal file
   36443   ** will not be able to find the master-journal name to determine
   36444   ** whether or not the journal is hot.
   36445   **
   36446   ** Easiest thing to do in this scenario is to truncate the journal
   36447   ** file to the required size.
   36448   */
   36449   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   36450    && jrnlSize>pPager->journalOff
   36451   ){
   36452     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
   36453   }
   36454   return rc;
   36455 }
   36456 
   36457 /*
   36458 ** Find a page in the hash table given its page number. Return
   36459 ** a pointer to the page or NULL if the requested page is not
   36460 ** already in memory.
   36461 */
   36462 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
   36463   PgHdr *p;                         /* Return value */
   36464 
   36465   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
   36466   ** fail, since no attempt to allocate dynamic memory will be made.
   36467   */
   36468   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
   36469   return p;
   36470 }
   36471 
   36472 /*
   36473 ** Discard the entire contents of the in-memory page-cache.
   36474 */
   36475 static void pager_reset(Pager *pPager){
   36476   sqlite3BackupRestart(pPager->pBackup);
   36477   sqlite3PcacheClear(pPager->pPCache);
   36478 }
   36479 
   36480 /*
   36481 ** Free all structures in the Pager.aSavepoint[] array and set both
   36482 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
   36483 ** if it is open and the pager is not in exclusive mode.
   36484 */
   36485 static void releaseAllSavepoints(Pager *pPager){
   36486   int ii;               /* Iterator for looping through Pager.aSavepoint */
   36487   for(ii=0; ii<pPager->nSavepoint; ii++){
   36488     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   36489   }
   36490   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
   36491     sqlite3OsClose(pPager->sjfd);
   36492   }
   36493   sqlite3_free(pPager->aSavepoint);
   36494   pPager->aSavepoint = 0;
   36495   pPager->nSavepoint = 0;
   36496   pPager->nSubRec = 0;
   36497 }
   36498 
   36499 /*
   36500 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
   36501 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
   36502 ** or SQLITE_NOMEM if a malloc failure occurs.
   36503 */
   36504 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
   36505   int ii;                   /* Loop counter */
   36506   int rc = SQLITE_OK;       /* Result code */
   36507 
   36508   for(ii=0; ii<pPager->nSavepoint; ii++){
   36509     PagerSavepoint *p = &pPager->aSavepoint[ii];
   36510     if( pgno<=p->nOrig ){
   36511       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
   36512       testcase( rc==SQLITE_NOMEM );
   36513       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   36514     }
   36515   }
   36516   return rc;
   36517 }
   36518 
   36519 /*
   36520 ** This function is a no-op if the pager is in exclusive mode and not
   36521 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
   36522 ** state.
   36523 **
   36524 ** If the pager is not in exclusive-access mode, the database file is
   36525 ** completely unlocked. If the file is unlocked and the file-system does
   36526 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
   36527 ** closed (if it is open).
   36528 **
   36529 ** If the pager is in ERROR state when this function is called, the
   36530 ** contents of the pager cache are discarded before switching back to
   36531 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
   36532 ** or not, any journal file left in the file-system will be treated
   36533 ** as a hot-journal and rolled back the next time a read-transaction
   36534 ** is opened (by this or by any other connection).
   36535 */
   36536 static void pager_unlock(Pager *pPager){
   36537 
   36538   assert( pPager->eState==PAGER_READER
   36539        || pPager->eState==PAGER_OPEN
   36540        || pPager->eState==PAGER_ERROR
   36541   );
   36542 
   36543   sqlite3BitvecDestroy(pPager->pInJournal);
   36544   pPager->pInJournal = 0;
   36545   releaseAllSavepoints(pPager);
   36546 
   36547   if( pagerUseWal(pPager) ){
   36548     assert( !isOpen(pPager->jfd) );
   36549     sqlite3WalEndReadTransaction(pPager->pWal);
   36550     pPager->eState = PAGER_OPEN;
   36551   }else if( !pPager->exclusiveMode ){
   36552     int rc;                       /* Error code returned by pagerUnlockDb() */
   36553     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
   36554 
   36555     /* If the operating system support deletion of open files, then
   36556     ** close the journal file when dropping the database lock.  Otherwise
   36557     ** another connection with journal_mode=delete might delete the file
   36558     ** out from under us.
   36559     */
   36560     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
   36561     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
   36562     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
   36563     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
   36564     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   36565     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
   36566     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
   36567      || 1!=(pPager->journalMode & 5)
   36568     ){
   36569       sqlite3OsClose(pPager->jfd);
   36570     }
   36571 
   36572     /* If the pager is in the ERROR state and the call to unlock the database
   36573     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
   36574     ** above the #define for UNKNOWN_LOCK for an explanation of why this
   36575     ** is necessary.
   36576     */
   36577     rc = pagerUnlockDb(pPager, NO_LOCK);
   36578     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
   36579       pPager->eLock = UNKNOWN_LOCK;
   36580     }
   36581 
   36582     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
   36583     ** without clearing the error code. This is intentional - the error
   36584     ** code is cleared and the cache reset in the block below.
   36585     */
   36586     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
   36587     pPager->changeCountDone = 0;
   36588     pPager->eState = PAGER_OPEN;
   36589   }
   36590 
   36591   /* If Pager.errCode is set, the contents of the pager cache cannot be
   36592   ** trusted. Now that there are no outstanding references to the pager,
   36593   ** it can safely move back to PAGER_OPEN state. This happens in both
   36594   ** normal and exclusive-locking mode.
   36595   */
   36596   if( pPager->errCode ){
   36597     assert( !MEMDB );
   36598     pager_reset(pPager);
   36599     pPager->changeCountDone = pPager->tempFile;
   36600     pPager->eState = PAGER_OPEN;
   36601     pPager->errCode = SQLITE_OK;
   36602   }
   36603 
   36604   pPager->journalOff = 0;
   36605   pPager->journalHdr = 0;
   36606   pPager->setMaster = 0;
   36607 }
   36608 
   36609 /*
   36610 ** This function is called whenever an IOERR or FULL error that requires
   36611 ** the pager to transition into the ERROR state may ahve occurred.
   36612 ** The first argument is a pointer to the pager structure, the second
   36613 ** the error-code about to be returned by a pager API function. The
   36614 ** value returned is a copy of the second argument to this function.
   36615 **
   36616 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
   36617 ** IOERR sub-codes, the pager enters the ERROR state and the error code
   36618 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
   36619 ** all major API calls on the Pager will immediately return Pager.errCode.
   36620 **
   36621 ** The ERROR state indicates that the contents of the pager-cache
   36622 ** cannot be trusted. This state can be cleared by completely discarding
   36623 ** the contents of the pager-cache. If a transaction was active when
   36624 ** the persistent error occurred, then the rollback journal may need
   36625 ** to be replayed to restore the contents of the database file (as if
   36626 ** it were a hot-journal).
   36627 */
   36628 static int pager_error(Pager *pPager, int rc){
   36629   int rc2 = rc & 0xff;
   36630   assert( rc==SQLITE_OK || !MEMDB );
   36631   assert(
   36632        pPager->errCode==SQLITE_FULL ||
   36633        pPager->errCode==SQLITE_OK ||
   36634        (pPager->errCode & 0xff)==SQLITE_IOERR
   36635   );
   36636   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
   36637     pPager->errCode = rc;
   36638     pPager->eState = PAGER_ERROR;
   36639   }
   36640   return rc;
   36641 }
   36642 
   36643 /*
   36644 ** This routine ends a transaction. A transaction is usually ended by
   36645 ** either a COMMIT or a ROLLBACK operation. This routine may be called
   36646 ** after rollback of a hot-journal, or if an error occurs while opening
   36647 ** the journal file or writing the very first journal-header of a
   36648 ** database transaction.
   36649 **
   36650 ** This routine is never called in PAGER_ERROR state. If it is called
   36651 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
   36652 ** exclusive than a RESERVED lock, it is a no-op.
   36653 **
   36654 ** Otherwise, any active savepoints are released.
   36655 **
   36656 ** If the journal file is open, then it is "finalized". Once a journal
   36657 ** file has been finalized it is not possible to use it to roll back a
   36658 ** transaction. Nor will it be considered to be a hot-journal by this
   36659 ** or any other database connection. Exactly how a journal is finalized
   36660 ** depends on whether or not the pager is running in exclusive mode and
   36661 ** the current journal-mode (Pager.journalMode value), as follows:
   36662 **
   36663 **   journalMode==MEMORY
   36664 **     Journal file descriptor is simply closed. This destroys an
   36665 **     in-memory journal.
   36666 **
   36667 **   journalMode==TRUNCATE
   36668 **     Journal file is truncated to zero bytes in size.
   36669 **
   36670 **   journalMode==PERSIST
   36671 **     The first 28 bytes of the journal file are zeroed. This invalidates
   36672 **     the first journal header in the file, and hence the entire journal
   36673 **     file. An invalid journal file cannot be rolled back.
   36674 **
   36675 **   journalMode==DELETE
   36676 **     The journal file is closed and deleted using sqlite3OsDelete().
   36677 **
   36678 **     If the pager is running in exclusive mode, this method of finalizing
   36679 **     the journal file is never used. Instead, if the journalMode is
   36680 **     DELETE and the pager is in exclusive mode, the method described under
   36681 **     journalMode==PERSIST is used instead.
   36682 **
   36683 ** After the journal is finalized, the pager moves to PAGER_READER state.
   36684 ** If running in non-exclusive rollback mode, the lock on the file is
   36685 ** downgraded to a SHARED_LOCK.
   36686 **
   36687 ** SQLITE_OK is returned if no error occurs. If an error occurs during
   36688 ** any of the IO operations to finalize the journal file or unlock the
   36689 ** database then the IO error code is returned to the user. If the
   36690 ** operation to finalize the journal file fails, then the code still
   36691 ** tries to unlock the database file if not in exclusive mode. If the
   36692 ** unlock operation fails as well, then the first error code related
   36693 ** to the first error encountered (the journal finalization one) is
   36694 ** returned.
   36695 */
   36696 static int pager_end_transaction(Pager *pPager, int hasMaster){
   36697   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   36698   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
   36699 
   36700   /* Do nothing if the pager does not have an open write transaction
   36701   ** or at least a RESERVED lock. This function may be called when there
   36702   ** is no write-transaction active but a RESERVED or greater lock is
   36703   ** held under two circumstances:
   36704   **
   36705   **   1. After a successful hot-journal rollback, it is called with
   36706   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   36707   **
   36708   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   36709   **      lock switches back to locking_mode=normal and then executes a
   36710   **      read-transaction, this function is called with eState==PAGER_READER
   36711   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   36712   */
   36713   assert( assert_pager_state(pPager) );
   36714   assert( pPager->eState!=PAGER_ERROR );
   36715   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
   36716     return SQLITE_OK;
   36717   }
   36718 
   36719   releaseAllSavepoints(pPager);
   36720   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
   36721   if( isOpen(pPager->jfd) ){
   36722     assert( !pagerUseWal(pPager) );
   36723 
   36724     /* Finalize the journal file. */
   36725     if( sqlite3IsMemJournal(pPager->jfd) ){
   36726       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
   36727       sqlite3OsClose(pPager->jfd);
   36728     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
   36729       if( pPager->journalOff==0 ){
   36730         rc = SQLITE_OK;
   36731       }else{
   36732         rc = sqlite3OsTruncate(pPager->jfd, 0);
   36733       }
   36734       pPager->journalOff = 0;
   36735     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   36736       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
   36737     ){
   36738       rc = zeroJournalHdr(pPager, hasMaster);
   36739       pPager->journalOff = 0;
   36740     }else{
   36741       /* This branch may be executed with Pager.journalMode==MEMORY if
   36742       ** a hot-journal was just rolled back. In this case the journal
   36743       ** file should be closed and deleted. If this connection writes to
   36744       ** the database file, it will do so using an in-memory journal.
   36745       */
   36746       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
   36747            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
   36748            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   36749       );
   36750       sqlite3OsClose(pPager->jfd);
   36751       if( !pPager->tempFile ){
   36752         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   36753       }
   36754     }
   36755   }
   36756 
   36757 #ifdef SQLITE_CHECK_PAGES
   36758   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
   36759   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
   36760     PgHdr *p = pager_lookup(pPager, 1);
   36761     if( p ){
   36762       p->pageHash = 0;
   36763       sqlite3PagerUnref(p);
   36764     }
   36765   }
   36766 #endif
   36767 
   36768   sqlite3BitvecDestroy(pPager->pInJournal);
   36769   pPager->pInJournal = 0;
   36770   pPager->nRec = 0;
   36771   sqlite3PcacheCleanAll(pPager->pPCache);
   36772   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
   36773 
   36774   if( pagerUseWal(pPager) ){
   36775     /* Drop the WAL write-lock, if any. Also, if the connection was in
   36776     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
   36777     ** lock held on the database file.
   36778     */
   36779     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
   36780     assert( rc2==SQLITE_OK );
   36781   }
   36782   if( !pPager->exclusiveMode
   36783    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   36784   ){
   36785     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
   36786     pPager->changeCountDone = 0;
   36787   }
   36788   pPager->eState = PAGER_READER;
   36789   pPager->setMaster = 0;
   36790 
   36791   return (rc==SQLITE_OK?rc2:rc);
   36792 }
   36793 
   36794 /*
   36795 ** Execute a rollback if a transaction is active and unlock the
   36796 ** database file.
   36797 **
   36798 ** If the pager has already entered the ERROR state, do not attempt
   36799 ** the rollback at this time. Instead, pager_unlock() is called. The
   36800 ** call to pager_unlock() will discard all in-memory pages, unlock
   36801 ** the database file and move the pager back to OPEN state. If this
   36802 ** means that there is a hot-journal left in the file-system, the next
   36803 ** connection to obtain a shared lock on the pager (which may be this one)
   36804 ** will roll it back.
   36805 **
   36806 ** If the pager has not already entered the ERROR state, but an IO or
   36807 ** malloc error occurs during a rollback, then this will itself cause
   36808 ** the pager to enter the ERROR state. Which will be cleared by the
   36809 ** call to pager_unlock(), as described above.
   36810 */
   36811 static void pagerUnlockAndRollback(Pager *pPager){
   36812   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
   36813     assert( assert_pager_state(pPager) );
   36814     if( pPager->eState>=PAGER_WRITER_LOCKED ){
   36815       sqlite3BeginBenignMalloc();
   36816       sqlite3PagerRollback(pPager);
   36817       sqlite3EndBenignMalloc();
   36818     }else if( !pPager->exclusiveMode ){
   36819       assert( pPager->eState==PAGER_READER );
   36820       pager_end_transaction(pPager, 0);
   36821     }
   36822   }
   36823   pager_unlock(pPager);
   36824 }
   36825 
   36826 /*
   36827 ** Parameter aData must point to a buffer of pPager->pageSize bytes
   36828 ** of data. Compute and return a checksum based ont the contents of the
   36829 ** page of data and the current value of pPager->cksumInit.
   36830 **
   36831 ** This is not a real checksum. It is really just the sum of the
   36832 ** random initial value (pPager->cksumInit) and every 200th byte
   36833 ** of the page data, starting with byte offset (pPager->pageSize%200).
   36834 ** Each byte is interpreted as an 8-bit unsigned integer.
   36835 **
   36836 ** Changing the formula used to compute this checksum results in an
   36837 ** incompatible journal file format.
   36838 **
   36839 ** If journal corruption occurs due to a power failure, the most likely
   36840 ** scenario is that one end or the other of the record will be changed.
   36841 ** It is much less likely that the two ends of the journal record will be
   36842 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
   36843 ** though fast and simple, catches the mostly likely kind of corruption.
   36844 */
   36845 static u32 pager_cksum(Pager *pPager, const u8 *aData){
   36846   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
   36847   int i = pPager->pageSize-200;          /* Loop counter */
   36848   while( i>0 ){
   36849     cksum += aData[i];
   36850     i -= 200;
   36851   }
   36852   return cksum;
   36853 }
   36854 
   36855 /*
   36856 ** Report the current page size and number of reserved bytes back
   36857 ** to the codec.
   36858 */
   36859 #ifdef SQLITE_HAS_CODEC
   36860 static void pagerReportSize(Pager *pPager){
   36861   if( pPager->xCodecSizeChng ){
   36862     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
   36863                            (int)pPager->nReserve);
   36864   }
   36865 }
   36866 #else
   36867 # define pagerReportSize(X)     /* No-op if we do not support a codec */
   36868 #endif
   36869 
   36870 /*
   36871 ** Read a single page from either the journal file (if isMainJrnl==1) or
   36872 ** from the sub-journal (if isMainJrnl==0) and playback that page.
   36873 ** The page begins at offset *pOffset into the file. The *pOffset
   36874 ** value is increased to the start of the next page in the journal.
   36875 **
   36876 ** The main rollback journal uses checksums - the statement journal does
   36877 ** not.
   36878 **
   36879 ** If the page number of the page record read from the (sub-)journal file
   36880 ** is greater than the current value of Pager.dbSize, then playback is
   36881 ** skipped and SQLITE_OK is returned.
   36882 **
   36883 ** If pDone is not NULL, then it is a record of pages that have already
   36884 ** been played back.  If the page at *pOffset has already been played back
   36885 ** (if the corresponding pDone bit is set) then skip the playback.
   36886 ** Make sure the pDone bit corresponding to the *pOffset page is set
   36887 ** prior to returning.
   36888 **
   36889 ** If the page record is successfully read from the (sub-)journal file
   36890 ** and played back, then SQLITE_OK is returned. If an IO error occurs
   36891 ** while reading the record from the (sub-)journal file or while writing
   36892 ** to the database file, then the IO error code is returned. If data
   36893 ** is successfully read from the (sub-)journal file but appears to be
   36894 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
   36895 ** two circumstances:
   36896 **
   36897 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
   36898 **   * If the record is being rolled back from the main journal file
   36899 **     and the checksum field does not match the record content.
   36900 **
   36901 ** Neither of these two scenarios are possible during a savepoint rollback.
   36902 **
   36903 ** If this is a savepoint rollback, then memory may have to be dynamically
   36904 ** allocated by this function. If this is the case and an allocation fails,
   36905 ** SQLITE_NOMEM is returned.
   36906 */
   36907 static int pager_playback_one_page(
   36908   Pager *pPager,                /* The pager being played back */
   36909   i64 *pOffset,                 /* Offset of record to playback */
   36910   Bitvec *pDone,                /* Bitvec of pages already played back */
   36911   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
   36912   int isSavepnt                 /* True for a savepoint rollback */
   36913 ){
   36914   int rc;
   36915   PgHdr *pPg;                   /* An existing page in the cache */
   36916   Pgno pgno;                    /* The page number of a page in journal */
   36917   u32 cksum;                    /* Checksum used for sanity checking */
   36918   char *aData;                  /* Temporary storage for the page */
   36919   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   36920   int isSynced;                 /* True if journal page is synced */
   36921 
   36922   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   36923   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
   36924   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
   36925   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
   36926 
   36927   aData = pPager->pTmpSpace;
   36928   assert( aData );         /* Temp storage must have already been allocated */
   36929   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
   36930 
   36931   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   36932   ** or savepoint rollback done at the request of the caller) or this is
   36933   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   36934   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
   36935   ** only reads from the main journal, not the sub-journal.
   36936   */
   36937   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
   36938        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
   36939   );
   36940   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
   36941 
   36942   /* Read the page number and page data from the journal or sub-journal
   36943   ** file. Return an error code to the caller if an IO error occurs.
   36944   */
   36945   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
   36946   rc = read32bits(jfd, *pOffset, &pgno);
   36947   if( rc!=SQLITE_OK ) return rc;
   36948   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
   36949   if( rc!=SQLITE_OK ) return rc;
   36950   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
   36951 
   36952   /* Sanity checking on the page.  This is more important that I originally
   36953   ** thought.  If a power failure occurs while the journal is being written,
   36954   ** it could cause invalid data to be written into the journal.  We need to
   36955   ** detect this invalid data (with high probability) and ignore it.
   36956   */
   36957   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
   36958     assert( !isSavepnt );
   36959     return SQLITE_DONE;
   36960   }
   36961   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
   36962     return SQLITE_OK;
   36963   }
   36964   if( isMainJrnl ){
   36965     rc = read32bits(jfd, (*pOffset)-4, &cksum);
   36966     if( rc ) return rc;
   36967     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
   36968       return SQLITE_DONE;
   36969     }
   36970   }
   36971 
   36972   /* If this page has already been played by before during the current
   36973   ** rollback, then don't bother to play it back again.
   36974   */
   36975   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
   36976     return rc;
   36977   }
   36978 
   36979   /* When playing back page 1, restore the nReserve setting
   36980   */
   36981   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
   36982     pPager->nReserve = ((u8*)aData)[20];
   36983     pagerReportSize(pPager);
   36984   }
   36985 
   36986   /* If the pager is in CACHEMOD state, then there must be a copy of this
   36987   ** page in the pager cache. In this case just update the pager cache,
   36988   ** not the database file. The page is left marked dirty in this case.
   36989   **
   36990   ** An exception to the above rule: If the database is in no-sync mode
   36991   ** and a page is moved during an incremental vacuum then the page may
   36992   ** not be in the pager cache. Later: if a malloc() or IO error occurs
   36993   ** during a Movepage() call, then the page may not be in the cache
   36994   ** either. So the condition described in the above paragraph is not
   36995   ** assert()able.
   36996   **
   36997   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
   36998   ** pager cache if it exists and the main file. The page is then marked
   36999   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   37000   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   37001   ** if the pager is in OPEN state.
   37002   **
   37003   ** Ticket #1171:  The statement journal might contain page content that is
   37004   ** different from the page content at the start of the transaction.
   37005   ** This occurs when a page is changed prior to the start of a statement
   37006   ** then changed again within the statement.  When rolling back such a
   37007   ** statement we must not write to the original database unless we know
   37008   ** for certain that original page contents are synced into the main rollback
   37009   ** journal.  Otherwise, a power loss might leave modified data in the
   37010   ** database file without an entry in the rollback journal that can
   37011   ** restore the database to its original form.  Two conditions must be
   37012   ** met before writing to the database files. (1) the database must be
   37013   ** locked.  (2) we know that the original page content is fully synced
   37014   ** in the main journal either because the page is not in cache or else
   37015   ** the page is marked as needSync==0.
   37016   **
   37017   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
   37018   ** is possible to fail a statement on a database that does not yet exist.
   37019   ** Do not attempt to write if database file has never been opened.
   37020   */
   37021   if( pagerUseWal(pPager) ){
   37022     pPg = 0;
   37023   }else{
   37024     pPg = pager_lookup(pPager, pgno);
   37025   }
   37026   assert( pPg || !MEMDB );
   37027   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
   37028   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
   37029            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
   37030            (isMainJrnl?"main-journal":"sub-journal")
   37031   ));
   37032   if( isMainJrnl ){
   37033     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
   37034   }else{
   37035     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
   37036   }
   37037   if( isOpen(pPager->fd)
   37038    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   37039    && isSynced
   37040   ){
   37041     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
   37042     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
   37043     assert( !pagerUseWal(pPager) );
   37044     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
   37045     if( pgno>pPager->dbFileSize ){
   37046       pPager->dbFileSize = pgno;
   37047     }
   37048     if( pPager->pBackup ){
   37049       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
   37050       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
   37051       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
   37052     }
   37053   }else if( !isMainJrnl && pPg==0 ){
   37054     /* If this is a rollback of a savepoint and data was not written to
   37055     ** the database and the page is not in-memory, there is a potential
   37056     ** problem. When the page is next fetched by the b-tree layer, it
   37057     ** will be read from the database file, which may or may not be
   37058     ** current.
   37059     **
   37060     ** There are a couple of different ways this can happen. All are quite
   37061     ** obscure. When running in synchronous mode, this can only happen
   37062     ** if the page is on the free-list at the start of the transaction, then
   37063     ** populated, then moved using sqlite3PagerMovepage().
   37064     **
   37065     ** The solution is to add an in-memory page to the cache containing
   37066     ** the data just read from the sub-journal. Mark the page as dirty
   37067     ** and if the pager requires a journal-sync, then mark the page as
   37068     ** requiring a journal-sync before it is written.
   37069     */
   37070     assert( isSavepnt );
   37071     assert( pPager->doNotSpill==0 );
   37072     pPager->doNotSpill++;
   37073     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
   37074     assert( pPager->doNotSpill==1 );
   37075     pPager->doNotSpill--;
   37076     if( rc!=SQLITE_OK ) return rc;
   37077     pPg->flags &= ~PGHDR_NEED_READ;
   37078     sqlite3PcacheMakeDirty(pPg);
   37079   }
   37080   if( pPg ){
   37081     /* No page should ever be explicitly rolled back that is in use, except
   37082     ** for page 1 which is held in use in order to keep the lock on the
   37083     ** database active. However such a page may be rolled back as a result
   37084     ** of an internal error resulting in an automatic call to
   37085     ** sqlite3PagerRollback().
   37086     */
   37087     void *pData;
   37088     pData = pPg->pData;
   37089     memcpy(pData, (u8*)aData, pPager->pageSize);
   37090     pPager->xReiniter(pPg);
   37091     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
   37092       /* If the contents of this page were just restored from the main
   37093       ** journal file, then its content must be as they were when the
   37094       ** transaction was first opened. In this case we can mark the page
   37095       ** as clean, since there will be no need to write it out to the
   37096       ** database.
   37097       **
   37098       ** There is one exception to this rule. If the page is being rolled
   37099       ** back as part of a savepoint (or statement) rollback from an
   37100       ** unsynced portion of the main journal file, then it is not safe
   37101       ** to mark the page as clean. This is because marking the page as
   37102       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
   37103       ** already in the journal file (recorded in Pager.pInJournal) and
   37104       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
   37105       ** again within this transaction, it will be marked as dirty but
   37106       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
   37107       ** be written out into the database file before its journal file
   37108       ** segment is synced. If a crash occurs during or following this,
   37109       ** database corruption may ensue.
   37110       */
   37111       assert( !pagerUseWal(pPager) );
   37112       sqlite3PcacheMakeClean(pPg);
   37113     }
   37114     pager_set_pagehash(pPg);
   37115 
   37116     /* If this was page 1, then restore the value of Pager.dbFileVers.
   37117     ** Do this before any decoding. */
   37118     if( pgno==1 ){
   37119       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
   37120     }
   37121 
   37122     /* Decode the page just read from disk */
   37123     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
   37124     sqlite3PcacheRelease(pPg);
   37125   }
   37126   return rc;
   37127 }
   37128 
   37129 /*
   37130 ** Parameter zMaster is the name of a master journal file. A single journal
   37131 ** file that referred to the master journal file has just been rolled back.
   37132 ** This routine checks if it is possible to delete the master journal file,
   37133 ** and does so if it is.
   37134 **
   37135 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
   37136 ** available for use within this function.
   37137 **
   37138 ** When a master journal file is created, it is populated with the names
   37139 ** of all of its child journals, one after another, formatted as utf-8
   37140 ** encoded text. The end of each child journal file is marked with a
   37141 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
   37142 ** file for a transaction involving two databases might be:
   37143 **
   37144 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
   37145 **
   37146 ** A master journal file may only be deleted once all of its child
   37147 ** journals have been rolled back.
   37148 **
   37149 ** This function reads the contents of the master-journal file into
   37150 ** memory and loops through each of the child journal names. For
   37151 ** each child journal, it checks if:
   37152 **
   37153 **   * if the child journal exists, and if so
   37154 **   * if the child journal contains a reference to master journal
   37155 **     file zMaster
   37156 **
   37157 ** If a child journal can be found that matches both of the criteria
   37158 ** above, this function returns without doing anything. Otherwise, if
   37159 ** no such child journal can be found, file zMaster is deleted from
   37160 ** the file-system using sqlite3OsDelete().
   37161 **
   37162 ** If an IO error within this function, an error code is returned. This
   37163 ** function allocates memory by calling sqlite3Malloc(). If an allocation
   37164 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
   37165 ** occur, SQLITE_OK is returned.
   37166 **
   37167 ** TODO: This function allocates a single block of memory to load
   37168 ** the entire contents of the master journal file. This could be
   37169 ** a couple of kilobytes or so - potentially larger than the page
   37170 ** size.
   37171 */
   37172 static int pager_delmaster(Pager *pPager, const char *zMaster){
   37173   sqlite3_vfs *pVfs = pPager->pVfs;
   37174   int rc;                   /* Return code */
   37175   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
   37176   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
   37177   char *zMasterJournal = 0; /* Contents of master journal file */
   37178   i64 nMasterJournal;       /* Size of master journal file */
   37179   char *zJournal;           /* Pointer to one journal within MJ file */
   37180   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
   37181   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
   37182 
   37183   /* Allocate space for both the pJournal and pMaster file descriptors.
   37184   ** If successful, open the master journal file for reading.
   37185   */
   37186   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
   37187   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
   37188   if( !pMaster ){
   37189     rc = SQLITE_NOMEM;
   37190   }else{
   37191     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
   37192     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
   37193   }
   37194   if( rc!=SQLITE_OK ) goto delmaster_out;
   37195 
   37196   /* Load the entire master journal file into space obtained from
   37197   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
   37198   ** sufficient space (in zMasterPtr) to hold the names of master
   37199   ** journal files extracted from regular rollback-journals.
   37200   */
   37201   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
   37202   if( rc!=SQLITE_OK ) goto delmaster_out;
   37203   nMasterPtr = pVfs->mxPathname+1;
   37204   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
   37205   if( !zMasterJournal ){
   37206     rc = SQLITE_NOMEM;
   37207     goto delmaster_out;
   37208   }
   37209   zMasterPtr = &zMasterJournal[nMasterJournal+1];
   37210   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
   37211   if( rc!=SQLITE_OK ) goto delmaster_out;
   37212   zMasterJournal[nMasterJournal] = 0;
   37213 
   37214   zJournal = zMasterJournal;
   37215   while( (zJournal-zMasterJournal)<nMasterJournal ){
   37216     int exists;
   37217     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
   37218     if( rc!=SQLITE_OK ){
   37219       goto delmaster_out;
   37220     }
   37221     if( exists ){
   37222       /* One of the journals pointed to by the master journal exists.
   37223       ** Open it and check if it points at the master journal. If
   37224       ** so, return without deleting the master journal file.
   37225       */
   37226       int c;
   37227       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
   37228       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
   37229       if( rc!=SQLITE_OK ){
   37230         goto delmaster_out;
   37231       }
   37232 
   37233       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
   37234       sqlite3OsClose(pJournal);
   37235       if( rc!=SQLITE_OK ){
   37236         goto delmaster_out;
   37237       }
   37238 
   37239       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
   37240       if( c ){
   37241         /* We have a match. Do not delete the master journal file. */
   37242         goto delmaster_out;
   37243       }
   37244     }
   37245     zJournal += (sqlite3Strlen30(zJournal)+1);
   37246   }
   37247 
   37248   sqlite3OsClose(pMaster);
   37249   rc = sqlite3OsDelete(pVfs, zMaster, 0);
   37250 
   37251 delmaster_out:
   37252   sqlite3_free(zMasterJournal);
   37253   if( pMaster ){
   37254     sqlite3OsClose(pMaster);
   37255     assert( !isOpen(pJournal) );
   37256     sqlite3_free(pMaster);
   37257   }
   37258   return rc;
   37259 }
   37260 
   37261 
   37262 /*
   37263 ** This function is used to change the actual size of the database
   37264 ** file in the file-system. This only happens when committing a transaction,
   37265 ** or rolling back a transaction (including rolling back a hot-journal).
   37266 **
   37267 ** If the main database file is not open, or the pager is not in either
   37268 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
   37269 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
   37270 ** If the file on disk is currently larger than nPage pages, then use the VFS
   37271 ** xTruncate() method to truncate it.
   37272 **
   37273 ** Or, it might might be the case that the file on disk is smaller than
   37274 ** nPage pages. Some operating system implementations can get confused if
   37275 ** you try to truncate a file to some size that is larger than it
   37276 ** currently is, so detect this case and write a single zero byte to
   37277 ** the end of the new file instead.
   37278 **
   37279 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
   37280 ** the database file, return the error code to the caller.
   37281 */
   37282 static int pager_truncate(Pager *pPager, Pgno nPage){
   37283   int rc = SQLITE_OK;
   37284   assert( pPager->eState!=PAGER_ERROR );
   37285   assert( pPager->eState!=PAGER_READER );
   37286 
   37287   if( isOpen(pPager->fd)
   37288    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   37289   ){
   37290     i64 currentSize, newSize;
   37291     assert( pPager->eLock==EXCLUSIVE_LOCK );
   37292     /* TODO: Is it safe to use Pager.dbFileSize here? */
   37293     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
   37294     newSize = pPager->pageSize*(i64)nPage;
   37295     if( rc==SQLITE_OK && currentSize!=newSize ){
   37296       if( currentSize>newSize ){
   37297         rc = sqlite3OsTruncate(pPager->fd, newSize);
   37298       }else{
   37299         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
   37300       }
   37301       if( rc==SQLITE_OK ){
   37302         pPager->dbFileSize = nPage;
   37303       }
   37304     }
   37305   }
   37306   return rc;
   37307 }
   37308 
   37309 /*
   37310 ** Set the value of the Pager.sectorSize variable for the given
   37311 ** pager based on the value returned by the xSectorSize method
   37312 ** of the open database file. The sector size will be used used
   37313 ** to determine the size and alignment of journal header and
   37314 ** master journal pointers within created journal files.
   37315 **
   37316 ** For temporary files the effective sector size is always 512 bytes.
   37317 **
   37318 ** Otherwise, for non-temporary files, the effective sector size is
   37319 ** the value returned by the xSectorSize() method rounded up to 32 if
   37320 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
   37321 ** is greater than MAX_SECTOR_SIZE.
   37322 */
   37323 static void setSectorSize(Pager *pPager){
   37324   assert( isOpen(pPager->fd) || pPager->tempFile );
   37325 
   37326   if( !pPager->tempFile ){
   37327     /* Sector size doesn't matter for temporary files. Also, the file
   37328     ** may not have been opened yet, in which case the OsSectorSize()
   37329     ** call will segfault.
   37330     */
   37331     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
   37332   }
   37333   if( pPager->sectorSize<32 ){
   37334     pPager->sectorSize = 512;
   37335   }
   37336   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
   37337     assert( MAX_SECTOR_SIZE>=512 );
   37338     pPager->sectorSize = MAX_SECTOR_SIZE;
   37339   }
   37340 }
   37341 
   37342 /*
   37343 ** Playback the journal and thus restore the database file to
   37344 ** the state it was in before we started making changes.
   37345 **
   37346 ** The journal file format is as follows:
   37347 **
   37348 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
   37349 **  (2)  4 byte big-endian integer which is the number of valid page records
   37350 **       in the journal.  If this value is 0xffffffff, then compute the
   37351 **       number of page records from the journal size.
   37352 **  (3)  4 byte big-endian integer which is the initial value for the
   37353 **       sanity checksum.
   37354 **  (4)  4 byte integer which is the number of pages to truncate the
   37355 **       database to during a rollback.
   37356 **  (5)  4 byte big-endian integer which is the sector size.  The header
   37357 **       is this many bytes in size.
   37358 **  (6)  4 byte big-endian integer which is the page size.
   37359 **  (7)  zero padding out to the next sector size.
   37360 **  (8)  Zero or more pages instances, each as follows:
   37361 **        +  4 byte page number.
   37362 **        +  pPager->pageSize bytes of data.
   37363 **        +  4 byte checksum
   37364 **
   37365 ** When we speak of the journal header, we mean the first 7 items above.
   37366 ** Each entry in the journal is an instance of the 8th item.
   37367 **
   37368 ** Call the value from the second bullet "nRec".  nRec is the number of
   37369 ** valid page entries in the journal.  In most cases, you can compute the
   37370 ** value of nRec from the size of the journal file.  But if a power
   37371 ** failure occurred while the journal was being written, it could be the
   37372 ** case that the size of the journal file had already been increased but
   37373 ** the extra entries had not yet made it safely to disk.  In such a case,
   37374 ** the value of nRec computed from the file size would be too large.  For
   37375 ** that reason, we always use the nRec value in the header.
   37376 **
   37377 ** If the nRec value is 0xffffffff it means that nRec should be computed
   37378 ** from the file size.  This value is used when the user selects the
   37379 ** no-sync option for the journal.  A power failure could lead to corruption
   37380 ** in this case.  But for things like temporary table (which will be
   37381 ** deleted when the power is restored) we don't care.
   37382 **
   37383 ** If the file opened as the journal file is not a well-formed
   37384 ** journal file then all pages up to the first corrupted page are rolled
   37385 ** back (or no pages if the journal header is corrupted). The journal file
   37386 ** is then deleted and SQLITE_OK returned, just as if no corruption had
   37387 ** been encountered.
   37388 **
   37389 ** If an I/O or malloc() error occurs, the journal-file is not deleted
   37390 ** and an error code is returned.
   37391 **
   37392 ** The isHot parameter indicates that we are trying to rollback a journal
   37393 ** that might be a hot journal.  Or, it could be that the journal is
   37394 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
   37395 ** If the journal really is hot, reset the pager cache prior rolling
   37396 ** back any content.  If the journal is merely persistent, no reset is
   37397 ** needed.
   37398 */
   37399 static int pager_playback(Pager *pPager, int isHot){
   37400   sqlite3_vfs *pVfs = pPager->pVfs;
   37401   i64 szJ;                 /* Size of the journal file in bytes */
   37402   u32 nRec;                /* Number of Records in the journal */
   37403   u32 u;                   /* Unsigned loop counter */
   37404   Pgno mxPg = 0;           /* Size of the original file in pages */
   37405   int rc;                  /* Result code of a subroutine */
   37406   int res = 1;             /* Value returned by sqlite3OsAccess() */
   37407   char *zMaster = 0;       /* Name of master journal file if any */
   37408   int needPagerReset;      /* True to reset page prior to first page rollback */
   37409 
   37410   /* Figure out how many records are in the journal.  Abort early if
   37411   ** the journal is empty.
   37412   */
   37413   assert( isOpen(pPager->jfd) );
   37414   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
   37415   if( rc!=SQLITE_OK ){
   37416     goto end_playback;
   37417   }
   37418 
   37419   /* Read the master journal name from the journal, if it is present.
   37420   ** If a master journal file name is specified, but the file is not
   37421   ** present on disk, then the journal is not hot and does not need to be
   37422   ** played back.
   37423   **
   37424   ** TODO: Technically the following is an error because it assumes that
   37425   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
   37426   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
   37427   **  mxPathname is 512, which is the same as the minimum allowable value
   37428   ** for pageSize.
   37429   */
   37430   zMaster = pPager->pTmpSpace;
   37431   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   37432   if( rc==SQLITE_OK && zMaster[0] ){
   37433     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   37434   }
   37435   zMaster = 0;
   37436   if( rc!=SQLITE_OK || !res ){
   37437     goto end_playback;
   37438   }
   37439   pPager->journalOff = 0;
   37440   needPagerReset = isHot;
   37441 
   37442   /* This loop terminates either when a readJournalHdr() or
   37443   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
   37444   ** occurs.
   37445   */
   37446   while( 1 ){
   37447     /* Read the next journal header from the journal file.  If there are
   37448     ** not enough bytes left in the journal file for a complete header, or
   37449     ** it is corrupted, then a process must have failed while writing it.
   37450     ** This indicates nothing more needs to be rolled back.
   37451     */
   37452     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
   37453     if( rc!=SQLITE_OK ){
   37454       if( rc==SQLITE_DONE ){
   37455         rc = SQLITE_OK;
   37456       }
   37457       goto end_playback;
   37458     }
   37459 
   37460     /* If nRec is 0xffffffff, then this journal was created by a process
   37461     ** working in no-sync mode. This means that the rest of the journal
   37462     ** file consists of pages, there are no more journal headers. Compute
   37463     ** the value of nRec based on this assumption.
   37464     */
   37465     if( nRec==0xffffffff ){
   37466       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
   37467       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
   37468     }
   37469 
   37470     /* If nRec is 0 and this rollback is of a transaction created by this
   37471     ** process and if this is the final header in the journal, then it means
   37472     ** that this part of the journal was being filled but has not yet been
   37473     ** synced to disk.  Compute the number of pages based on the remaining
   37474     ** size of the file.
   37475     **
   37476     ** The third term of the test was added to fix ticket #2565.
   37477     ** When rolling back a hot journal, nRec==0 always means that the next
   37478     ** chunk of the journal contains zero pages to be rolled back.  But
   37479     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
   37480     ** the journal, it means that the journal might contain additional
   37481     ** pages that need to be rolled back and that the number of pages
   37482     ** should be computed based on the journal file size.
   37483     */
   37484     if( nRec==0 && !isHot &&
   37485         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
   37486       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
   37487     }
   37488 
   37489     /* If this is the first header read from the journal, truncate the
   37490     ** database file back to its original size.
   37491     */
   37492     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
   37493       rc = pager_truncate(pPager, mxPg);
   37494       if( rc!=SQLITE_OK ){
   37495         goto end_playback;
   37496       }
   37497       pPager->dbSize = mxPg;
   37498     }
   37499 
   37500     /* Copy original pages out of the journal and back into the
   37501     ** database file and/or page cache.
   37502     */
   37503     for(u=0; u<nRec; u++){
   37504       if( needPagerReset ){
   37505         pager_reset(pPager);
   37506         needPagerReset = 0;
   37507       }
   37508       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
   37509       if( rc!=SQLITE_OK ){
   37510         if( rc==SQLITE_DONE ){
   37511           rc = SQLITE_OK;
   37512           pPager->journalOff = szJ;
   37513           break;
   37514         }else if( rc==SQLITE_IOERR_SHORT_READ ){
   37515           /* If the journal has been truncated, simply stop reading and
   37516           ** processing the journal. This might happen if the journal was
   37517           ** not completely written and synced prior to a crash.  In that
   37518           ** case, the database should have never been written in the
   37519           ** first place so it is OK to simply abandon the rollback. */
   37520           rc = SQLITE_OK;
   37521           goto end_playback;
   37522         }else{
   37523           /* If we are unable to rollback, quit and return the error
   37524           ** code.  This will cause the pager to enter the error state
   37525           ** so that no further harm will be done.  Perhaps the next
   37526           ** process to come along will be able to rollback the database.
   37527           */
   37528           goto end_playback;
   37529         }
   37530       }
   37531     }
   37532   }
   37533   /*NOTREACHED*/
   37534   assert( 0 );
   37535 
   37536 end_playback:
   37537   /* Following a rollback, the database file should be back in its original
   37538   ** state prior to the start of the transaction, so invoke the
   37539   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
   37540   ** assertion that the transaction counter was modified.
   37541   */
   37542   assert(
   37543     pPager->fd->pMethods==0 ||
   37544     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
   37545   );
   37546 
   37547   /* If this playback is happening automatically as a result of an IO or
   37548   ** malloc error that occurred after the change-counter was updated but
   37549   ** before the transaction was committed, then the change-counter
   37550   ** modification may just have been reverted. If this happens in exclusive
   37551   ** mode, then subsequent transactions performed by the connection will not
   37552   ** update the change-counter at all. This may lead to cache inconsistency
   37553   ** problems for other processes at some point in the future. So, just
   37554   ** in case this has happened, clear the changeCountDone flag now.
   37555   */
   37556   pPager->changeCountDone = pPager->tempFile;
   37557 
   37558   if( rc==SQLITE_OK ){
   37559     zMaster = pPager->pTmpSpace;
   37560     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
   37561     testcase( rc!=SQLITE_OK );
   37562   }
   37563   if( rc==SQLITE_OK && !pPager->noSync
   37564    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   37565   ){
   37566     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   37567   }
   37568   if( rc==SQLITE_OK ){
   37569     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
   37570     testcase( rc!=SQLITE_OK );
   37571   }
   37572   if( rc==SQLITE_OK && zMaster[0] && res ){
   37573     /* If there was a master journal and this routine will return success,
   37574     ** see if it is possible to delete the master journal.
   37575     */
   37576     rc = pager_delmaster(pPager, zMaster);
   37577     testcase( rc!=SQLITE_OK );
   37578   }
   37579 
   37580   /* The Pager.sectorSize variable may have been updated while rolling
   37581   ** back a journal created by a process with a different sector size
   37582   ** value. Reset it to the correct value for this process.
   37583   */
   37584   setSectorSize(pPager);
   37585   return rc;
   37586 }
   37587 
   37588 
   37589 /*
   37590 ** Read the content for page pPg out of the database file and into
   37591 ** pPg->pData. A shared lock or greater must be held on the database
   37592 ** file before this function is called.
   37593 **
   37594 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
   37595 ** the value read from the database file.
   37596 **
   37597 ** If an IO error occurs, then the IO error is returned to the caller.
   37598 ** Otherwise, SQLITE_OK is returned.
   37599 */
   37600 static int readDbPage(PgHdr *pPg){
   37601   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
   37602   Pgno pgno = pPg->pgno;       /* Page number to read */
   37603   int rc = SQLITE_OK;          /* Return code */
   37604   int isInWal = 0;             /* True if page is in log file */
   37605   int pgsz = pPager->pageSize; /* Number of bytes to read */
   37606 
   37607   assert( pPager->eState>=PAGER_READER && !MEMDB );
   37608   assert( isOpen(pPager->fd) );
   37609 
   37610   if( NEVER(!isOpen(pPager->fd)) ){
   37611     assert( pPager->tempFile );
   37612     memset(pPg->pData, 0, pPager->pageSize);
   37613     return SQLITE_OK;
   37614   }
   37615 
   37616   if( pagerUseWal(pPager) ){
   37617     /* Try to pull the page from the write-ahead log. */
   37618     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
   37619   }
   37620   if( rc==SQLITE_OK && !isInWal ){
   37621     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
   37622     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
   37623     if( rc==SQLITE_IOERR_SHORT_READ ){
   37624       rc = SQLITE_OK;
   37625     }
   37626   }
   37627 
   37628   if( pgno==1 ){
   37629     if( rc ){
   37630       /* If the read is unsuccessful, set the dbFileVers[] to something
   37631       ** that will never be a valid file version.  dbFileVers[] is a copy
   37632       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
   37633       ** zero or the size of the database in page. Bytes 32..35 and 35..39
   37634       ** should be page numbers which are never 0xffffffff.  So filling
   37635       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
   37636       **
   37637       ** For an encrypted database, the situation is more complex:  bytes
   37638       ** 24..39 of the database are white noise.  But the probability of
   37639       ** white noising equaling 16 bytes of 0xff is vanishingly small so
   37640       ** we should still be ok.
   37641       */
   37642       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
   37643     }else{
   37644       u8 *dbFileVers = &((u8*)pPg->pData)[24];
   37645       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
   37646     }
   37647   }
   37648   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
   37649 
   37650   PAGER_INCR(sqlite3_pager_readdb_count);
   37651   PAGER_INCR(pPager->nRead);
   37652   IOTRACE(("PGIN %p %d\n", pPager, pgno));
   37653   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
   37654                PAGERID(pPager), pgno, pager_pagehash(pPg)));
   37655 
   37656   return rc;
   37657 }
   37658 
   37659 #ifndef SQLITE_OMIT_WAL
   37660 /*
   37661 ** This function is invoked once for each page that has already been
   37662 ** written into the log file when a WAL transaction is rolled back.
   37663 ** Parameter iPg is the page number of said page. The pCtx argument
   37664 ** is actually a pointer to the Pager structure.
   37665 **
   37666 ** If page iPg is present in the cache, and has no outstanding references,
   37667 ** it is discarded. Otherwise, if there are one or more outstanding
   37668 ** references, the page content is reloaded from the database. If the
   37669 ** attempt to reload content from the database is required and fails,
   37670 ** return an SQLite error code. Otherwise, SQLITE_OK.
   37671 */
   37672 static int pagerUndoCallback(void *pCtx, Pgno iPg){
   37673   int rc = SQLITE_OK;
   37674   Pager *pPager = (Pager *)pCtx;
   37675   PgHdr *pPg;
   37676 
   37677   pPg = sqlite3PagerLookup(pPager, iPg);
   37678   if( pPg ){
   37679     if( sqlite3PcachePageRefcount(pPg)==1 ){
   37680       sqlite3PcacheDrop(pPg);
   37681     }else{
   37682       rc = readDbPage(pPg);
   37683       if( rc==SQLITE_OK ){
   37684         pPager->xReiniter(pPg);
   37685       }
   37686       sqlite3PagerUnref(pPg);
   37687     }
   37688   }
   37689 
   37690   /* Normally, if a transaction is rolled back, any backup processes are
   37691   ** updated as data is copied out of the rollback journal and into the
   37692   ** database. This is not generally possible with a WAL database, as
   37693   ** rollback involves simply truncating the log file. Therefore, if one
   37694   ** or more frames have already been written to the log (and therefore
   37695   ** also copied into the backup databases) as part of this transaction,
   37696   ** the backups must be restarted.
   37697   */
   37698   sqlite3BackupRestart(pPager->pBackup);
   37699 
   37700   return rc;
   37701 }
   37702 
   37703 /*
   37704 ** This function is called to rollback a transaction on a WAL database.
   37705 */
   37706 static int pagerRollbackWal(Pager *pPager){
   37707   int rc;                         /* Return Code */
   37708   PgHdr *pList;                   /* List of dirty pages to revert */
   37709 
   37710   /* For all pages in the cache that are currently dirty or have already
   37711   ** been written (but not committed) to the log file, do one of the
   37712   ** following:
   37713   **
   37714   **   + Discard the cached page (if refcount==0), or
   37715   **   + Reload page content from the database (if refcount>0).
   37716   */
   37717   pPager->dbSize = pPager->dbOrigSize;
   37718   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
   37719   pList = sqlite3PcacheDirtyList(pPager->pPCache);
   37720   while( pList && rc==SQLITE_OK ){
   37721     PgHdr *pNext = pList->pDirty;
   37722     rc = pagerUndoCallback((void *)pPager, pList->pgno);
   37723     pList = pNext;
   37724   }
   37725 
   37726   return rc;
   37727 }
   37728 
   37729 
   37730 /*
   37731 ** Update the value of the change-counter at offsets 24 and 92 in
   37732 ** the header and the sqlite version number at offset 96.
   37733 **
   37734 ** This is an unconditional update.  See also the pager_incr_changecounter()
   37735 ** routine which only updates the change-counter if the update is actually
   37736 ** needed, as determined by the pPager->changeCountDone state variable.
   37737 */
   37738 static void pager_write_changecounter(PgHdr *pPg){
   37739   u32 change_counter;
   37740 
   37741   /* Increment the value just read and write it back to byte 24. */
   37742   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
   37743   put32bits(((char*)pPg->pData)+24, change_counter);
   37744 
   37745   /* Also store the SQLite version number in bytes 96..99 and in
   37746   ** bytes 92..95 store the change counter for which the version number
   37747   ** is valid. */
   37748   put32bits(((char*)pPg->pData)+92, change_counter);
   37749   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
   37750 }
   37751 
   37752 /*
   37753 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
   37754 ** the contents of the list of pages headed by pList (connected by pDirty),
   37755 ** this function notifies any active backup processes that the pages have
   37756 ** changed.
   37757 **
   37758 ** The list of pages passed into this routine is always sorted by page number.
   37759 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
   37760 */
   37761 static int pagerWalFrames(
   37762   Pager *pPager,                  /* Pager object */
   37763   PgHdr *pList,                   /* List of frames to log */
   37764   Pgno nTruncate,                 /* Database size after this commit */
   37765   int isCommit,                   /* True if this is a commit */
   37766   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
   37767 ){
   37768   int rc;                         /* Return code */
   37769 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
   37770   PgHdr *p;                       /* For looping over pages */
   37771 #endif
   37772 
   37773   assert( pPager->pWal );
   37774 #ifdef SQLITE_DEBUG
   37775   /* Verify that the page list is in accending order */
   37776   for(p=pList; p && p->pDirty; p=p->pDirty){
   37777     assert( p->pgno < p->pDirty->pgno );
   37778   }
   37779 #endif
   37780 
   37781   if( pList->pgno==1 ) pager_write_changecounter(pList);
   37782   rc = sqlite3WalFrames(pPager->pWal,
   37783       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
   37784   );
   37785   if( rc==SQLITE_OK && pPager->pBackup ){
   37786     PgHdr *p;
   37787     for(p=pList; p; p=p->pDirty){
   37788       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
   37789     }
   37790   }
   37791 
   37792 #ifdef SQLITE_CHECK_PAGES
   37793   for(p=pList; p; p=p->pDirty){
   37794     pager_set_pagehash(p);
   37795   }
   37796 #endif
   37797 
   37798   return rc;
   37799 }
   37800 
   37801 /*
   37802 ** Begin a read transaction on the WAL.
   37803 **
   37804 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
   37805 ** makes a snapshot of the database at the current point in time and preserves
   37806 ** that snapshot for use by the reader in spite of concurrently changes by
   37807 ** other writers or checkpointers.
   37808 */
   37809 static int pagerBeginReadTransaction(Pager *pPager){
   37810   int rc;                         /* Return code */
   37811   int changed = 0;                /* True if cache must be reset */
   37812 
   37813   assert( pagerUseWal(pPager) );
   37814   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   37815 
   37816   /* sqlite3WalEndReadTransaction() was not called for the previous
   37817   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
   37818   ** are in locking_mode=NORMAL and EndRead() was previously called,
   37819   ** the duplicate call is harmless.
   37820   */
   37821   sqlite3WalEndReadTransaction(pPager->pWal);
   37822 
   37823   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
   37824   if( rc!=SQLITE_OK || changed ){
   37825     pager_reset(pPager);
   37826   }
   37827 
   37828   return rc;
   37829 }
   37830 #endif
   37831 
   37832 /*
   37833 ** This function is called as part of the transition from PAGER_OPEN
   37834 ** to PAGER_READER state to determine the size of the database file
   37835 ** in pages (assuming the page size currently stored in Pager.pageSize).
   37836 **
   37837 ** If no error occurs, SQLITE_OK is returned and the size of the database
   37838 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
   37839 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
   37840 */
   37841 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
   37842   Pgno nPage;                     /* Value to return via *pnPage */
   37843 
   37844   /* Query the WAL sub-system for the database size. The WalDbsize()
   37845   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
   37846   ** if the database size is not available. The database size is not
   37847   ** available from the WAL sub-system if the log file is empty or
   37848   ** contains no valid committed transactions.
   37849   */
   37850   assert( pPager->eState==PAGER_OPEN );
   37851   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
   37852   nPage = sqlite3WalDbsize(pPager->pWal);
   37853 
   37854   /* If the database size was not available from the WAL sub-system,
   37855   ** determine it based on the size of the database file. If the size
   37856   ** of the database file is not an integer multiple of the page-size,
   37857   ** round down to the nearest page. Except, any file larger than 0
   37858   ** bytes in size is considered to contain at least one page.
   37859   */
   37860   if( nPage==0 ){
   37861     i64 n = 0;                    /* Size of db file in bytes */
   37862     assert( isOpen(pPager->fd) || pPager->tempFile );
   37863     if( isOpen(pPager->fd) ){
   37864       int rc = sqlite3OsFileSize(pPager->fd, &n);
   37865       if( rc!=SQLITE_OK ){
   37866         return rc;
   37867       }
   37868     }
   37869     nPage = (Pgno)(n / pPager->pageSize);
   37870     if( nPage==0 && n>0 ){
   37871       nPage = 1;
   37872     }
   37873   }
   37874 
   37875   /* If the current number of pages in the file is greater than the
   37876   ** configured maximum pager number, increase the allowed limit so
   37877   ** that the file can be read.
   37878   */
   37879   if( nPage>pPager->mxPgno ){
   37880     pPager->mxPgno = (Pgno)nPage;
   37881   }
   37882 
   37883   *pnPage = nPage;
   37884   return SQLITE_OK;
   37885 }
   37886 
   37887 #ifndef SQLITE_OMIT_WAL
   37888 /*
   37889 ** Check if the *-wal file that corresponds to the database opened by pPager
   37890 ** exists if the database is not empy, or verify that the *-wal file does
   37891 ** not exist (by deleting it) if the database file is empty.
   37892 **
   37893 ** If the database is not empty and the *-wal file exists, open the pager
   37894 ** in WAL mode.  If the database is empty or if no *-wal file exists and
   37895 ** if no error occurs, make sure Pager.journalMode is not set to
   37896 ** PAGER_JOURNALMODE_WAL.
   37897 **
   37898 ** Return SQLITE_OK or an error code.
   37899 **
   37900 ** The caller must hold a SHARED lock on the database file to call this
   37901 ** function. Because an EXCLUSIVE lock on the db file is required to delete
   37902 ** a WAL on a none-empty database, this ensures there is no race condition
   37903 ** between the xAccess() below and an xDelete() being executed by some
   37904 ** other connection.
   37905 */
   37906 static int pagerOpenWalIfPresent(Pager *pPager){
   37907   int rc = SQLITE_OK;
   37908   assert( pPager->eState==PAGER_OPEN );
   37909   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
   37910 
   37911   if( !pPager->tempFile ){
   37912     int isWal;                    /* True if WAL file exists */
   37913     Pgno nPage;                   /* Size of the database file */
   37914 
   37915     rc = pagerPagecount(pPager, &nPage);
   37916     if( rc ) return rc;
   37917     if( nPage==0 ){
   37918       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
   37919       isWal = 0;
   37920     }else{
   37921       rc = sqlite3OsAccess(
   37922           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
   37923       );
   37924     }
   37925     if( rc==SQLITE_OK ){
   37926       if( isWal ){
   37927         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
   37928         rc = sqlite3PagerOpenWal(pPager, 0);
   37929       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
   37930         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
   37931       }
   37932     }
   37933   }
   37934   return rc;
   37935 }
   37936 #endif
   37937 
   37938 /*
   37939 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
   37940 ** the entire master journal file. The case pSavepoint==NULL occurs when
   37941 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
   37942 ** savepoint.
   37943 **
   37944 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
   37945 ** being rolled back), then the rollback consists of up to three stages,
   37946 ** performed in the order specified:
   37947 **
   37948 **   * Pages are played back from the main journal starting at byte
   37949 **     offset PagerSavepoint.iOffset and continuing to
   37950 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
   37951 **     file if PagerSavepoint.iHdrOffset is zero.
   37952 **
   37953 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
   37954 **     back starting from the journal header immediately following
   37955 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
   37956 **
   37957 **   * Pages are then played back from the sub-journal file, starting
   37958 **     with the PagerSavepoint.iSubRec and continuing to the end of
   37959 **     the journal file.
   37960 **
   37961 ** Throughout the rollback process, each time a page is rolled back, the
   37962 ** corresponding bit is set in a bitvec structure (variable pDone in the
   37963 ** implementation below). This is used to ensure that a page is only
   37964 ** rolled back the first time it is encountered in either journal.
   37965 **
   37966 ** If pSavepoint is NULL, then pages are only played back from the main
   37967 ** journal file. There is no need for a bitvec in this case.
   37968 **
   37969 ** In either case, before playback commences the Pager.dbSize variable
   37970 ** is reset to the value that it held at the start of the savepoint
   37971 ** (or transaction). No page with a page-number greater than this value
   37972 ** is played back. If one is encountered it is simply skipped.
   37973 */
   37974 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   37975   i64 szJ;                 /* Effective size of the main journal */
   37976   i64 iHdrOff;             /* End of first segment of main-journal records */
   37977   int rc = SQLITE_OK;      /* Return code */
   37978   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
   37979 
   37980   assert( pPager->eState!=PAGER_ERROR );
   37981   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   37982 
   37983   /* Allocate a bitvec to use to store the set of pages rolled back */
   37984   if( pSavepoint ){
   37985     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
   37986     if( !pDone ){
   37987       return SQLITE_NOMEM;
   37988     }
   37989   }
   37990 
   37991   /* Set the database size back to the value it was before the savepoint
   37992   ** being reverted was opened.
   37993   */
   37994   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
   37995   pPager->changeCountDone = pPager->tempFile;
   37996 
   37997   if( !pSavepoint && pagerUseWal(pPager) ){
   37998     return pagerRollbackWal(pPager);
   37999   }
   38000 
   38001   /* Use pPager->journalOff as the effective size of the main rollback
   38002   ** journal.  The actual file might be larger than this in
   38003   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
   38004   ** past pPager->journalOff is off-limits to us.
   38005   */
   38006   szJ = pPager->journalOff;
   38007   assert( pagerUseWal(pPager)==0 || szJ==0 );
   38008 
   38009   /* Begin by rolling back records from the main journal starting at
   38010   ** PagerSavepoint.iOffset and continuing to the next journal header.
   38011   ** There might be records in the main journal that have a page number
   38012   ** greater than the current database size (pPager->dbSize) but those
   38013   ** will be skipped automatically.  Pages are added to pDone as they
   38014   ** are played back.
   38015   */
   38016   if( pSavepoint && !pagerUseWal(pPager) ){
   38017     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
   38018     pPager->journalOff = pSavepoint->iOffset;
   38019     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
   38020       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   38021     }
   38022     assert( rc!=SQLITE_DONE );
   38023   }else{
   38024     pPager->journalOff = 0;
   38025   }
   38026 
   38027   /* Continue rolling back records out of the main journal starting at
   38028   ** the first journal header seen and continuing until the effective end
   38029   ** of the main journal file.  Continue to skip out-of-range pages and
   38030   ** continue adding pages rolled back to pDone.
   38031   */
   38032   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
   38033     u32 ii;            /* Loop counter */
   38034     u32 nJRec = 0;     /* Number of Journal Records */
   38035     u32 dummy;
   38036     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
   38037     assert( rc!=SQLITE_DONE );
   38038 
   38039     /*
   38040     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
   38041     ** test is related to ticket #2565.  See the discussion in the
   38042     ** pager_playback() function for additional information.
   38043     */
   38044     if( nJRec==0
   38045      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
   38046     ){
   38047       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
   38048     }
   38049     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
   38050       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
   38051     }
   38052     assert( rc!=SQLITE_DONE );
   38053   }
   38054   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
   38055 
   38056   /* Finally,  rollback pages from the sub-journal.  Page that were
   38057   ** previously rolled back out of the main journal (and are hence in pDone)
   38058   ** will be skipped.  Out-of-range pages are also skipped.
   38059   */
   38060   if( pSavepoint ){
   38061     u32 ii;            /* Loop counter */
   38062     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
   38063 
   38064     if( pagerUseWal(pPager) ){
   38065       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
   38066     }
   38067     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
   38068       assert( offset==ii*(4+pPager->pageSize) );
   38069       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
   38070     }
   38071     assert( rc!=SQLITE_DONE );
   38072   }
   38073 
   38074   sqlite3BitvecDestroy(pDone);
   38075   if( rc==SQLITE_OK ){
   38076     pPager->journalOff = szJ;
   38077   }
   38078 
   38079   return rc;
   38080 }
   38081 
   38082 /*
   38083 ** Change the maximum number of in-memory pages that are allowed.
   38084 */
   38085 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
   38086   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
   38087 }
   38088 
   38089 /*
   38090 ** Adjust the robustness of the database to damage due to OS crashes
   38091 ** or power failures by changing the number of syncs()s when writing
   38092 ** the rollback journal.  There are three levels:
   38093 **
   38094 **    OFF       sqlite3OsSync() is never called.  This is the default
   38095 **              for temporary and transient files.
   38096 **
   38097 **    NORMAL    The journal is synced once before writes begin on the
   38098 **              database.  This is normally adequate protection, but
   38099 **              it is theoretically possible, though very unlikely,
   38100 **              that an inopertune power failure could leave the journal
   38101 **              in a state which would cause damage to the database
   38102 **              when it is rolled back.
   38103 **
   38104 **    FULL      The journal is synced twice before writes begin on the
   38105 **              database (with some additional information - the nRec field
   38106 **              of the journal header - being written in between the two
   38107 **              syncs).  If we assume that writing a
   38108 **              single disk sector is atomic, then this mode provides
   38109 **              assurance that the journal will not be corrupted to the
   38110 **              point of causing damage to the database during rollback.
   38111 **
   38112 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
   38113 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
   38114 ** prior to the start of checkpoint and that the database file is synced
   38115 ** at the conclusion of the checkpoint if the entire content of the WAL
   38116 ** was written back into the database.  But no sync operations occur for
   38117 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
   38118 ** file is synced following each commit operation, in addition to the
   38119 ** syncs associated with NORMAL.
   38120 **
   38121 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
   38122 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
   38123 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
   38124 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
   38125 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
   38126 ** synchronous=FULL versus synchronous=NORMAL setting determines when
   38127 ** the xSync primitive is called and is relevant to all platforms.
   38128 **
   38129 ** Numeric values associated with these states are OFF==1, NORMAL=2,
   38130 ** and FULL=3.
   38131 */
   38132 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   38133 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
   38134   Pager *pPager,        /* The pager to set safety level for */
   38135   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   38136   int bFullFsync,       /* PRAGMA fullfsync */
   38137   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
   38138 ){
   38139   assert( level>=1 && level<=3 );
   38140   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
   38141   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
   38142   if( pPager->noSync ){
   38143     pPager->syncFlags = 0;
   38144     pPager->ckptSyncFlags = 0;
   38145   }else if( bFullFsync ){
   38146     pPager->syncFlags = SQLITE_SYNC_FULL;
   38147     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   38148   }else if( bCkptFullFsync ){
   38149     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   38150     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
   38151   }else{
   38152     pPager->syncFlags = SQLITE_SYNC_NORMAL;
   38153     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
   38154   }
   38155 }
   38156 #endif
   38157 
   38158 /*
   38159 ** The following global variable is incremented whenever the library
   38160 ** attempts to open a temporary file.  This information is used for
   38161 ** testing and analysis only.
   38162 */
   38163 #ifdef SQLITE_TEST
   38164 SQLITE_API int sqlite3_opentemp_count = 0;
   38165 #endif
   38166 
   38167 /*
   38168 ** Open a temporary file.
   38169 **
   38170 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
   38171 ** or some other error code if we fail. The OS will automatically
   38172 ** delete the temporary file when it is closed.
   38173 **
   38174 ** The flags passed to the VFS layer xOpen() call are those specified
   38175 ** by parameter vfsFlags ORed with the following:
   38176 **
   38177 **     SQLITE_OPEN_READWRITE
   38178 **     SQLITE_OPEN_CREATE
   38179 **     SQLITE_OPEN_EXCLUSIVE
   38180 **     SQLITE_OPEN_DELETEONCLOSE
   38181 */
   38182 static int pagerOpentemp(
   38183   Pager *pPager,        /* The pager object */
   38184   sqlite3_file *pFile,  /* Write the file descriptor here */
   38185   int vfsFlags          /* Flags passed through to the VFS */
   38186 ){
   38187   int rc;               /* Return code */
   38188 
   38189 #ifdef SQLITE_TEST
   38190   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
   38191 #endif
   38192 
   38193   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
   38194             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
   38195   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
   38196   assert( rc!=SQLITE_OK || isOpen(pFile) );
   38197   return rc;
   38198 }
   38199 
   38200 /*
   38201 ** Set the busy handler function.
   38202 **
   38203 ** The pager invokes the busy-handler if sqlite3OsLock() returns
   38204 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
   38205 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
   38206 ** lock. It does *not* invoke the busy handler when upgrading from
   38207 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
   38208 ** (which occurs during hot-journal rollback). Summary:
   38209 **
   38210 **   Transition                        | Invokes xBusyHandler
   38211 **   --------------------------------------------------------
   38212 **   NO_LOCK       -> SHARED_LOCK      | Yes
   38213 **   SHARED_LOCK   -> RESERVED_LOCK    | No
   38214 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
   38215 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
   38216 **
   38217 ** If the busy-handler callback returns non-zero, the lock is
   38218 ** retried. If it returns zero, then the SQLITE_BUSY error is
   38219 ** returned to the caller of the pager API function.
   38220 */
   38221 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
   38222   Pager *pPager,                       /* Pager object */
   38223   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
   38224   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
   38225 ){
   38226   pPager->xBusyHandler = xBusyHandler;
   38227   pPager->pBusyHandlerArg = pBusyHandlerArg;
   38228 }
   38229 
   38230 /*
   38231 ** Change the page size used by the Pager object. The new page size
   38232 ** is passed in *pPageSize.
   38233 **
   38234 ** If the pager is in the error state when this function is called, it
   38235 ** is a no-op. The value returned is the error state error code (i.e.
   38236 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
   38237 **
   38238 ** Otherwise, if all of the following are true:
   38239 **
   38240 **   * the new page size (value of *pPageSize) is valid (a power
   38241 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
   38242 **
   38243 **   * there are no outstanding page references, and
   38244 **
   38245 **   * the database is either not an in-memory database or it is
   38246 **     an in-memory database that currently consists of zero pages.
   38247 **
   38248 ** then the pager object page size is set to *pPageSize.
   38249 **
   38250 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
   38251 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
   38252 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
   38253 ** In all other cases, SQLITE_OK is returned.
   38254 **
   38255 ** If the page size is not changed, either because one of the enumerated
   38256 ** conditions above is not true, the pager was in error state when this
   38257 ** function was called, or because the memory allocation attempt failed,
   38258 ** then *pPageSize is set to the old, retained page size before returning.
   38259 */
   38260 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
   38261   int rc = SQLITE_OK;
   38262 
   38263   /* It is not possible to do a full assert_pager_state() here, as this
   38264   ** function may be called from within PagerOpen(), before the state
   38265   ** of the Pager object is internally consistent.
   38266   **
   38267   ** At one point this function returned an error if the pager was in
   38268   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   38269   ** there is at least one outstanding page reference, this function
   38270   ** is a no-op for that case anyhow.
   38271   */
   38272 
   38273   u32 pageSize = *pPageSize;
   38274   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   38275   if( (pPager->memDb==0 || pPager->dbSize==0)
   38276    && sqlite3PcacheRefCount(pPager->pPCache)==0
   38277    && pageSize && pageSize!=(u32)pPager->pageSize
   38278   ){
   38279     char *pNew = NULL;             /* New temp space */
   38280     i64 nByte = 0;
   38281 
   38282     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
   38283       rc = sqlite3OsFileSize(pPager->fd, &nByte);
   38284     }
   38285     if( rc==SQLITE_OK ){
   38286       pNew = (char *)sqlite3PageMalloc(pageSize);
   38287       if( !pNew ) rc = SQLITE_NOMEM;
   38288     }
   38289 
   38290     if( rc==SQLITE_OK ){
   38291       pager_reset(pPager);
   38292       pPager->dbSize = (Pgno)(nByte/pageSize);
   38293       pPager->pageSize = pageSize;
   38294       sqlite3PageFree(pPager->pTmpSpace);
   38295       pPager->pTmpSpace = pNew;
   38296       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
   38297     }
   38298   }
   38299 
   38300   *pPageSize = pPager->pageSize;
   38301   if( rc==SQLITE_OK ){
   38302     if( nReserve<0 ) nReserve = pPager->nReserve;
   38303     assert( nReserve>=0 && nReserve<1000 );
   38304     pPager->nReserve = (i16)nReserve;
   38305     pagerReportSize(pPager);
   38306   }
   38307   return rc;
   38308 }
   38309 
   38310 /*
   38311 ** Return a pointer to the "temporary page" buffer held internally
   38312 ** by the pager.  This is a buffer that is big enough to hold the
   38313 ** entire content of a database page.  This buffer is used internally
   38314 ** during rollback and will be overwritten whenever a rollback
   38315 ** occurs.  But other modules are free to use it too, as long as
   38316 ** no rollbacks are happening.
   38317 */
   38318 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
   38319   return pPager->pTmpSpace;
   38320 }
   38321 
   38322 /*
   38323 ** Attempt to set the maximum database page count if mxPage is positive.
   38324 ** Make no changes if mxPage is zero or negative.  And never reduce the
   38325 ** maximum page count below the current size of the database.
   38326 **
   38327 ** Regardless of mxPage, return the current maximum page count.
   38328 */
   38329 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
   38330   if( mxPage>0 ){
   38331     pPager->mxPgno = mxPage;
   38332   }
   38333   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
   38334   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
   38335   return pPager->mxPgno;
   38336 }
   38337 
   38338 /*
   38339 ** The following set of routines are used to disable the simulated
   38340 ** I/O error mechanism.  These routines are used to avoid simulated
   38341 ** errors in places where we do not care about errors.
   38342 **
   38343 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
   38344 ** and generate no code.
   38345 */
   38346 #ifdef SQLITE_TEST
   38347 SQLITE_API extern int sqlite3_io_error_pending;
   38348 SQLITE_API extern int sqlite3_io_error_hit;
   38349 static int saved_cnt;
   38350 void disable_simulated_io_errors(void){
   38351   saved_cnt = sqlite3_io_error_pending;
   38352   sqlite3_io_error_pending = -1;
   38353 }
   38354 void enable_simulated_io_errors(void){
   38355   sqlite3_io_error_pending = saved_cnt;
   38356 }
   38357 #else
   38358 # define disable_simulated_io_errors()
   38359 # define enable_simulated_io_errors()
   38360 #endif
   38361 
   38362 /*
   38363 ** Read the first N bytes from the beginning of the file into memory
   38364 ** that pDest points to.
   38365 **
   38366 ** If the pager was opened on a transient file (zFilename==""), or
   38367 ** opened on a file less than N bytes in size, the output buffer is
   38368 ** zeroed and SQLITE_OK returned. The rationale for this is that this
   38369 ** function is used to read database headers, and a new transient or
   38370 ** zero sized database has a header than consists entirely of zeroes.
   38371 **
   38372 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
   38373 ** the error code is returned to the caller and the contents of the
   38374 ** output buffer undefined.
   38375 */
   38376 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
   38377   int rc = SQLITE_OK;
   38378   memset(pDest, 0, N);
   38379   assert( isOpen(pPager->fd) || pPager->tempFile );
   38380 
   38381   /* This routine is only called by btree immediately after creating
   38382   ** the Pager object.  There has not been an opportunity to transition
   38383   ** to WAL mode yet.
   38384   */
   38385   assert( !pagerUseWal(pPager) );
   38386 
   38387   if( isOpen(pPager->fd) ){
   38388     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
   38389     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
   38390     if( rc==SQLITE_IOERR_SHORT_READ ){
   38391       rc = SQLITE_OK;
   38392     }
   38393   }
   38394   return rc;
   38395 }
   38396 
   38397 /*
   38398 ** This function may only be called when a read-transaction is open on
   38399 ** the pager. It returns the total number of pages in the database.
   38400 **
   38401 ** However, if the file is between 1 and <page-size> bytes in size, then
   38402 ** this is considered a 1 page file.
   38403 */
   38404 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
   38405   assert( pPager->eState>=PAGER_READER );
   38406   assert( pPager->eState!=PAGER_WRITER_FINISHED );
   38407   *pnPage = (int)pPager->dbSize;
   38408 }
   38409 
   38410 
   38411 /*
   38412 ** Try to obtain a lock of type locktype on the database file. If
   38413 ** a similar or greater lock is already held, this function is a no-op
   38414 ** (returning SQLITE_OK immediately).
   38415 **
   38416 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
   38417 ** the busy callback if the lock is currently not available. Repeat
   38418 ** until the busy callback returns false or until the attempt to
   38419 ** obtain the lock succeeds.
   38420 **
   38421 ** Return SQLITE_OK on success and an error code if we cannot obtain
   38422 ** the lock. If the lock is obtained successfully, set the Pager.state
   38423 ** variable to locktype before returning.
   38424 */
   38425 static int pager_wait_on_lock(Pager *pPager, int locktype){
   38426   int rc;                              /* Return code */
   38427 
   38428   /* Check that this is either a no-op (because the requested lock is
   38429   ** already held, or one of the transistions that the busy-handler
   38430   ** may be invoked during, according to the comment above
   38431   ** sqlite3PagerSetBusyhandler().
   38432   */
   38433   assert( (pPager->eLock>=locktype)
   38434        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
   38435        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
   38436   );
   38437 
   38438   do {
   38439     rc = pagerLockDb(pPager, locktype);
   38440   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
   38441   return rc;
   38442 }
   38443 
   38444 /*
   38445 ** Function assertTruncateConstraint(pPager) checks that one of the
   38446 ** following is true for all dirty pages currently in the page-cache:
   38447 **
   38448 **   a) The page number is less than or equal to the size of the
   38449 **      current database image, in pages, OR
   38450 **
   38451 **   b) if the page content were written at this time, it would not
   38452 **      be necessary to write the current content out to the sub-journal
   38453 **      (as determined by function subjRequiresPage()).
   38454 **
   38455 ** If the condition asserted by this function were not true, and the
   38456 ** dirty page were to be discarded from the cache via the pagerStress()
   38457 ** routine, pagerStress() would not write the current page content to
   38458 ** the database file. If a savepoint transaction were rolled back after
   38459 ** this happened, the correct behaviour would be to restore the current
   38460 ** content of the page. However, since this content is not present in either
   38461 ** the database file or the portion of the rollback journal and
   38462 ** sub-journal rolled back the content could not be restored and the
   38463 ** database image would become corrupt. It is therefore fortunate that
   38464 ** this circumstance cannot arise.
   38465 */
   38466 #if defined(SQLITE_DEBUG)
   38467 static void assertTruncateConstraintCb(PgHdr *pPg){
   38468   assert( pPg->flags&PGHDR_DIRTY );
   38469   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
   38470 }
   38471 static void assertTruncateConstraint(Pager *pPager){
   38472   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
   38473 }
   38474 #else
   38475 # define assertTruncateConstraint(pPager)
   38476 #endif
   38477 
   38478 /*
   38479 ** Truncate the in-memory database file image to nPage pages. This
   38480 ** function does not actually modify the database file on disk. It
   38481 ** just sets the internal state of the pager object so that the
   38482 ** truncation will be done when the current transaction is committed.
   38483 */
   38484 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
   38485   assert( pPager->dbSize>=nPage );
   38486   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   38487   pPager->dbSize = nPage;
   38488   assertTruncateConstraint(pPager);
   38489 }
   38490 
   38491 
   38492 /*
   38493 ** This function is called before attempting a hot-journal rollback. It
   38494 ** syncs the journal file to disk, then sets pPager->journalHdr to the
   38495 ** size of the journal file so that the pager_playback() routine knows
   38496 ** that the entire journal file has been synced.
   38497 **
   38498 ** Syncing a hot-journal to disk before attempting to roll it back ensures
   38499 ** that if a power-failure occurs during the rollback, the process that
   38500 ** attempts rollback following system recovery sees the same journal
   38501 ** content as this process.
   38502 **
   38503 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
   38504 ** an SQLite error code.
   38505 */
   38506 static int pagerSyncHotJournal(Pager *pPager){
   38507   int rc = SQLITE_OK;
   38508   if( !pPager->noSync ){
   38509     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
   38510   }
   38511   if( rc==SQLITE_OK ){
   38512     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
   38513   }
   38514   return rc;
   38515 }
   38516 
   38517 /*
   38518 ** Shutdown the page cache.  Free all memory and close all files.
   38519 **
   38520 ** If a transaction was in progress when this routine is called, that
   38521 ** transaction is rolled back.  All outstanding pages are invalidated
   38522 ** and their memory is freed.  Any attempt to use a page associated
   38523 ** with this page cache after this function returns will likely
   38524 ** result in a coredump.
   38525 **
   38526 ** This function always succeeds. If a transaction is active an attempt
   38527 ** is made to roll it back. If an error occurs during the rollback
   38528 ** a hot journal may be left in the filesystem but no error is returned
   38529 ** to the caller.
   38530 */
   38531 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
   38532   u8 *pTmp = (u8 *)pPager->pTmpSpace;
   38533 
   38534   disable_simulated_io_errors();
   38535   sqlite3BeginBenignMalloc();
   38536   /* pPager->errCode = 0; */
   38537   pPager->exclusiveMode = 0;
   38538 #ifndef SQLITE_OMIT_WAL
   38539   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
   38540   pPager->pWal = 0;
   38541 #endif
   38542   pager_reset(pPager);
   38543   if( MEMDB ){
   38544     pager_unlock(pPager);
   38545   }else{
   38546     /* If it is open, sync the journal file before calling UnlockAndRollback.
   38547     ** If this is not done, then an unsynced portion of the open journal
   38548     ** file may be played back into the database. If a power failure occurs
   38549     ** while this is happening, the database could become corrupt.
   38550     **
   38551     ** If an error occurs while trying to sync the journal, shift the pager
   38552     ** into the ERROR state. This causes UnlockAndRollback to unlock the
   38553     ** database and close the journal file without attempting to roll it
   38554     ** back or finalize it. The next database user will have to do hot-journal
   38555     ** rollback before accessing the database file.
   38556     */
   38557     if( isOpen(pPager->jfd) ){
   38558       pager_error(pPager, pagerSyncHotJournal(pPager));
   38559     }
   38560     pagerUnlockAndRollback(pPager);
   38561   }
   38562   sqlite3EndBenignMalloc();
   38563   enable_simulated_io_errors();
   38564   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
   38565   IOTRACE(("CLOSE %p\n", pPager))
   38566   sqlite3OsClose(pPager->jfd);
   38567   sqlite3OsClose(pPager->fd);
   38568   sqlite3PageFree(pTmp);
   38569   sqlite3PcacheClose(pPager->pPCache);
   38570 
   38571 #ifdef SQLITE_HAS_CODEC
   38572   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   38573 #endif
   38574 
   38575   assert( !pPager->aSavepoint && !pPager->pInJournal );
   38576   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
   38577 
   38578   sqlite3_free(pPager);
   38579   return SQLITE_OK;
   38580 }
   38581 
   38582 #if !defined(NDEBUG) || defined(SQLITE_TEST)
   38583 /*
   38584 ** Return the page number for page pPg.
   38585 */
   38586 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
   38587   return pPg->pgno;
   38588 }
   38589 #endif
   38590 
   38591 /*
   38592 ** Increment the reference count for page pPg.
   38593 */
   38594 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
   38595   sqlite3PcacheRef(pPg);
   38596 }
   38597 
   38598 /*
   38599 ** Sync the journal. In other words, make sure all the pages that have
   38600 ** been written to the journal have actually reached the surface of the
   38601 ** disk and can be restored in the event of a hot-journal rollback.
   38602 **
   38603 ** If the Pager.noSync flag is set, then this function is a no-op.
   38604 ** Otherwise, the actions required depend on the journal-mode and the
   38605 ** device characteristics of the the file-system, as follows:
   38606 **
   38607 **   * If the journal file is an in-memory journal file, no action need
   38608 **     be taken.
   38609 **
   38610 **   * Otherwise, if the device does not support the SAFE_APPEND property,
   38611 **     then the nRec field of the most recently written journal header
   38612 **     is updated to contain the number of journal records that have
   38613 **     been written following it. If the pager is operating in full-sync
   38614 **     mode, then the journal file is synced before this field is updated.
   38615 **
   38616 **   * If the device does not support the SEQUENTIAL property, then
   38617 **     journal file is synced.
   38618 **
   38619 ** Or, in pseudo-code:
   38620 **
   38621 **   if( NOT <in-memory journal> ){
   38622 **     if( NOT SAFE_APPEND ){
   38623 **       if( <full-sync mode> ) xSync(<journal file>);
   38624 **       <update nRec field>
   38625 **     }
   38626 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
   38627 **   }
   38628 **
   38629 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
   38630 ** page currently held in memory before returning SQLITE_OK. If an IO
   38631 ** error is encountered, then the IO error code is returned to the caller.
   38632 */
   38633 static int syncJournal(Pager *pPager, int newHdr){
   38634   int rc;                         /* Return code */
   38635 
   38636   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   38637        || pPager->eState==PAGER_WRITER_DBMOD
   38638   );
   38639   assert( assert_pager_state(pPager) );
   38640   assert( !pagerUseWal(pPager) );
   38641 
   38642   rc = sqlite3PagerExclusiveLock(pPager);
   38643   if( rc!=SQLITE_OK ) return rc;
   38644 
   38645   if( !pPager->noSync ){
   38646     assert( !pPager->tempFile );
   38647     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
   38648       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   38649       assert( isOpen(pPager->jfd) );
   38650 
   38651       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   38652         /* This block deals with an obscure problem. If the last connection
   38653         ** that wrote to this database was operating in persistent-journal
   38654         ** mode, then the journal file may at this point actually be larger
   38655         ** than Pager.journalOff bytes. If the next thing in the journal
   38656         ** file happens to be a journal-header (written as part of the
   38657         ** previous connection's transaction), and a crash or power-failure
   38658         ** occurs after nRec is updated but before this connection writes
   38659         ** anything else to the journal file (or commits/rolls back its
   38660         ** transaction), then SQLite may become confused when doing the
   38661         ** hot-journal rollback following recovery. It may roll back all
   38662         ** of this connections data, then proceed to rolling back the old,
   38663         ** out-of-date data that follows it. Database corruption.
   38664         **
   38665         ** To work around this, if the journal file does appear to contain
   38666         ** a valid header following Pager.journalOff, then write a 0x00
   38667         ** byte to the start of it to prevent it from being recognized.
   38668         **
   38669         ** Variable iNextHdrOffset is set to the offset at which this
   38670         ** problematic header will occur, if it exists. aMagic is used
   38671         ** as a temporary buffer to inspect the first couple of bytes of
   38672         ** the potential journal header.
   38673         */
   38674         i64 iNextHdrOffset;
   38675         u8 aMagic[8];
   38676         u8 zHeader[sizeof(aJournalMagic)+4];
   38677 
   38678         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
   38679         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
   38680 
   38681         iNextHdrOffset = journalHdrOffset(pPager);
   38682         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
   38683         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
   38684           static const u8 zerobyte = 0;
   38685           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
   38686         }
   38687         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
   38688           return rc;
   38689         }
   38690 
   38691         /* Write the nRec value into the journal file header. If in
   38692         ** full-synchronous mode, sync the journal first. This ensures that
   38693         ** all data has really hit the disk before nRec is updated to mark
   38694         ** it as a candidate for rollback.
   38695         **
   38696         ** This is not required if the persistent media supports the
   38697         ** SAFE_APPEND property. Because in this case it is not possible
   38698         ** for garbage data to be appended to the file, the nRec field
   38699         ** is populated with 0xFFFFFFFF when the journal header is written
   38700         ** and never needs to be updated.
   38701         */
   38702         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   38703           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   38704           IOTRACE(("JSYNC %p\n", pPager))
   38705           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
   38706           if( rc!=SQLITE_OK ) return rc;
   38707         }
   38708         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
   38709         rc = sqlite3OsWrite(
   38710             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
   38711         );
   38712         if( rc!=SQLITE_OK ) return rc;
   38713       }
   38714       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
   38715         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
   38716         IOTRACE(("JSYNC %p\n", pPager))
   38717         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
   38718           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
   38719         );
   38720         if( rc!=SQLITE_OK ) return rc;
   38721       }
   38722 
   38723       pPager->journalHdr = pPager->journalOff;
   38724       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
   38725         pPager->nRec = 0;
   38726         rc = writeJournalHdr(pPager);
   38727         if( rc!=SQLITE_OK ) return rc;
   38728       }
   38729     }else{
   38730       pPager->journalHdr = pPager->journalOff;
   38731     }
   38732   }
   38733 
   38734   /* Unless the pager is in noSync mode, the journal file was just
   38735   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   38736   ** all pages.
   38737   */
   38738   sqlite3PcacheClearSyncFlags(pPager->pPCache);
   38739   pPager->eState = PAGER_WRITER_DBMOD;
   38740   assert( assert_pager_state(pPager) );
   38741   return SQLITE_OK;
   38742 }
   38743 
   38744 /*
   38745 ** The argument is the first in a linked list of dirty pages connected
   38746 ** by the PgHdr.pDirty pointer. This function writes each one of the
   38747 ** in-memory pages in the list to the database file. The argument may
   38748 ** be NULL, representing an empty list. In this case this function is
   38749 ** a no-op.
   38750 **
   38751 ** The pager must hold at least a RESERVED lock when this function
   38752 ** is called. Before writing anything to the database file, this lock
   38753 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
   38754 ** SQLITE_BUSY is returned and no data is written to the database file.
   38755 **
   38756 ** If the pager is a temp-file pager and the actual file-system file
   38757 ** is not yet open, it is created and opened before any data is
   38758 ** written out.
   38759 **
   38760 ** Once the lock has been upgraded and, if necessary, the file opened,
   38761 ** the pages are written out to the database file in list order. Writing
   38762 ** a page is skipped if it meets either of the following criteria:
   38763 **
   38764 **   * The page number is greater than Pager.dbSize, or
   38765 **   * The PGHDR_DONT_WRITE flag is set on the page.
   38766 **
   38767 ** If writing out a page causes the database file to grow, Pager.dbFileSize
   38768 ** is updated accordingly. If page 1 is written out, then the value cached
   38769 ** in Pager.dbFileVers[] is updated to match the new value stored in
   38770 ** the database file.
   38771 **
   38772 ** If everything is successful, SQLITE_OK is returned. If an IO error
   38773 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
   38774 ** be obtained, SQLITE_BUSY is returned.
   38775 */
   38776 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   38777   int rc = SQLITE_OK;                  /* Return code */
   38778 
   38779   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
   38780   assert( !pagerUseWal(pPager) );
   38781   assert( pPager->eState==PAGER_WRITER_DBMOD );
   38782   assert( pPager->eLock==EXCLUSIVE_LOCK );
   38783 
   38784   /* If the file is a temp-file has not yet been opened, open it now. It
   38785   ** is not possible for rc to be other than SQLITE_OK if this branch
   38786   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
   38787   */
   38788   if( !isOpen(pPager->fd) ){
   38789     assert( pPager->tempFile && rc==SQLITE_OK );
   38790     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
   38791   }
   38792 
   38793   /* Before the first write, give the VFS a hint of what the final
   38794   ** file size will be.
   38795   */
   38796   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
   38797   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
   38798     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
   38799     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
   38800     pPager->dbHintSize = pPager->dbSize;
   38801   }
   38802 
   38803   while( rc==SQLITE_OK && pList ){
   38804     Pgno pgno = pList->pgno;
   38805 
   38806     /* If there are dirty pages in the page cache with page numbers greater
   38807     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
   38808     ** make the file smaller (presumably by auto-vacuum code). Do not write
   38809     ** any such pages to the file.
   38810     **
   38811     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
   38812     ** set (set by sqlite3PagerDontWrite()).
   38813     */
   38814     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
   38815       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
   38816       char *pData;                                   /* Data to write */
   38817 
   38818       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
   38819       if( pList->pgno==1 ) pager_write_changecounter(pList);
   38820 
   38821       /* Encode the database */
   38822       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
   38823 
   38824       /* Write out the page data. */
   38825       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
   38826 
   38827       /* If page 1 was just written, update Pager.dbFileVers to match
   38828       ** the value now stored in the database file. If writing this
   38829       ** page caused the database file to grow, update dbFileSize.
   38830       */
   38831       if( pgno==1 ){
   38832         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
   38833       }
   38834       if( pgno>pPager->dbFileSize ){
   38835         pPager->dbFileSize = pgno;
   38836       }
   38837 
   38838       /* Update any backup objects copying the contents of this pager. */
   38839       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
   38840 
   38841       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
   38842                    PAGERID(pPager), pgno, pager_pagehash(pList)));
   38843       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
   38844       PAGER_INCR(sqlite3_pager_writedb_count);
   38845       PAGER_INCR(pPager->nWrite);
   38846     }else{
   38847       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
   38848     }
   38849     pager_set_pagehash(pList);
   38850     pList = pList->pDirty;
   38851   }
   38852 
   38853   return rc;
   38854 }
   38855 
   38856 /*
   38857 ** Ensure that the sub-journal file is open. If it is already open, this
   38858 ** function is a no-op.
   38859 **
   38860 ** SQLITE_OK is returned if everything goes according to plan. An
   38861 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
   38862 ** fails.
   38863 */
   38864 static int openSubJournal(Pager *pPager){
   38865   int rc = SQLITE_OK;
   38866   if( !isOpen(pPager->sjfd) ){
   38867     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
   38868       sqlite3MemJournalOpen(pPager->sjfd);
   38869     }else{
   38870       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
   38871     }
   38872   }
   38873   return rc;
   38874 }
   38875 
   38876 /*
   38877 ** Append a record of the current state of page pPg to the sub-journal.
   38878 ** It is the callers responsibility to use subjRequiresPage() to check
   38879 ** that it is really required before calling this function.
   38880 **
   38881 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
   38882 ** for all open savepoints before returning.
   38883 **
   38884 ** This function returns SQLITE_OK if everything is successful, an IO
   38885 ** error code if the attempt to write to the sub-journal fails, or
   38886 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
   38887 ** bitvec.
   38888 */
   38889 static int subjournalPage(PgHdr *pPg){
   38890   int rc = SQLITE_OK;
   38891   Pager *pPager = pPg->pPager;
   38892   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   38893 
   38894     /* Open the sub-journal, if it has not already been opened */
   38895     assert( pPager->useJournal );
   38896     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
   38897     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
   38898     assert( pagerUseWal(pPager)
   38899          || pageInJournal(pPg)
   38900          || pPg->pgno>pPager->dbOrigSize
   38901     );
   38902     rc = openSubJournal(pPager);
   38903 
   38904     /* If the sub-journal was opened successfully (or was already open),
   38905     ** write the journal record into the file.  */
   38906     if( rc==SQLITE_OK ){
   38907       void *pData = pPg->pData;
   38908       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
   38909       char *pData2;
   38910 
   38911       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   38912       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
   38913       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
   38914       if( rc==SQLITE_OK ){
   38915         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
   38916       }
   38917     }
   38918   }
   38919   if( rc==SQLITE_OK ){
   38920     pPager->nSubRec++;
   38921     assert( pPager->nSavepoint>0 );
   38922     rc = addToSavepointBitvecs(pPager, pPg->pgno);
   38923   }
   38924   return rc;
   38925 }
   38926 
   38927 /*
   38928 ** This function is called by the pcache layer when it has reached some
   38929 ** soft memory limit. The first argument is a pointer to a Pager object
   38930 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
   38931 ** database). The second argument is a reference to a page that is
   38932 ** currently dirty but has no outstanding references. The page
   38933 ** is always associated with the Pager object passed as the first
   38934 ** argument.
   38935 **
   38936 ** The job of this function is to make pPg clean by writing its contents
   38937 ** out to the database file, if possible. This may involve syncing the
   38938 ** journal file.
   38939 **
   38940 ** If successful, sqlite3PcacheMakeClean() is called on the page and
   38941 ** SQLITE_OK returned. If an IO error occurs while trying to make the
   38942 ** page clean, the IO error code is returned. If the page cannot be
   38943 ** made clean for some other reason, but no error occurs, then SQLITE_OK
   38944 ** is returned by sqlite3PcacheMakeClean() is not called.
   38945 */
   38946 static int pagerStress(void *p, PgHdr *pPg){
   38947   Pager *pPager = (Pager *)p;
   38948   int rc = SQLITE_OK;
   38949 
   38950   assert( pPg->pPager==pPager );
   38951   assert( pPg->flags&PGHDR_DIRTY );
   38952 
   38953   /* The doNotSyncSpill flag is set during times when doing a sync of
   38954   ** journal (and adding a new header) is not allowed.  This occurs
   38955   ** during calls to sqlite3PagerWrite() while trying to journal multiple
   38956   ** pages belonging to the same sector.
   38957   **
   38958   ** The doNotSpill flag inhibits all cache spilling regardless of whether
   38959   ** or not a sync is required.  This is set during a rollback.
   38960   **
   38961   ** Spilling is also prohibited when in an error state since that could
   38962   ** lead to database corruption.   In the current implementaton it
   38963   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
   38964   ** while in the error state, hence it is impossible for this routine to
   38965   ** be called in the error state.  Nevertheless, we include a NEVER()
   38966   ** test for the error state as a safeguard against future changes.
   38967   */
   38968   if( NEVER(pPager->errCode) ) return SQLITE_OK;
   38969   if( pPager->doNotSpill ) return SQLITE_OK;
   38970   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
   38971     return SQLITE_OK;
   38972   }
   38973 
   38974   pPg->pDirty = 0;
   38975   if( pagerUseWal(pPager) ){
   38976     /* Write a single frame for this page to the log. */
   38977     if( subjRequiresPage(pPg) ){
   38978       rc = subjournalPage(pPg);
   38979     }
   38980     if( rc==SQLITE_OK ){
   38981       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
   38982     }
   38983   }else{
   38984 
   38985     /* Sync the journal file if required. */
   38986     if( pPg->flags&PGHDR_NEED_SYNC
   38987      || pPager->eState==PAGER_WRITER_CACHEMOD
   38988     ){
   38989       rc = syncJournal(pPager, 1);
   38990     }
   38991 
   38992     /* If the page number of this page is larger than the current size of
   38993     ** the database image, it may need to be written to the sub-journal.
   38994     ** This is because the call to pager_write_pagelist() below will not
   38995     ** actually write data to the file in this case.
   38996     **
   38997     ** Consider the following sequence of events:
   38998     **
   38999     **   BEGIN;
   39000     **     <journal page X>
   39001     **     <modify page X>
   39002     **     SAVEPOINT sp;
   39003     **       <shrink database file to Y pages>
   39004     **       pagerStress(page X)
   39005     **     ROLLBACK TO sp;
   39006     **
   39007     ** If (X>Y), then when pagerStress is called page X will not be written
   39008     ** out to the database file, but will be dropped from the cache. Then,
   39009     ** following the "ROLLBACK TO sp" statement, reading page X will read
   39010     ** data from the database file. This will be the copy of page X as it
   39011     ** was when the transaction started, not as it was when "SAVEPOINT sp"
   39012     ** was executed.
   39013     **
   39014     ** The solution is to write the current data for page X into the
   39015     ** sub-journal file now (if it is not already there), so that it will
   39016     ** be restored to its current value when the "ROLLBACK TO sp" is
   39017     ** executed.
   39018     */
   39019     if( NEVER(
   39020         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
   39021     ) ){
   39022       rc = subjournalPage(pPg);
   39023     }
   39024 
   39025     /* Write the contents of the page out to the database file. */
   39026     if( rc==SQLITE_OK ){
   39027       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
   39028       rc = pager_write_pagelist(pPager, pPg);
   39029     }
   39030   }
   39031 
   39032   /* Mark the page as clean. */
   39033   if( rc==SQLITE_OK ){
   39034     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
   39035     sqlite3PcacheMakeClean(pPg);
   39036   }
   39037 
   39038   return pager_error(pPager, rc);
   39039 }
   39040 
   39041 
   39042 /*
   39043 ** Allocate and initialize a new Pager object and put a pointer to it
   39044 ** in *ppPager. The pager should eventually be freed by passing it
   39045 ** to sqlite3PagerClose().
   39046 **
   39047 ** The zFilename argument is the path to the database file to open.
   39048 ** If zFilename is NULL then a randomly-named temporary file is created
   39049 ** and used as the file to be cached. Temporary files are be deleted
   39050 ** automatically when they are closed. If zFilename is ":memory:" then
   39051 ** all information is held in cache. It is never written to disk.
   39052 ** This can be used to implement an in-memory database.
   39053 **
   39054 ** The nExtra parameter specifies the number of bytes of space allocated
   39055 ** along with each page reference. This space is available to the user
   39056 ** via the sqlite3PagerGetExtra() API.
   39057 **
   39058 ** The flags argument is used to specify properties that affect the
   39059 ** operation of the pager. It should be passed some bitwise combination
   39060 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
   39061 **
   39062 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
   39063 ** of the xOpen() method of the supplied VFS when opening files.
   39064 **
   39065 ** If the pager object is allocated and the specified file opened
   39066 ** successfully, SQLITE_OK is returned and *ppPager set to point to
   39067 ** the new pager object. If an error occurs, *ppPager is set to NULL
   39068 ** and error code returned. This function may return SQLITE_NOMEM
   39069 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
   39070 ** various SQLITE_IO_XXX errors.
   39071 */
   39072 SQLITE_PRIVATE int sqlite3PagerOpen(
   39073   sqlite3_vfs *pVfs,       /* The virtual file system to use */
   39074   Pager **ppPager,         /* OUT: Return the Pager structure here */
   39075   const char *zFilename,   /* Name of the database file to open */
   39076   int nExtra,              /* Extra bytes append to each in-memory page */
   39077   int flags,               /* flags controlling this file */
   39078   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
   39079   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
   39080 ){
   39081   u8 *pPtr;
   39082   Pager *pPager = 0;       /* Pager object to allocate and return */
   39083   int rc = SQLITE_OK;      /* Return code */
   39084   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
   39085   int memDb = 0;           /* True if this is an in-memory file */
   39086   int readOnly = 0;        /* True if this is a read-only file */
   39087   int journalFileSize;     /* Bytes to allocate for each journal fd */
   39088   char *zPathname = 0;     /* Full path to database file */
   39089   int nPathname = 0;       /* Number of bytes in zPathname */
   39090   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
   39091   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
   39092   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   39093   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   39094 
   39095   /* Figure out how much space is required for each journal file-handle
   39096   ** (there are two of them, the main journal and the sub-journal). This
   39097   ** is the maximum space required for an in-memory journal file handle
   39098   ** and a regular journal file-handle. Note that a "regular journal-handle"
   39099   ** may be a wrapper capable of caching the first portion of the journal
   39100   ** file in memory to implement the atomic-write optimization (see
   39101   ** source file journal.c).
   39102   */
   39103   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
   39104     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
   39105   }else{
   39106     journalFileSize = ROUND8(sqlite3MemJournalSize());
   39107   }
   39108 
   39109   /* Set the output variable to NULL in case an error occurs. */
   39110   *ppPager = 0;
   39111 
   39112 #ifndef SQLITE_OMIT_MEMORYDB
   39113   if( flags & PAGER_MEMORY ){
   39114     memDb = 1;
   39115     zFilename = 0;
   39116   }
   39117 #endif
   39118 
   39119   /* Compute and store the full pathname in an allocated buffer pointed
   39120   ** to by zPathname, length nPathname. Or, if this is a temporary file,
   39121   ** leave both nPathname and zPathname set to 0.
   39122   */
   39123   if( zFilename && zFilename[0] ){
   39124     nPathname = pVfs->mxPathname+1;
   39125     zPathname = sqlite3Malloc(nPathname*2);
   39126     if( zPathname==0 ){
   39127       return SQLITE_NOMEM;
   39128     }
   39129     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
   39130     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
   39131     nPathname = sqlite3Strlen30(zPathname);
   39132     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
   39133       /* This branch is taken when the journal path required by
   39134       ** the database being opened will be more than pVfs->mxPathname
   39135       ** bytes in length. This means the database cannot be opened,
   39136       ** as it will not be possible to open the journal file or even
   39137       ** check for a hot-journal before reading.
   39138       */
   39139       rc = SQLITE_CANTOPEN_BKPT;
   39140     }
   39141     if( rc!=SQLITE_OK ){
   39142       sqlite3_free(zPathname);
   39143       return rc;
   39144     }
   39145   }
   39146 
   39147   /* Allocate memory for the Pager structure, PCache object, the
   39148   ** three file descriptors, the database file name and the journal
   39149   ** file name. The layout in memory is as follows:
   39150   **
   39151   **     Pager object                    (sizeof(Pager) bytes)
   39152   **     PCache object                   (sqlite3PcacheSize() bytes)
   39153   **     Database file handle            (pVfs->szOsFile bytes)
   39154   **     Sub-journal file handle         (journalFileSize bytes)
   39155   **     Main journal file handle        (journalFileSize bytes)
   39156   **     Database file name              (nPathname+1 bytes)
   39157   **     Journal file name               (nPathname+8+1 bytes)
   39158   */
   39159   pPtr = (u8 *)sqlite3MallocZero(
   39160     ROUND8(sizeof(*pPager)) +      /* Pager structure */
   39161     ROUND8(pcacheSize) +           /* PCache object */
   39162     ROUND8(pVfs->szOsFile) +       /* The main db file */
   39163     journalFileSize * 2 +          /* The two journal files */
   39164     nPathname + 1 +                /* zFilename */
   39165     nPathname + 8 + 1              /* zJournal */
   39166 #ifndef SQLITE_OMIT_WAL
   39167     + nPathname + 4 + 1              /* zWal */
   39168 #endif
   39169   );
   39170   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   39171   if( !pPtr ){
   39172     sqlite3_free(zPathname);
   39173     return SQLITE_NOMEM;
   39174   }
   39175   pPager =              (Pager*)(pPtr);
   39176   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
   39177   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
   39178   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
   39179   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
   39180   pPager->zFilename =    (char*)(pPtr += journalFileSize);
   39181   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
   39182 
   39183   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
   39184   if( zPathname ){
   39185     assert( nPathname>0 );
   39186     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
   39187     memcpy(pPager->zFilename, zPathname, nPathname);
   39188     memcpy(pPager->zJournal, zPathname, nPathname);
   39189     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
   39190 #ifndef SQLITE_OMIT_WAL
   39191     pPager->zWal = &pPager->zJournal[nPathname+8+1];
   39192     memcpy(pPager->zWal, zPathname, nPathname);
   39193     memcpy(&pPager->zWal[nPathname], "-wal", 4);
   39194 #endif
   39195     sqlite3_free(zPathname);
   39196   }
   39197   pPager->pVfs = pVfs;
   39198   pPager->vfsFlags = vfsFlags;
   39199 
   39200   /* Open the pager file.
   39201   */
   39202   if( zFilename && zFilename[0] ){
   39203     int fout = 0;                    /* VFS flags returned by xOpen() */
   39204     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
   39205     assert( !memDb );
   39206     readOnly = (fout&SQLITE_OPEN_READONLY);
   39207 
   39208     /* If the file was successfully opened for read/write access,
   39209     ** choose a default page size in case we have to create the
   39210     ** database file. The default page size is the maximum of:
   39211     **
   39212     **    + SQLITE_DEFAULT_PAGE_SIZE,
   39213     **    + The value returned by sqlite3OsSectorSize()
   39214     **    + The largest page size that can be written atomically.
   39215     */
   39216     if( rc==SQLITE_OK && !readOnly ){
   39217       setSectorSize(pPager);
   39218       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
   39219       if( szPageDflt<pPager->sectorSize ){
   39220         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
   39221           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
   39222         }else{
   39223           szPageDflt = (u32)pPager->sectorSize;
   39224         }
   39225       }
   39226 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   39227       {
   39228         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
   39229         int ii;
   39230         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
   39231         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
   39232         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
   39233         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
   39234           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
   39235             szPageDflt = ii;
   39236           }
   39237         }
   39238       }
   39239 #endif
   39240     }
   39241   }else{
   39242     /* If a temporary file is requested, it is not opened immediately.
   39243     ** In this case we accept the default page size and delay actually
   39244     ** opening the file until the first call to OsWrite().
   39245     **
   39246     ** This branch is also run for an in-memory database. An in-memory
   39247     ** database is the same as a temp-file that is never written out to
   39248     ** disk and uses an in-memory rollback journal.
   39249     */
   39250     tempFile = 1;
   39251     pPager->eState = PAGER_READER;
   39252     pPager->eLock = EXCLUSIVE_LOCK;
   39253     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   39254   }
   39255 
   39256   /* The following call to PagerSetPagesize() serves to set the value of
   39257   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   39258   */
   39259   if( rc==SQLITE_OK ){
   39260     assert( pPager->memDb==0 );
   39261     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
   39262     testcase( rc!=SQLITE_OK );
   39263   }
   39264 
   39265   /* If an error occurred in either of the blocks above, free the
   39266   ** Pager structure and close the file.
   39267   */
   39268   if( rc!=SQLITE_OK ){
   39269     assert( !pPager->pTmpSpace );
   39270     sqlite3OsClose(pPager->fd);
   39271     sqlite3_free(pPager);
   39272     return rc;
   39273   }
   39274 
   39275   /* Initialize the PCache object. */
   39276   assert( nExtra<1000 );
   39277   nExtra = ROUND8(nExtra);
   39278   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
   39279                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
   39280 
   39281   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
   39282   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
   39283 
   39284   pPager->useJournal = (u8)useJournal;
   39285   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
   39286   /* pPager->stmtOpen = 0; */
   39287   /* pPager->stmtInUse = 0; */
   39288   /* pPager->nRef = 0; */
   39289   /* pPager->stmtSize = 0; */
   39290   /* pPager->stmtJSize = 0; */
   39291   /* pPager->nPage = 0; */
   39292   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
   39293   /* pPager->state = PAGER_UNLOCK; */
   39294 #if 0
   39295   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
   39296 #endif
   39297   /* pPager->errMask = 0; */
   39298   pPager->tempFile = (u8)tempFile;
   39299   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
   39300           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   39301   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
   39302   pPager->exclusiveMode = (u8)tempFile;
   39303   pPager->changeCountDone = pPager->tempFile;
   39304   pPager->memDb = (u8)memDb;
   39305   pPager->readOnly = (u8)readOnly;
   39306   assert( useJournal || pPager->tempFile );
   39307   pPager->noSync = pPager->tempFile;
   39308   pPager->fullSync = pPager->noSync ?0:1;
   39309   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
   39310   pPager->ckptSyncFlags = pPager->syncFlags;
   39311   /* pPager->pFirst = 0; */
   39312   /* pPager->pFirstSynced = 0; */
   39313   /* pPager->pLast = 0; */
   39314   pPager->nExtra = (u16)nExtra;
   39315   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
   39316   assert( isOpen(pPager->fd) || tempFile );
   39317   setSectorSize(pPager);
   39318   if( !useJournal ){
   39319     pPager->journalMode = PAGER_JOURNALMODE_OFF;
   39320   }else if( memDb ){
   39321     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
   39322   }
   39323   /* pPager->xBusyHandler = 0; */
   39324   /* pPager->pBusyHandlerArg = 0; */
   39325   pPager->xReiniter = xReinit;
   39326   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
   39327 
   39328   *ppPager = pPager;
   39329   return SQLITE_OK;
   39330 }
   39331 
   39332 
   39333 
   39334 /*
   39335 ** This function is called after transitioning from PAGER_UNLOCK to
   39336 ** PAGER_SHARED state. It tests if there is a hot journal present in
   39337 ** the file-system for the given pager. A hot journal is one that
   39338 ** needs to be played back. According to this function, a hot-journal
   39339 ** file exists if the following criteria are met:
   39340 **
   39341 **   * The journal file exists in the file system, and
   39342 **   * No process holds a RESERVED or greater lock on the database file, and
   39343 **   * The database file itself is greater than 0 bytes in size, and
   39344 **   * The first byte of the journal file exists and is not 0x00.
   39345 **
   39346 ** If the current size of the database file is 0 but a journal file
   39347 ** exists, that is probably an old journal left over from a prior
   39348 ** database with the same name. In this case the journal file is
   39349 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
   39350 ** is returned.
   39351 **
   39352 ** This routine does not check if there is a master journal filename
   39353 ** at the end of the file. If there is, and that master journal file
   39354 ** does not exist, then the journal file is not really hot. In this
   39355 ** case this routine will return a false-positive. The pager_playback()
   39356 ** routine will discover that the journal file is not really hot and
   39357 ** will not roll it back.
   39358 **
   39359 ** If a hot-journal file is found to exist, *pExists is set to 1 and
   39360 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
   39361 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
   39362 ** to determine whether or not a hot-journal file exists, the IO error
   39363 ** code is returned and the value of *pExists is undefined.
   39364 */
   39365 static int hasHotJournal(Pager *pPager, int *pExists){
   39366   sqlite3_vfs * const pVfs = pPager->pVfs;
   39367   int rc = SQLITE_OK;           /* Return code */
   39368   int exists = 1;               /* True if a journal file is present */
   39369   int jrnlOpen = !!isOpen(pPager->jfd);
   39370 
   39371   assert( pPager->useJournal );
   39372   assert( isOpen(pPager->fd) );
   39373   assert( pPager->eState==PAGER_OPEN );
   39374 
   39375   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
   39376     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
   39377   ));
   39378 
   39379   *pExists = 0;
   39380   if( !jrnlOpen ){
   39381     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
   39382   }
   39383   if( rc==SQLITE_OK && exists ){
   39384     int locked = 0;             /* True if some process holds a RESERVED lock */
   39385 
   39386     /* Race condition here:  Another process might have been holding the
   39387     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
   39388     ** call above, but then delete the journal and drop the lock before
   39389     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
   39390     ** is the case, this routine might think there is a hot journal when
   39391     ** in fact there is none.  This results in a false-positive which will
   39392     ** be dealt with by the playback routine.  Ticket #3883.
   39393     */
   39394     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
   39395     if( rc==SQLITE_OK && !locked ){
   39396       Pgno nPage;                 /* Number of pages in database file */
   39397 
   39398       /* Check the size of the database file. If it consists of 0 pages,
   39399       ** then delete the journal file. See the header comment above for
   39400       ** the reasoning here.  Delete the obsolete journal file under
   39401       ** a RESERVED lock to avoid race conditions and to avoid violating
   39402       ** [H33020].
   39403       */
   39404       rc = pagerPagecount(pPager, &nPage);
   39405       if( rc==SQLITE_OK ){
   39406         if( nPage==0 ){
   39407           sqlite3BeginBenignMalloc();
   39408           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
   39409             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
   39410             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
   39411           }
   39412           sqlite3EndBenignMalloc();
   39413         }else{
   39414           /* The journal file exists and no other connection has a reserved
   39415           ** or greater lock on the database file. Now check that there is
   39416           ** at least one non-zero bytes at the start of the journal file.
   39417           ** If there is, then we consider this journal to be hot. If not,
   39418           ** it can be ignored.
   39419           */
   39420           if( !jrnlOpen ){
   39421             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
   39422             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
   39423           }
   39424           if( rc==SQLITE_OK ){
   39425             u8 first = 0;
   39426             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
   39427             if( rc==SQLITE_IOERR_SHORT_READ ){
   39428               rc = SQLITE_OK;
   39429             }
   39430             if( !jrnlOpen ){
   39431               sqlite3OsClose(pPager->jfd);
   39432             }
   39433             *pExists = (first!=0);
   39434           }else if( rc==SQLITE_CANTOPEN ){
   39435             /* If we cannot open the rollback journal file in order to see if
   39436             ** its has a zero header, that might be due to an I/O error, or
   39437             ** it might be due to the race condition described above and in
   39438             ** ticket #3883.  Either way, assume that the journal is hot.
   39439             ** This might be a false positive.  But if it is, then the
   39440             ** automatic journal playback and recovery mechanism will deal
   39441             ** with it under an EXCLUSIVE lock where we do not need to
   39442             ** worry so much with race conditions.
   39443             */
   39444             *pExists = 1;
   39445             rc = SQLITE_OK;
   39446           }
   39447         }
   39448       }
   39449     }
   39450   }
   39451 
   39452   return rc;
   39453 }
   39454 
   39455 /*
   39456 ** This function is called to obtain a shared lock on the database file.
   39457 ** It is illegal to call sqlite3PagerAcquire() until after this function
   39458 ** has been successfully called. If a shared-lock is already held when
   39459 ** this function is called, it is a no-op.
   39460 **
   39461 ** The following operations are also performed by this function.
   39462 **
   39463 **   1) If the pager is currently in PAGER_OPEN state (no lock held
   39464 **      on the database file), then an attempt is made to obtain a
   39465 **      SHARED lock on the database file. Immediately after obtaining
   39466 **      the SHARED lock, the file-system is checked for a hot-journal,
   39467 **      which is played back if present. Following any hot-journal
   39468 **      rollback, the contents of the cache are validated by checking
   39469 **      the 'change-counter' field of the database file header and
   39470 **      discarded if they are found to be invalid.
   39471 **
   39472 **   2) If the pager is running in exclusive-mode, and there are currently
   39473 **      no outstanding references to any pages, and is in the error state,
   39474 **      then an attempt is made to clear the error state by discarding
   39475 **      the contents of the page cache and rolling back any open journal
   39476 **      file.
   39477 **
   39478 ** If everything is successful, SQLITE_OK is returned. If an IO error
   39479 ** occurs while locking the database, checking for a hot-journal file or
   39480 ** rolling back a journal file, the IO error code is returned.
   39481 */
   39482 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
   39483   int rc = SQLITE_OK;                /* Return code */
   39484 
   39485   /* This routine is only called from b-tree and only when there are no
   39486   ** outstanding pages. This implies that the pager state should either
   39487   ** be OPEN or READER. READER is only possible if the pager is or was in
   39488   ** exclusive access mode.
   39489   */
   39490   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   39491   assert( assert_pager_state(pPager) );
   39492   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
   39493   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
   39494 
   39495   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
   39496     int bHotJournal = 1;          /* True if there exists a hot journal-file */
   39497 
   39498     assert( !MEMDB );
   39499     assert( pPager->noReadlock==0 || pPager->readOnly );
   39500 
   39501     if( pPager->noReadlock==0 ){
   39502       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
   39503       if( rc!=SQLITE_OK ){
   39504         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
   39505         goto failed;
   39506       }
   39507     }
   39508 
   39509     /* If a journal file exists, and there is no RESERVED lock on the
   39510     ** database file, then it either needs to be played back or deleted.
   39511     */
   39512     if( pPager->eLock<=SHARED_LOCK ){
   39513       rc = hasHotJournal(pPager, &bHotJournal);
   39514     }
   39515     if( rc!=SQLITE_OK ){
   39516       goto failed;
   39517     }
   39518     if( bHotJournal ){
   39519       /* Get an EXCLUSIVE lock on the database file. At this point it is
   39520       ** important that a RESERVED lock is not obtained on the way to the
   39521       ** EXCLUSIVE lock. If it were, another process might open the
   39522       ** database file, detect the RESERVED lock, and conclude that the
   39523       ** database is safe to read while this process is still rolling the
   39524       ** hot-journal back.
   39525       **
   39526       ** Because the intermediate RESERVED lock is not requested, any
   39527       ** other process attempting to access the database file will get to
   39528       ** this point in the code and fail to obtain its own EXCLUSIVE lock
   39529       ** on the database file.
   39530       **
   39531       ** Unless the pager is in locking_mode=exclusive mode, the lock is
   39532       ** downgraded to SHARED_LOCK before this function returns.
   39533       */
   39534       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   39535       if( rc!=SQLITE_OK ){
   39536         goto failed;
   39537       }
   39538 
   39539       /* If it is not already open and the file exists on disk, open the
   39540       ** journal for read/write access. Write access is required because
   39541       ** in exclusive-access mode the file descriptor will be kept open
   39542       ** and possibly used for a transaction later on. Also, write-access
   39543       ** is usually required to finalize the journal in journal_mode=persist
   39544       ** mode (and also for journal_mode=truncate on some systems).
   39545       **
   39546       ** If the journal does not exist, it usually means that some
   39547       ** other connection managed to get in and roll it back before
   39548       ** this connection obtained the exclusive lock above. Or, it
   39549       ** may mean that the pager was in the error-state when this
   39550       ** function was called and the journal file does not exist.
   39551       */
   39552       if( !isOpen(pPager->jfd) ){
   39553         sqlite3_vfs * const pVfs = pPager->pVfs;
   39554         int bExists;              /* True if journal file exists */
   39555         rc = sqlite3OsAccess(
   39556             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
   39557         if( rc==SQLITE_OK && bExists ){
   39558           int fout = 0;
   39559           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
   39560           assert( !pPager->tempFile );
   39561           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
   39562           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   39563           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
   39564             rc = SQLITE_CANTOPEN_BKPT;
   39565             sqlite3OsClose(pPager->jfd);
   39566           }
   39567         }
   39568       }
   39569 
   39570       /* Playback and delete the journal.  Drop the database write
   39571       ** lock and reacquire the read lock. Purge the cache before
   39572       ** playing back the hot-journal so that we don't end up with
   39573       ** an inconsistent cache.  Sync the hot journal before playing
   39574       ** it back since the process that crashed and left the hot journal
   39575       ** probably did not sync it and we are required to always sync
   39576       ** the journal before playing it back.
   39577       */
   39578       if( isOpen(pPager->jfd) ){
   39579         assert( rc==SQLITE_OK );
   39580         rc = pagerSyncHotJournal(pPager);
   39581         if( rc==SQLITE_OK ){
   39582           rc = pager_playback(pPager, 1);
   39583           pPager->eState = PAGER_OPEN;
   39584         }
   39585       }else if( !pPager->exclusiveMode ){
   39586         pagerUnlockDb(pPager, SHARED_LOCK);
   39587       }
   39588 
   39589       if( rc!=SQLITE_OK ){
   39590         /* This branch is taken if an error occurs while trying to open
   39591         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
   39592         ** pager_unlock() routine will be called before returning to unlock
   39593         ** the file. If the unlock attempt fails, then Pager.eLock must be
   39594         ** set to UNKNOWN_LOCK (see the comment above the #define for
   39595         ** UNKNOWN_LOCK above for an explanation).
   39596         **
   39597         ** In order to get pager_unlock() to do this, set Pager.eState to
   39598         ** PAGER_ERROR now. This is not actually counted as a transition
   39599         ** to ERROR state in the state diagram at the top of this file,
   39600         ** since we know that the same call to pager_unlock() will very
   39601         ** shortly transition the pager object to the OPEN state. Calling
   39602         ** assert_pager_state() would fail now, as it should not be possible
   39603         ** to be in ERROR state when there are zero outstanding page
   39604         ** references.
   39605         */
   39606         pager_error(pPager, rc);
   39607         goto failed;
   39608       }
   39609 
   39610       assert( pPager->eState==PAGER_OPEN );
   39611       assert( (pPager->eLock==SHARED_LOCK)
   39612            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
   39613       );
   39614     }
   39615 
   39616     if( !pPager->tempFile
   39617      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
   39618     ){
   39619       /* The shared-lock has just been acquired on the database file
   39620       ** and there are already pages in the cache (from a previous
   39621       ** read or write transaction).  Check to see if the database
   39622       ** has been modified.  If the database has changed, flush the
   39623       ** cache.
   39624       **
   39625       ** Database changes is detected by looking at 15 bytes beginning
   39626       ** at offset 24 into the file.  The first 4 of these 16 bytes are
   39627       ** a 32-bit counter that is incremented with each change.  The
   39628       ** other bytes change randomly with each file change when
   39629       ** a codec is in use.
   39630       **
   39631       ** There is a vanishingly small chance that a change will not be
   39632       ** detected.  The chance of an undetected change is so small that
   39633       ** it can be neglected.
   39634       */
   39635       Pgno nPage = 0;
   39636       char dbFileVers[sizeof(pPager->dbFileVers)];
   39637 
   39638       rc = pagerPagecount(pPager, &nPage);
   39639       if( rc ) goto failed;
   39640 
   39641       if( nPage>0 ){
   39642         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
   39643         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
   39644         if( rc!=SQLITE_OK ){
   39645           goto failed;
   39646         }
   39647       }else{
   39648         memset(dbFileVers, 0, sizeof(dbFileVers));
   39649       }
   39650 
   39651       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
   39652         pager_reset(pPager);
   39653       }
   39654     }
   39655 
   39656     /* If there is a WAL file in the file-system, open this database in WAL
   39657     ** mode. Otherwise, the following function call is a no-op.
   39658     */
   39659     rc = pagerOpenWalIfPresent(pPager);
   39660 #ifndef SQLITE_OMIT_WAL
   39661     assert( pPager->pWal==0 || rc==SQLITE_OK );
   39662 #endif
   39663   }
   39664 
   39665   if( pagerUseWal(pPager) ){
   39666     assert( rc==SQLITE_OK );
   39667     rc = pagerBeginReadTransaction(pPager);
   39668   }
   39669 
   39670   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
   39671     rc = pagerPagecount(pPager, &pPager->dbSize);
   39672   }
   39673 
   39674  failed:
   39675   if( rc!=SQLITE_OK ){
   39676     assert( !MEMDB );
   39677     pager_unlock(pPager);
   39678     assert( pPager->eState==PAGER_OPEN );
   39679   }else{
   39680     pPager->eState = PAGER_READER;
   39681   }
   39682   return rc;
   39683 }
   39684 
   39685 /*
   39686 ** If the reference count has reached zero, rollback any active
   39687 ** transaction and unlock the pager.
   39688 **
   39689 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
   39690 ** the rollback journal, the unlock is not performed and there is
   39691 ** nothing to rollback, so this routine is a no-op.
   39692 */
   39693 static void pagerUnlockIfUnused(Pager *pPager){
   39694   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
   39695     pagerUnlockAndRollback(pPager);
   39696   }
   39697 }
   39698 
   39699 /*
   39700 ** Acquire a reference to page number pgno in pager pPager (a page
   39701 ** reference has type DbPage*). If the requested reference is
   39702 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
   39703 **
   39704 ** If the requested page is already in the cache, it is returned.
   39705 ** Otherwise, a new page object is allocated and populated with data
   39706 ** read from the database file. In some cases, the pcache module may
   39707 ** choose not to allocate a new page object and may reuse an existing
   39708 ** object with no outstanding references.
   39709 **
   39710 ** The extra data appended to a page is always initialized to zeros the
   39711 ** first time a page is loaded into memory. If the page requested is
   39712 ** already in the cache when this function is called, then the extra
   39713 ** data is left as it was when the page object was last used.
   39714 **
   39715 ** If the database image is smaller than the requested page or if a
   39716 ** non-zero value is passed as the noContent parameter and the
   39717 ** requested page is not already stored in the cache, then no
   39718 ** actual disk read occurs. In this case the memory image of the
   39719 ** page is initialized to all zeros.
   39720 **
   39721 ** If noContent is true, it means that we do not care about the contents
   39722 ** of the page. This occurs in two seperate scenarios:
   39723 **
   39724 **   a) When reading a free-list leaf page from the database, and
   39725 **
   39726 **   b) When a savepoint is being rolled back and we need to load
   39727 **      a new page into the cache to be filled with the data read
   39728 **      from the savepoint journal.
   39729 **
   39730 ** If noContent is true, then the data returned is zeroed instead of
   39731 ** being read from the database. Additionally, the bits corresponding
   39732 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
   39733 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
   39734 ** savepoints are set. This means if the page is made writable at any
   39735 ** point in the future, using a call to sqlite3PagerWrite(), its contents
   39736 ** will not be journaled. This saves IO.
   39737 **
   39738 ** The acquisition might fail for several reasons.  In all cases,
   39739 ** an appropriate error code is returned and *ppPage is set to NULL.
   39740 **
   39741 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
   39742 ** to find a page in the in-memory cache first.  If the page is not already
   39743 ** in memory, this routine goes to disk to read it in whereas Lookup()
   39744 ** just returns 0.  This routine acquires a read-lock the first time it
   39745 ** has to go to disk, and could also playback an old journal if necessary.
   39746 ** Since Lookup() never goes to disk, it never has to deal with locks
   39747 ** or journal files.
   39748 */
   39749 SQLITE_PRIVATE int sqlite3PagerAcquire(
   39750   Pager *pPager,      /* The pager open on the database file */
   39751   Pgno pgno,          /* Page number to fetch */
   39752   DbPage **ppPage,    /* Write a pointer to the page here */
   39753   int noContent       /* Do not bother reading content from disk if true */
   39754 ){
   39755   int rc;
   39756   PgHdr *pPg;
   39757 
   39758   assert( pPager->eState>=PAGER_READER );
   39759   assert( assert_pager_state(pPager) );
   39760 
   39761   if( pgno==0 ){
   39762     return SQLITE_CORRUPT_BKPT;
   39763   }
   39764 
   39765   /* If the pager is in the error state, return an error immediately.
   39766   ** Otherwise, request the page from the PCache layer. */
   39767   if( pPager->errCode!=SQLITE_OK ){
   39768     rc = pPager->errCode;
   39769   }else{
   39770     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
   39771   }
   39772 
   39773   if( rc!=SQLITE_OK ){
   39774     /* Either the call to sqlite3PcacheFetch() returned an error or the
   39775     ** pager was already in the error-state when this function was called.
   39776     ** Set pPg to 0 and jump to the exception handler.  */
   39777     pPg = 0;
   39778     goto pager_acquire_err;
   39779   }
   39780   assert( (*ppPage)->pgno==pgno );
   39781   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
   39782 
   39783   if( (*ppPage)->pPager && !noContent ){
   39784     /* In this case the pcache already contains an initialized copy of
   39785     ** the page. Return without further ado.  */
   39786     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
   39787     PAGER_INCR(pPager->nHit);
   39788     return SQLITE_OK;
   39789 
   39790   }else{
   39791     /* The pager cache has created a new page. Its content needs to
   39792     ** be initialized.  */
   39793 
   39794     PAGER_INCR(pPager->nMiss);
   39795     pPg = *ppPage;
   39796     pPg->pPager = pPager;
   39797 
   39798     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
   39799     ** number greater than this, or the unused locking-page, is requested. */
   39800     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
   39801       rc = SQLITE_CORRUPT_BKPT;
   39802       goto pager_acquire_err;
   39803     }
   39804 
   39805     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
   39806       if( pgno>pPager->mxPgno ){
   39807         rc = SQLITE_FULL;
   39808         goto pager_acquire_err;
   39809       }
   39810       if( noContent ){
   39811         /* Failure to set the bits in the InJournal bit-vectors is benign.
   39812         ** It merely means that we might do some extra work to journal a
   39813         ** page that does not need to be journaled.  Nevertheless, be sure
   39814         ** to test the case where a malloc error occurs while trying to set
   39815         ** a bit in a bit vector.
   39816         */
   39817         sqlite3BeginBenignMalloc();
   39818         if( pgno<=pPager->dbOrigSize ){
   39819           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
   39820           testcase( rc==SQLITE_NOMEM );
   39821         }
   39822         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
   39823         testcase( rc==SQLITE_NOMEM );
   39824         sqlite3EndBenignMalloc();
   39825       }
   39826       memset(pPg->pData, 0, pPager->pageSize);
   39827       IOTRACE(("ZERO %p %d\n", pPager, pgno));
   39828     }else{
   39829       assert( pPg->pPager==pPager );
   39830       rc = readDbPage(pPg);
   39831       if( rc!=SQLITE_OK ){
   39832         goto pager_acquire_err;
   39833       }
   39834     }
   39835     pager_set_pagehash(pPg);
   39836   }
   39837 
   39838   return SQLITE_OK;
   39839 
   39840 pager_acquire_err:
   39841   assert( rc!=SQLITE_OK );
   39842   if( pPg ){
   39843     sqlite3PcacheDrop(pPg);
   39844   }
   39845   pagerUnlockIfUnused(pPager);
   39846 
   39847   *ppPage = 0;
   39848   return rc;
   39849 }
   39850 
   39851 /*
   39852 ** Acquire a page if it is already in the in-memory cache.  Do
   39853 ** not read the page from disk.  Return a pointer to the page,
   39854 ** or 0 if the page is not in cache.
   39855 **
   39856 ** See also sqlite3PagerGet().  The difference between this routine
   39857 ** and sqlite3PagerGet() is that _get() will go to the disk and read
   39858 ** in the page if the page is not already in cache.  This routine
   39859 ** returns NULL if the page is not in cache or if a disk I/O error
   39860 ** has ever happened.
   39861 */
   39862 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
   39863   PgHdr *pPg = 0;
   39864   assert( pPager!=0 );
   39865   assert( pgno!=0 );
   39866   assert( pPager->pPCache!=0 );
   39867   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
   39868   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
   39869   return pPg;
   39870 }
   39871 
   39872 /*
   39873 ** Release a page reference.
   39874 **
   39875 ** If the number of references to the page drop to zero, then the
   39876 ** page is added to the LRU list.  When all references to all pages
   39877 ** are released, a rollback occurs and the lock on the database is
   39878 ** removed.
   39879 */
   39880 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
   39881   if( pPg ){
   39882     Pager *pPager = pPg->pPager;
   39883     sqlite3PcacheRelease(pPg);
   39884     pagerUnlockIfUnused(pPager);
   39885   }
   39886 }
   39887 
   39888 /*
   39889 ** This function is called at the start of every write transaction.
   39890 ** There must already be a RESERVED or EXCLUSIVE lock on the database
   39891 ** file when this routine is called.
   39892 **
   39893 ** Open the journal file for pager pPager and write a journal header
   39894 ** to the start of it. If there are active savepoints, open the sub-journal
   39895 ** as well. This function is only used when the journal file is being
   39896 ** opened to write a rollback log for a transaction. It is not used
   39897 ** when opening a hot journal file to roll it back.
   39898 **
   39899 ** If the journal file is already open (as it may be in exclusive mode),
   39900 ** then this function just writes a journal header to the start of the
   39901 ** already open file.
   39902 **
   39903 ** Whether or not the journal file is opened by this function, the
   39904 ** Pager.pInJournal bitvec structure is allocated.
   39905 **
   39906 ** Return SQLITE_OK if everything is successful. Otherwise, return
   39907 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
   39908 ** an IO error code if opening or writing the journal file fails.
   39909 */
   39910 static int pager_open_journal(Pager *pPager){
   39911   int rc = SQLITE_OK;                        /* Return code */
   39912   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
   39913 
   39914   assert( pPager->eState==PAGER_WRITER_LOCKED );
   39915   assert( assert_pager_state(pPager) );
   39916   assert( pPager->pInJournal==0 );
   39917 
   39918   /* If already in the error state, this function is a no-op.  But on
   39919   ** the other hand, this routine is never called if we are already in
   39920   ** an error state. */
   39921   if( NEVER(pPager->errCode) ) return pPager->errCode;
   39922 
   39923   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
   39924     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
   39925     if( pPager->pInJournal==0 ){
   39926       return SQLITE_NOMEM;
   39927     }
   39928 
   39929     /* Open the journal file if it is not already open. */
   39930     if( !isOpen(pPager->jfd) ){
   39931       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
   39932         sqlite3MemJournalOpen(pPager->jfd);
   39933       }else{
   39934         const int flags =                   /* VFS flags to open journal file */
   39935           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   39936           (pPager->tempFile ?
   39937             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
   39938             (SQLITE_OPEN_MAIN_JOURNAL)
   39939           );
   39940   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   39941         rc = sqlite3JournalOpen(
   39942             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
   39943         );
   39944   #else
   39945         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
   39946   #endif
   39947       }
   39948       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
   39949     }
   39950 
   39951 
   39952     /* Write the first journal header to the journal file and open
   39953     ** the sub-journal if necessary.
   39954     */
   39955     if( rc==SQLITE_OK ){
   39956       /* TODO: Check if all of these are really required. */
   39957       pPager->nRec = 0;
   39958       pPager->journalOff = 0;
   39959       pPager->setMaster = 0;
   39960       pPager->journalHdr = 0;
   39961       rc = writeJournalHdr(pPager);
   39962     }
   39963   }
   39964 
   39965   if( rc!=SQLITE_OK ){
   39966     sqlite3BitvecDestroy(pPager->pInJournal);
   39967     pPager->pInJournal = 0;
   39968   }else{
   39969     assert( pPager->eState==PAGER_WRITER_LOCKED );
   39970     pPager->eState = PAGER_WRITER_CACHEMOD;
   39971   }
   39972 
   39973   return rc;
   39974 }
   39975 
   39976 /*
   39977 ** Begin a write-transaction on the specified pager object. If a
   39978 ** write-transaction has already been opened, this function is a no-op.
   39979 **
   39980 ** If the exFlag argument is false, then acquire at least a RESERVED
   39981 ** lock on the database file. If exFlag is true, then acquire at least
   39982 ** an EXCLUSIVE lock. If such a lock is already held, no locking
   39983 ** functions need be called.
   39984 **
   39985 ** If the subjInMemory argument is non-zero, then any sub-journal opened
   39986 ** within this transaction will be opened as an in-memory file. This
   39987 ** has no effect if the sub-journal is already opened (as it may be when
   39988 ** running in exclusive mode) or if the transaction does not require a
   39989 ** sub-journal. If the subjInMemory argument is zero, then any required
   39990 ** sub-journal is implemented in-memory if pPager is an in-memory database,
   39991 ** or using a temporary file otherwise.
   39992 */
   39993 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
   39994   int rc = SQLITE_OK;
   39995 
   39996   if( pPager->errCode ) return pPager->errCode;
   39997   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
   39998   pPager->subjInMemory = (u8)subjInMemory;
   39999 
   40000   if( ALWAYS(pPager->eState==PAGER_READER) ){
   40001     assert( pPager->pInJournal==0 );
   40002 
   40003     if( pagerUseWal(pPager) ){
   40004       /* If the pager is configured to use locking_mode=exclusive, and an
   40005       ** exclusive lock on the database is not already held, obtain it now.
   40006       */
   40007       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
   40008         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   40009         if( rc!=SQLITE_OK ){
   40010           return rc;
   40011         }
   40012         sqlite3WalExclusiveMode(pPager->pWal, 1);
   40013       }
   40014 
   40015       /* Grab the write lock on the log file. If successful, upgrade to
   40016       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
   40017       ** The busy-handler is not invoked if another connection already
   40018       ** holds the write-lock. If possible, the upper layer will call it.
   40019       */
   40020       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
   40021     }else{
   40022       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
   40023       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
   40024       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
   40025       ** lock, but not when obtaining the RESERVED lock.
   40026       */
   40027       rc = pagerLockDb(pPager, RESERVED_LOCK);
   40028       if( rc==SQLITE_OK && exFlag ){
   40029         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   40030       }
   40031     }
   40032 
   40033     if( rc==SQLITE_OK ){
   40034       /* Change to WRITER_LOCKED state.
   40035       **
   40036       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
   40037       ** when it has an open transaction, but never to DBMOD or FINISHED.
   40038       ** This is because in those states the code to roll back savepoint
   40039       ** transactions may copy data from the sub-journal into the database
   40040       ** file as well as into the page cache. Which would be incorrect in
   40041       ** WAL mode.
   40042       */
   40043       pPager->eState = PAGER_WRITER_LOCKED;
   40044       pPager->dbHintSize = pPager->dbSize;
   40045       pPager->dbFileSize = pPager->dbSize;
   40046       pPager->dbOrigSize = pPager->dbSize;
   40047       pPager->journalOff = 0;
   40048     }
   40049 
   40050     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
   40051     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
   40052     assert( assert_pager_state(pPager) );
   40053   }
   40054 
   40055   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
   40056   return rc;
   40057 }
   40058 
   40059 /*
   40060 ** Mark a single data page as writeable. The page is written into the
   40061 ** main journal or sub-journal as required. If the page is written into
   40062 ** one of the journals, the corresponding bit is set in the
   40063 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
   40064 ** of any open savepoints as appropriate.
   40065 */
   40066 static int pager_write(PgHdr *pPg){
   40067   void *pData = pPg->pData;
   40068   Pager *pPager = pPg->pPager;
   40069   int rc = SQLITE_OK;
   40070 
   40071   /* This routine is not called unless a write-transaction has already
   40072   ** been started. The journal file may or may not be open at this point.
   40073   ** It is never called in the ERROR state.
   40074   */
   40075   assert( pPager->eState==PAGER_WRITER_LOCKED
   40076        || pPager->eState==PAGER_WRITER_CACHEMOD
   40077        || pPager->eState==PAGER_WRITER_DBMOD
   40078   );
   40079   assert( assert_pager_state(pPager) );
   40080 
   40081   /* If an error has been previously detected, report the same error
   40082   ** again. This should not happen, but the check provides robustness. */
   40083   if( NEVER(pPager->errCode) )  return pPager->errCode;
   40084 
   40085   /* Higher-level routines never call this function if database is not
   40086   ** writable.  But check anyway, just for robustness. */
   40087   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
   40088 
   40089   CHECK_PAGE(pPg);
   40090 
   40091   /* The journal file needs to be opened. Higher level routines have already
   40092   ** obtained the necessary locks to begin the write-transaction, but the
   40093   ** rollback journal might not yet be open. Open it now if this is the case.
   40094   **
   40095   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   40096   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   40097   ** an error might occur and the pager would end up in WRITER_LOCKED state
   40098   ** with pages marked as dirty in the cache.
   40099   */
   40100   if( pPager->eState==PAGER_WRITER_LOCKED ){
   40101     rc = pager_open_journal(pPager);
   40102     if( rc!=SQLITE_OK ) return rc;
   40103   }
   40104   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
   40105   assert( assert_pager_state(pPager) );
   40106 
   40107   /* Mark the page as dirty.  If the page has already been written
   40108   ** to the journal then we can return right away.
   40109   */
   40110   sqlite3PcacheMakeDirty(pPg);
   40111   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
   40112     assert( !pagerUseWal(pPager) );
   40113   }else{
   40114 
   40115     /* The transaction journal now exists and we have a RESERVED or an
   40116     ** EXCLUSIVE lock on the main database file.  Write the current page to
   40117     ** the transaction journal if it is not there already.
   40118     */
   40119     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
   40120       assert( pagerUseWal(pPager)==0 );
   40121       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
   40122         u32 cksum;
   40123         char *pData2;
   40124         i64 iOff = pPager->journalOff;
   40125 
   40126         /* We should never write to the journal file the page that
   40127         ** contains the database locks.  The following assert verifies
   40128         ** that we do not. */
   40129         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
   40130 
   40131         assert( pPager->journalHdr<=pPager->journalOff );
   40132         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
   40133         cksum = pager_cksum(pPager, (u8*)pData2);
   40134 
   40135         /* Even if an IO or diskfull error occurs while journalling the
   40136         ** page in the block above, set the need-sync flag for the page.
   40137         ** Otherwise, when the transaction is rolled back, the logic in
   40138         ** playback_one_page() will think that the page needs to be restored
   40139         ** in the database file. And if an IO error occurs while doing so,
   40140         ** then corruption may follow.
   40141         */
   40142         pPg->flags |= PGHDR_NEED_SYNC;
   40143 
   40144         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
   40145         if( rc!=SQLITE_OK ) return rc;
   40146         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
   40147         if( rc!=SQLITE_OK ) return rc;
   40148         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   40149         if( rc!=SQLITE_OK ) return rc;
   40150 
   40151         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
   40152                  pPager->journalOff, pPager->pageSize));
   40153         PAGER_INCR(sqlite3_pager_writej_count);
   40154         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
   40155              PAGERID(pPager), pPg->pgno,
   40156              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
   40157 
   40158         pPager->journalOff += 8 + pPager->pageSize;
   40159         pPager->nRec++;
   40160         assert( pPager->pInJournal!=0 );
   40161         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
   40162         testcase( rc==SQLITE_NOMEM );
   40163         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   40164         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
   40165         if( rc!=SQLITE_OK ){
   40166           assert( rc==SQLITE_NOMEM );
   40167           return rc;
   40168         }
   40169       }else{
   40170         if( pPager->eState!=PAGER_WRITER_DBMOD ){
   40171           pPg->flags |= PGHDR_NEED_SYNC;
   40172         }
   40173         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
   40174                 PAGERID(pPager), pPg->pgno,
   40175                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
   40176       }
   40177     }
   40178 
   40179     /* If the statement journal is open and the page is not in it,
   40180     ** then write the current page to the statement journal.  Note that
   40181     ** the statement journal format differs from the standard journal format
   40182     ** in that it omits the checksums and the header.
   40183     */
   40184     if( subjRequiresPage(pPg) ){
   40185       rc = subjournalPage(pPg);
   40186     }
   40187   }
   40188 
   40189   /* Update the database size and return.
   40190   */
   40191   if( pPager->dbSize<pPg->pgno ){
   40192     pPager->dbSize = pPg->pgno;
   40193   }
   40194   return rc;
   40195 }
   40196 
   40197 /*
   40198 ** Mark a data page as writeable. This routine must be called before
   40199 ** making changes to a page. The caller must check the return value
   40200 ** of this function and be careful not to change any page data unless
   40201 ** this routine returns SQLITE_OK.
   40202 **
   40203 ** The difference between this function and pager_write() is that this
   40204 ** function also deals with the special case where 2 or more pages
   40205 ** fit on a single disk sector. In this case all co-resident pages
   40206 ** must have been written to the journal file before returning.
   40207 **
   40208 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
   40209 ** as appropriate. Otherwise, SQLITE_OK.
   40210 */
   40211 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
   40212   int rc = SQLITE_OK;
   40213 
   40214   PgHdr *pPg = pDbPage;
   40215   Pager *pPager = pPg->pPager;
   40216   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
   40217 
   40218   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   40219   assert( pPager->eState!=PAGER_ERROR );
   40220   assert( assert_pager_state(pPager) );
   40221 
   40222   if( nPagePerSector>1 ){
   40223     Pgno nPageCount;          /* Total number of pages in database file */
   40224     Pgno pg1;                 /* First page of the sector pPg is located on. */
   40225     int nPage = 0;            /* Number of pages starting at pg1 to journal */
   40226     int ii;                   /* Loop counter */
   40227     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
   40228 
   40229     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
   40230     ** a journal header to be written between the pages journaled by
   40231     ** this function.
   40232     */
   40233     assert( !MEMDB );
   40234     assert( pPager->doNotSyncSpill==0 );
   40235     pPager->doNotSyncSpill++;
   40236 
   40237     /* This trick assumes that both the page-size and sector-size are
   40238     ** an integer power of 2. It sets variable pg1 to the identifier
   40239     ** of the first page of the sector pPg is located on.
   40240     */
   40241     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
   40242 
   40243     nPageCount = pPager->dbSize;
   40244     if( pPg->pgno>nPageCount ){
   40245       nPage = (pPg->pgno - pg1)+1;
   40246     }else if( (pg1+nPagePerSector-1)>nPageCount ){
   40247       nPage = nPageCount+1-pg1;
   40248     }else{
   40249       nPage = nPagePerSector;
   40250     }
   40251     assert(nPage>0);
   40252     assert(pg1<=pPg->pgno);
   40253     assert((pg1+nPage)>pPg->pgno);
   40254 
   40255     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
   40256       Pgno pg = pg1+ii;
   40257       PgHdr *pPage;
   40258       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
   40259         if( pg!=PAGER_MJ_PGNO(pPager) ){
   40260           rc = sqlite3PagerGet(pPager, pg, &pPage);
   40261           if( rc==SQLITE_OK ){
   40262             rc = pager_write(pPage);
   40263             if( pPage->flags&PGHDR_NEED_SYNC ){
   40264               needSync = 1;
   40265             }
   40266             sqlite3PagerUnref(pPage);
   40267           }
   40268         }
   40269       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
   40270         if( pPage->flags&PGHDR_NEED_SYNC ){
   40271           needSync = 1;
   40272         }
   40273         sqlite3PagerUnref(pPage);
   40274       }
   40275     }
   40276 
   40277     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   40278     ** starting at pg1, then it needs to be set for all of them. Because
   40279     ** writing to any of these nPage pages may damage the others, the
   40280     ** journal file must contain sync()ed copies of all of them
   40281     ** before any of them can be written out to the database file.
   40282     */
   40283     if( rc==SQLITE_OK && needSync ){
   40284       assert( !MEMDB );
   40285       for(ii=0; ii<nPage; ii++){
   40286         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
   40287         if( pPage ){
   40288           pPage->flags |= PGHDR_NEED_SYNC;
   40289           sqlite3PagerUnref(pPage);
   40290         }
   40291       }
   40292     }
   40293 
   40294     assert( pPager->doNotSyncSpill==1 );
   40295     pPager->doNotSyncSpill--;
   40296   }else{
   40297     rc = pager_write(pDbPage);
   40298   }
   40299   return rc;
   40300 }
   40301 
   40302 /*
   40303 ** Return TRUE if the page given in the argument was previously passed
   40304 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
   40305 ** to change the content of the page.
   40306 */
   40307 #ifndef NDEBUG
   40308 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
   40309   return pPg->flags&PGHDR_DIRTY;
   40310 }
   40311 #endif
   40312 
   40313 /*
   40314 ** A call to this routine tells the pager that it is not necessary to
   40315 ** write the information on page pPg back to the disk, even though
   40316 ** that page might be marked as dirty.  This happens, for example, when
   40317 ** the page has been added as a leaf of the freelist and so its
   40318 ** content no longer matters.
   40319 **
   40320 ** The overlying software layer calls this routine when all of the data
   40321 ** on the given page is unused. The pager marks the page as clean so
   40322 ** that it does not get written to disk.
   40323 **
   40324 ** Tests show that this optimization can quadruple the speed of large
   40325 ** DELETE operations.
   40326 */
   40327 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
   40328   Pager *pPager = pPg->pPager;
   40329   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
   40330     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
   40331     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
   40332     pPg->flags |= PGHDR_DONT_WRITE;
   40333     pager_set_pagehash(pPg);
   40334   }
   40335 }
   40336 
   40337 /*
   40338 ** This routine is called to increment the value of the database file
   40339 ** change-counter, stored as a 4-byte big-endian integer starting at
   40340 ** byte offset 24 of the pager file.  The secondary change counter at
   40341 ** 92 is also updated, as is the SQLite version number at offset 96.
   40342 **
   40343 ** But this only happens if the pPager->changeCountDone flag is false.
   40344 ** To avoid excess churning of page 1, the update only happens once.
   40345 ** See also the pager_write_changecounter() routine that does an
   40346 ** unconditional update of the change counters.
   40347 **
   40348 ** If the isDirectMode flag is zero, then this is done by calling
   40349 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
   40350 ** page data. In this case the file will be updated when the current
   40351 ** transaction is committed.
   40352 **
   40353 ** The isDirectMode flag may only be non-zero if the library was compiled
   40354 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
   40355 ** if isDirect is non-zero, then the database file is updated directly
   40356 ** by writing an updated version of page 1 using a call to the
   40357 ** sqlite3OsWrite() function.
   40358 */
   40359 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
   40360   int rc = SQLITE_OK;
   40361 
   40362   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   40363        || pPager->eState==PAGER_WRITER_DBMOD
   40364   );
   40365   assert( assert_pager_state(pPager) );
   40366 
   40367   /* Declare and initialize constant integer 'isDirect'. If the
   40368   ** atomic-write optimization is enabled in this build, then isDirect
   40369   ** is initialized to the value passed as the isDirectMode parameter
   40370   ** to this function. Otherwise, it is always set to zero.
   40371   **
   40372   ** The idea is that if the atomic-write optimization is not
   40373   ** enabled at compile time, the compiler can omit the tests of
   40374   ** 'isDirect' below, as well as the block enclosed in the
   40375   ** "if( isDirect )" condition.
   40376   */
   40377 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
   40378 # define DIRECT_MODE 0
   40379   assert( isDirectMode==0 );
   40380   UNUSED_PARAMETER(isDirectMode);
   40381 #else
   40382 # define DIRECT_MODE isDirectMode
   40383 #endif
   40384 
   40385   if( !pPager->changeCountDone && pPager->dbSize>0 ){
   40386     PgHdr *pPgHdr;                /* Reference to page 1 */
   40387 
   40388     assert( !pPager->tempFile && isOpen(pPager->fd) );
   40389 
   40390     /* Open page 1 of the file for writing. */
   40391     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
   40392     assert( pPgHdr==0 || rc==SQLITE_OK );
   40393 
   40394     /* If page one was fetched successfully, and this function is not
   40395     ** operating in direct-mode, make page 1 writable.  When not in
   40396     ** direct mode, page 1 is always held in cache and hence the PagerGet()
   40397     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
   40398     */
   40399     if( !DIRECT_MODE && rc==SQLITE_OK ){
   40400       rc = sqlite3PagerWrite(pPgHdr);
   40401     }
   40402 
   40403     if( rc==SQLITE_OK ){
   40404       /* Actually do the update of the change counter */
   40405       pager_write_changecounter(pPgHdr);
   40406 
   40407       /* If running in direct mode, write the contents of page 1 to the file. */
   40408       if( DIRECT_MODE ){
   40409         const void *zBuf;
   40410         assert( pPager->dbFileSize>0 );
   40411         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
   40412         if( rc==SQLITE_OK ){
   40413           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
   40414         }
   40415         if( rc==SQLITE_OK ){
   40416           pPager->changeCountDone = 1;
   40417         }
   40418       }else{
   40419         pPager->changeCountDone = 1;
   40420       }
   40421     }
   40422 
   40423     /* Release the page reference. */
   40424     sqlite3PagerUnref(pPgHdr);
   40425   }
   40426   return rc;
   40427 }
   40428 
   40429 /*
   40430 ** Sync the database file to disk. This is a no-op for in-memory databases
   40431 ** or pages with the Pager.noSync flag set.
   40432 **
   40433 ** If successful, or if called on a pager for which it is a no-op, this
   40434 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
   40435 */
   40436 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
   40437   int rc;                              /* Return code */
   40438   assert( !MEMDB );
   40439   if( pPager->noSync ){
   40440     rc = SQLITE_OK;
   40441   }else{
   40442     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   40443   }
   40444   return rc;
   40445 }
   40446 
   40447 /*
   40448 ** This function may only be called while a write-transaction is active in
   40449 ** rollback. If the connection is in WAL mode, this call is a no-op.
   40450 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
   40451 ** the database file, an attempt is made to obtain one.
   40452 **
   40453 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
   40454 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
   40455 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
   40456 ** returned.
   40457 */
   40458 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   40459   int rc = SQLITE_OK;
   40460   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   40461        || pPager->eState==PAGER_WRITER_DBMOD
   40462        || pPager->eState==PAGER_WRITER_LOCKED
   40463   );
   40464   assert( assert_pager_state(pPager) );
   40465   if( 0==pagerUseWal(pPager) ){
   40466     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
   40467   }
   40468   return rc;
   40469 }
   40470 
   40471 /*
   40472 ** Sync the database file for the pager pPager. zMaster points to the name
   40473 ** of a master journal file that should be written into the individual
   40474 ** journal file. zMaster may be NULL, which is interpreted as no master
   40475 ** journal (a single database transaction).
   40476 **
   40477 ** This routine ensures that:
   40478 **
   40479 **   * The database file change-counter is updated,
   40480 **   * the journal is synced (unless the atomic-write optimization is used),
   40481 **   * all dirty pages are written to the database file,
   40482 **   * the database file is truncated (if required), and
   40483 **   * the database file synced.
   40484 **
   40485 ** The only thing that remains to commit the transaction is to finalize
   40486 ** (delete, truncate or zero the first part of) the journal file (or
   40487 ** delete the master journal file if specified).
   40488 **
   40489 ** Note that if zMaster==NULL, this does not overwrite a previous value
   40490 ** passed to an sqlite3PagerCommitPhaseOne() call.
   40491 **
   40492 ** If the final parameter - noSync - is true, then the database file itself
   40493 ** is not synced. The caller must call sqlite3PagerSync() directly to
   40494 ** sync the database file before calling CommitPhaseTwo() to delete the
   40495 ** journal file in this case.
   40496 */
   40497 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   40498   Pager *pPager,                  /* Pager object */
   40499   const char *zMaster,            /* If not NULL, the master journal name */
   40500   int noSync                      /* True to omit the xSync on the db file */
   40501 ){
   40502   int rc = SQLITE_OK;             /* Return code */
   40503 
   40504   assert( pPager->eState==PAGER_WRITER_LOCKED
   40505        || pPager->eState==PAGER_WRITER_CACHEMOD
   40506        || pPager->eState==PAGER_WRITER_DBMOD
   40507        || pPager->eState==PAGER_ERROR
   40508   );
   40509   assert( assert_pager_state(pPager) );
   40510 
   40511   /* If a prior error occurred, report that error again. */
   40512   if( NEVER(pPager->errCode) ) return pPager->errCode;
   40513 
   40514   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
   40515       pPager->zFilename, zMaster, pPager->dbSize));
   40516 
   40517   /* If no database changes have been made, return early. */
   40518   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
   40519 
   40520   if( MEMDB ){
   40521     /* If this is an in-memory db, or no pages have been written to, or this
   40522     ** function has already been called, it is mostly a no-op.  However, any
   40523     ** backup in progress needs to be restarted.
   40524     */
   40525     sqlite3BackupRestart(pPager->pBackup);
   40526   }else{
   40527     if( pagerUseWal(pPager) ){
   40528       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
   40529       if( pList ){
   40530         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
   40531             (pPager->fullSync ? pPager->syncFlags : 0)
   40532         );
   40533       }
   40534       if( rc==SQLITE_OK ){
   40535         sqlite3PcacheCleanAll(pPager->pPCache);
   40536       }
   40537     }else{
   40538       /* The following block updates the change-counter. Exactly how it
   40539       ** does this depends on whether or not the atomic-update optimization
   40540       ** was enabled at compile time, and if this transaction meets the
   40541       ** runtime criteria to use the operation:
   40542       **
   40543       **    * The file-system supports the atomic-write property for
   40544       **      blocks of size page-size, and
   40545       **    * This commit is not part of a multi-file transaction, and
   40546       **    * Exactly one page has been modified and store in the journal file.
   40547       **
   40548       ** If the optimization was not enabled at compile time, then the
   40549       ** pager_incr_changecounter() function is called to update the change
   40550       ** counter in 'indirect-mode'. If the optimization is compiled in but
   40551       ** is not applicable to this transaction, call sqlite3JournalCreate()
   40552       ** to make sure the journal file has actually been created, then call
   40553       ** pager_incr_changecounter() to update the change-counter in indirect
   40554       ** mode.
   40555       **
   40556       ** Otherwise, if the optimization is both enabled and applicable,
   40557       ** then call pager_incr_changecounter() to update the change-counter
   40558       ** in 'direct' mode. In this case the journal file will never be
   40559       ** created for this transaction.
   40560       */
   40561   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   40562       PgHdr *pPg;
   40563       assert( isOpen(pPager->jfd)
   40564            || pPager->journalMode==PAGER_JOURNALMODE_OFF
   40565            || pPager->journalMode==PAGER_JOURNALMODE_WAL
   40566       );
   40567       if( !zMaster && isOpen(pPager->jfd)
   40568        && pPager->journalOff==jrnlBufferSize(pPager)
   40569        && pPager->dbSize>=pPager->dbOrigSize
   40570        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
   40571       ){
   40572         /* Update the db file change counter via the direct-write method. The
   40573         ** following call will modify the in-memory representation of page 1
   40574         ** to include the updated change counter and then write page 1
   40575         ** directly to the database file. Because of the atomic-write
   40576         ** property of the host file-system, this is safe.
   40577         */
   40578         rc = pager_incr_changecounter(pPager, 1);
   40579       }else{
   40580         rc = sqlite3JournalCreate(pPager->jfd);
   40581         if( rc==SQLITE_OK ){
   40582           rc = pager_incr_changecounter(pPager, 0);
   40583         }
   40584       }
   40585   #else
   40586       rc = pager_incr_changecounter(pPager, 0);
   40587   #endif
   40588       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40589 
   40590       /* If this transaction has made the database smaller, then all pages
   40591       ** being discarded by the truncation must be written to the journal
   40592       ** file. This can only happen in auto-vacuum mode.
   40593       **
   40594       ** Before reading the pages with page numbers larger than the
   40595       ** current value of Pager.dbSize, set dbSize back to the value
   40596       ** that it took at the start of the transaction. Otherwise, the
   40597       ** calls to sqlite3PagerGet() return zeroed pages instead of
   40598       ** reading data from the database file.
   40599       */
   40600   #ifndef SQLITE_OMIT_AUTOVACUUM
   40601       if( pPager->dbSize<pPager->dbOrigSize
   40602        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
   40603       ){
   40604         Pgno i;                                   /* Iterator variable */
   40605         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
   40606         const Pgno dbSize = pPager->dbSize;       /* Database image size */
   40607         pPager->dbSize = pPager->dbOrigSize;
   40608         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
   40609           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
   40610             PgHdr *pPage;             /* Page to journal */
   40611             rc = sqlite3PagerGet(pPager, i, &pPage);
   40612             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40613             rc = sqlite3PagerWrite(pPage);
   40614             sqlite3PagerUnref(pPage);
   40615             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40616           }
   40617         }
   40618         pPager->dbSize = dbSize;
   40619       }
   40620   #endif
   40621 
   40622       /* Write the master journal name into the journal file. If a master
   40623       ** journal file name has already been written to the journal file,
   40624       ** or if zMaster is NULL (no master journal), then this call is a no-op.
   40625       */
   40626       rc = writeMasterJournal(pPager, zMaster);
   40627       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40628 
   40629       /* Sync the journal file and write all dirty pages to the database.
   40630       ** If the atomic-update optimization is being used, this sync will not
   40631       ** create the journal file or perform any real IO.
   40632       **
   40633       ** Because the change-counter page was just modified, unless the
   40634       ** atomic-update optimization is used it is almost certain that the
   40635       ** journal requires a sync here. However, in locking_mode=exclusive
   40636       ** on a system under memory pressure it is just possible that this is
   40637       ** not the case. In this case it is likely enough that the redundant
   40638       ** xSync() call will be changed to a no-op by the OS anyhow.
   40639       */
   40640       rc = syncJournal(pPager, 0);
   40641       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40642 
   40643       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
   40644       if( rc!=SQLITE_OK ){
   40645         assert( rc!=SQLITE_IOERR_BLOCKED );
   40646         goto commit_phase_one_exit;
   40647       }
   40648       sqlite3PcacheCleanAll(pPager->pPCache);
   40649 
   40650       /* If the file on disk is not the same size as the database image,
   40651       ** then use pager_truncate to grow or shrink the file here.
   40652       */
   40653       if( pPager->dbSize!=pPager->dbFileSize ){
   40654         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
   40655         assert( pPager->eState==PAGER_WRITER_DBMOD );
   40656         rc = pager_truncate(pPager, nNew);
   40657         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
   40658       }
   40659 
   40660       /* Finally, sync the database file. */
   40661       if( !pPager->noSync && !noSync ){
   40662         rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
   40663       }
   40664       IOTRACE(("DBSYNC %p\n", pPager))
   40665     }
   40666   }
   40667 
   40668 commit_phase_one_exit:
   40669   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
   40670     pPager->eState = PAGER_WRITER_FINISHED;
   40671   }
   40672   return rc;
   40673 }
   40674 
   40675 
   40676 /*
   40677 ** When this function is called, the database file has been completely
   40678 ** updated to reflect the changes made by the current transaction and
   40679 ** synced to disk. The journal file still exists in the file-system
   40680 ** though, and if a failure occurs at this point it will eventually
   40681 ** be used as a hot-journal and the current transaction rolled back.
   40682 **
   40683 ** This function finalizes the journal file, either by deleting,
   40684 ** truncating or partially zeroing it, so that it cannot be used
   40685 ** for hot-journal rollback. Once this is done the transaction is
   40686 ** irrevocably committed.
   40687 **
   40688 ** If an error occurs, an IO error code is returned and the pager
   40689 ** moves into the error state. Otherwise, SQLITE_OK is returned.
   40690 */
   40691 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   40692   int rc = SQLITE_OK;                  /* Return code */
   40693 
   40694   /* This routine should not be called if a prior error has occurred.
   40695   ** But if (due to a coding error elsewhere in the system) it does get
   40696   ** called, just return the same error code without doing anything. */
   40697   if( NEVER(pPager->errCode) ) return pPager->errCode;
   40698 
   40699   assert( pPager->eState==PAGER_WRITER_LOCKED
   40700        || pPager->eState==PAGER_WRITER_FINISHED
   40701        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
   40702   );
   40703   assert( assert_pager_state(pPager) );
   40704 
   40705   /* An optimization. If the database was not actually modified during
   40706   ** this transaction, the pager is running in exclusive-mode and is
   40707   ** using persistent journals, then this function is a no-op.
   40708   **
   40709   ** The start of the journal file currently contains a single journal
   40710   ** header with the nRec field set to 0. If such a journal is used as
   40711   ** a hot-journal during hot-journal rollback, 0 changes will be made
   40712   ** to the database file. So there is no need to zero the journal
   40713   ** header. Since the pager is in exclusive mode, there is no need
   40714   ** to drop any locks either.
   40715   */
   40716   if( pPager->eState==PAGER_WRITER_LOCKED
   40717    && pPager->exclusiveMode
   40718    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   40719   ){
   40720     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
   40721     pPager->eState = PAGER_READER;
   40722     return SQLITE_OK;
   40723   }
   40724 
   40725   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
   40726   rc = pager_end_transaction(pPager, pPager->setMaster);
   40727   return pager_error(pPager, rc);
   40728 }
   40729 
   40730 /*
   40731 ** If a write transaction is open, then all changes made within the
   40732 ** transaction are reverted and the current write-transaction is closed.
   40733 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
   40734 ** state if an error occurs.
   40735 **
   40736 ** If the pager is already in PAGER_ERROR state when this function is called,
   40737 ** it returns Pager.errCode immediately. No work is performed in this case.
   40738 **
   40739 ** Otherwise, in rollback mode, this function performs two functions:
   40740 **
   40741 **   1) It rolls back the journal file, restoring all database file and
   40742 **      in-memory cache pages to the state they were in when the transaction
   40743 **      was opened, and
   40744 **
   40745 **   2) It finalizes the journal file, so that it is not used for hot
   40746 **      rollback at any point in the future.
   40747 **
   40748 ** Finalization of the journal file (task 2) is only performed if the
   40749 ** rollback is successful.
   40750 **
   40751 ** In WAL mode, all cache-entries containing data modified within the
   40752 ** current transaction are either expelled from the cache or reverted to
   40753 ** their pre-transaction state by re-reading data from the database or
   40754 ** WAL files. The WAL transaction is then closed.
   40755 */
   40756 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   40757   int rc = SQLITE_OK;                  /* Return code */
   40758   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
   40759 
   40760   /* PagerRollback() is a no-op if called in READER or OPEN state. If
   40761   ** the pager is already in the ERROR state, the rollback is not
   40762   ** attempted here. Instead, the error code is returned to the caller.
   40763   */
   40764   assert( assert_pager_state(pPager) );
   40765   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
   40766   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
   40767 
   40768   if( pagerUseWal(pPager) ){
   40769     int rc2;
   40770     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
   40771     rc2 = pager_end_transaction(pPager, pPager->setMaster);
   40772     if( rc==SQLITE_OK ) rc = rc2;
   40773   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
   40774     rc = pager_end_transaction(pPager, 0);
   40775   }else{
   40776     rc = pager_playback(pPager, 0);
   40777   }
   40778 
   40779   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   40780   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
   40781 
   40782   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
   40783   ** cache. So call pager_error() on the way out to make any error persistent.
   40784   */
   40785   return pager_error(pPager, rc);
   40786 }
   40787 
   40788 /*
   40789 ** Return TRUE if the database file is opened read-only.  Return FALSE
   40790 ** if the database is (in theory) writable.
   40791 */
   40792 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
   40793   return pPager->readOnly;
   40794 }
   40795 
   40796 /*
   40797 ** Return the number of references to the pager.
   40798 */
   40799 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
   40800   return sqlite3PcacheRefCount(pPager->pPCache);
   40801 }
   40802 
   40803 /*
   40804 ** Return the approximate number of bytes of memory currently
   40805 ** used by the pager and its associated cache.
   40806 */
   40807 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
   40808   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
   40809                                      + 5*sizeof(void*);
   40810   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
   40811            + sqlite3MallocSize(pPager)
   40812            + pPager->pageSize;
   40813 }
   40814 
   40815 /*
   40816 ** Return the number of references to the specified page.
   40817 */
   40818 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
   40819   return sqlite3PcachePageRefcount(pPage);
   40820 }
   40821 
   40822 #ifdef SQLITE_TEST
   40823 /*
   40824 ** This routine is used for testing and analysis only.
   40825 */
   40826 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
   40827   static int a[11];
   40828   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
   40829   a[1] = sqlite3PcachePagecount(pPager->pPCache);
   40830   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
   40831   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
   40832   a[4] = pPager->eState;
   40833   a[5] = pPager->errCode;
   40834   a[6] = pPager->nHit;
   40835   a[7] = pPager->nMiss;
   40836   a[8] = 0;  /* Used to be pPager->nOvfl */
   40837   a[9] = pPager->nRead;
   40838   a[10] = pPager->nWrite;
   40839   return a;
   40840 }
   40841 #endif
   40842 
   40843 /*
   40844 ** Return true if this is an in-memory pager.
   40845 */
   40846 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
   40847   return MEMDB;
   40848 }
   40849 
   40850 /*
   40851 ** Check that there are at least nSavepoint savepoints open. If there are
   40852 ** currently less than nSavepoints open, then open one or more savepoints
   40853 ** to make up the difference. If the number of savepoints is already
   40854 ** equal to nSavepoint, then this function is a no-op.
   40855 **
   40856 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
   40857 ** occurs while opening the sub-journal file, then an IO error code is
   40858 ** returned. Otherwise, SQLITE_OK.
   40859 */
   40860 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
   40861   int rc = SQLITE_OK;                       /* Return code */
   40862   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
   40863 
   40864   assert( pPager->eState>=PAGER_WRITER_LOCKED );
   40865   assert( assert_pager_state(pPager) );
   40866 
   40867   if( nSavepoint>nCurrent && pPager->useJournal ){
   40868     int ii;                                 /* Iterator variable */
   40869     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
   40870 
   40871     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
   40872     ** if the allocation fails. Otherwise, zero the new portion in case a
   40873     ** malloc failure occurs while populating it in the for(...) loop below.
   40874     */
   40875     aNew = (PagerSavepoint *)sqlite3Realloc(
   40876         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
   40877     );
   40878     if( !aNew ){
   40879       return SQLITE_NOMEM;
   40880     }
   40881     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
   40882     pPager->aSavepoint = aNew;
   40883 
   40884     /* Populate the PagerSavepoint structures just allocated. */
   40885     for(ii=nCurrent; ii<nSavepoint; ii++){
   40886       aNew[ii].nOrig = pPager->dbSize;
   40887       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
   40888         aNew[ii].iOffset = pPager->journalOff;
   40889       }else{
   40890         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
   40891       }
   40892       aNew[ii].iSubRec = pPager->nSubRec;
   40893       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
   40894       if( !aNew[ii].pInSavepoint ){
   40895         return SQLITE_NOMEM;
   40896       }
   40897       if( pagerUseWal(pPager) ){
   40898         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
   40899       }
   40900       pPager->nSavepoint = ii+1;
   40901     }
   40902     assert( pPager->nSavepoint==nSavepoint );
   40903     assertTruncateConstraint(pPager);
   40904   }
   40905 
   40906   return rc;
   40907 }
   40908 
   40909 /*
   40910 ** This function is called to rollback or release (commit) a savepoint.
   40911 ** The savepoint to release or rollback need not be the most recently
   40912 ** created savepoint.
   40913 **
   40914 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
   40915 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
   40916 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
   40917 ** that have occurred since the specified savepoint was created.
   40918 **
   40919 ** The savepoint to rollback or release is identified by parameter
   40920 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
   40921 ** (the first created). A value of (Pager.nSavepoint-1) means operate
   40922 ** on the most recently created savepoint. If iSavepoint is greater than
   40923 ** (Pager.nSavepoint-1), then this function is a no-op.
   40924 **
   40925 ** If a negative value is passed to this function, then the current
   40926 ** transaction is rolled back. This is different to calling
   40927 ** sqlite3PagerRollback() because this function does not terminate
   40928 ** the transaction or unlock the database, it just restores the
   40929 ** contents of the database to its original state.
   40930 **
   40931 ** In any case, all savepoints with an index greater than iSavepoint
   40932 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
   40933 ** then savepoint iSavepoint is also destroyed.
   40934 **
   40935 ** This function may return SQLITE_NOMEM if a memory allocation fails,
   40936 ** or an IO error code if an IO error occurs while rolling back a
   40937 ** savepoint. If no errors occur, SQLITE_OK is returned.
   40938 */
   40939 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   40940   int rc = pPager->errCode;       /* Return code */
   40941 
   40942   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   40943   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
   40944 
   40945   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
   40946     int ii;            /* Iterator variable */
   40947     int nNew;          /* Number of remaining savepoints after this op. */
   40948 
   40949     /* Figure out how many savepoints will still be active after this
   40950     ** operation. Store this value in nNew. Then free resources associated
   40951     ** with any savepoints that are destroyed by this operation.
   40952     */
   40953     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
   40954     for(ii=nNew; ii<pPager->nSavepoint; ii++){
   40955       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
   40956     }
   40957     pPager->nSavepoint = nNew;
   40958 
   40959     /* If this is a release of the outermost savepoint, truncate
   40960     ** the sub-journal to zero bytes in size. */
   40961     if( op==SAVEPOINT_RELEASE ){
   40962       if( nNew==0 && isOpen(pPager->sjfd) ){
   40963         /* Only truncate if it is an in-memory sub-journal. */
   40964         if( sqlite3IsMemJournal(pPager->sjfd) ){
   40965           rc = sqlite3OsTruncate(pPager->sjfd, 0);
   40966           assert( rc==SQLITE_OK );
   40967         }
   40968         pPager->nSubRec = 0;
   40969       }
   40970     }
   40971     /* Else this is a rollback operation, playback the specified savepoint.
   40972     ** If this is a temp-file, it is possible that the journal file has
   40973     ** not yet been opened. In this case there have been no changes to
   40974     ** the database file, so the playback operation can be skipped.
   40975     */
   40976     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
   40977       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
   40978       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
   40979       assert(rc!=SQLITE_DONE);
   40980     }
   40981   }
   40982 
   40983   return rc;
   40984 }
   40985 
   40986 /*
   40987 ** Return the full pathname of the database file.
   40988 */
   40989 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
   40990   return pPager->zFilename;
   40991 }
   40992 
   40993 /*
   40994 ** Return the VFS structure for the pager.
   40995 */
   40996 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
   40997   return pPager->pVfs;
   40998 }
   40999 
   41000 /*
   41001 ** Return the file handle for the database file associated
   41002 ** with the pager.  This might return NULL if the file has
   41003 ** not yet been opened.
   41004 */
   41005 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   41006   return pPager->fd;
   41007 }
   41008 
   41009 /*
   41010 ** Return the full pathname of the journal file.
   41011 */
   41012 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   41013   return pPager->zJournal;
   41014 }
   41015 
   41016 /*
   41017 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
   41018 ** if fsync()s are executed normally.
   41019 */
   41020 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
   41021   return pPager->noSync;
   41022 }
   41023 
   41024 #ifdef SQLITE_HAS_CODEC
   41025 /*
   41026 ** Set or retrieve the codec for this pager
   41027 */
   41028 SQLITE_PRIVATE void sqlite3PagerSetCodec(
   41029   Pager *pPager,
   41030   void *(*xCodec)(void*,void*,Pgno,int),
   41031   void (*xCodecSizeChng)(void*,int,int),
   41032   void (*xCodecFree)(void*),
   41033   void *pCodec
   41034 ){
   41035   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
   41036   pPager->xCodec = pPager->memDb ? 0 : xCodec;
   41037   pPager->xCodecSizeChng = xCodecSizeChng;
   41038   pPager->xCodecFree = xCodecFree;
   41039   pPager->pCodec = pCodec;
   41040   pagerReportSize(pPager);
   41041 }
   41042 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
   41043   return pPager->pCodec;
   41044 }
   41045 #endif
   41046 
   41047 #ifndef SQLITE_OMIT_AUTOVACUUM
   41048 /*
   41049 ** Move the page pPg to location pgno in the file.
   41050 **
   41051 ** There must be no references to the page previously located at
   41052 ** pgno (which we call pPgOld) though that page is allowed to be
   41053 ** in cache.  If the page previously located at pgno is not already
   41054 ** in the rollback journal, it is not put there by by this routine.
   41055 **
   41056 ** References to the page pPg remain valid. Updating any
   41057 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
   41058 ** allocated along with the page) is the responsibility of the caller.
   41059 **
   41060 ** A transaction must be active when this routine is called. It used to be
   41061 ** required that a statement transaction was not active, but this restriction
   41062 ** has been removed (CREATE INDEX needs to move a page when a statement
   41063 ** transaction is active).
   41064 **
   41065 ** If the fourth argument, isCommit, is non-zero, then this page is being
   41066 ** moved as part of a database reorganization just before the transaction
   41067 ** is being committed. In this case, it is guaranteed that the database page
   41068 ** pPg refers to will not be written to again within this transaction.
   41069 **
   41070 ** This function may return SQLITE_NOMEM or an IO error code if an error
   41071 ** occurs. Otherwise, it returns SQLITE_OK.
   41072 */
   41073 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
   41074   PgHdr *pPgOld;               /* The page being overwritten. */
   41075   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
   41076   int rc;                      /* Return code */
   41077   Pgno origPgno;               /* The original page number */
   41078 
   41079   assert( pPg->nRef>0 );
   41080   assert( pPager->eState==PAGER_WRITER_CACHEMOD
   41081        || pPager->eState==PAGER_WRITER_DBMOD
   41082   );
   41083   assert( assert_pager_state(pPager) );
   41084 
   41085   /* In order to be able to rollback, an in-memory database must journal
   41086   ** the page we are moving from.
   41087   */
   41088   if( MEMDB ){
   41089     rc = sqlite3PagerWrite(pPg);
   41090     if( rc ) return rc;
   41091   }
   41092 
   41093   /* If the page being moved is dirty and has not been saved by the latest
   41094   ** savepoint, then save the current contents of the page into the
   41095   ** sub-journal now. This is required to handle the following scenario:
   41096   **
   41097   **   BEGIN;
   41098   **     <journal page X, then modify it in memory>
   41099   **     SAVEPOINT one;
   41100   **       <Move page X to location Y>
   41101   **     ROLLBACK TO one;
   41102   **
   41103   ** If page X were not written to the sub-journal here, it would not
   41104   ** be possible to restore its contents when the "ROLLBACK TO one"
   41105   ** statement were is processed.
   41106   **
   41107   ** subjournalPage() may need to allocate space to store pPg->pgno into
   41108   ** one or more savepoint bitvecs. This is the reason this function
   41109   ** may return SQLITE_NOMEM.
   41110   */
   41111   if( pPg->flags&PGHDR_DIRTY
   41112    && subjRequiresPage(pPg)
   41113    && SQLITE_OK!=(rc = subjournalPage(pPg))
   41114   ){
   41115     return rc;
   41116   }
   41117 
   41118   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
   41119       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   41120   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
   41121 
   41122   /* If the journal needs to be sync()ed before page pPg->pgno can
   41123   ** be written to, store pPg->pgno in local variable needSyncPgno.
   41124   **
   41125   ** If the isCommit flag is set, there is no need to remember that
   41126   ** the journal needs to be sync()ed before database page pPg->pgno
   41127   ** can be written to. The caller has already promised not to write to it.
   41128   */
   41129   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
   41130     needSyncPgno = pPg->pgno;
   41131     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
   41132     assert( pPg->flags&PGHDR_DIRTY );
   41133   }
   41134 
   41135   /* If the cache contains a page with page-number pgno, remove it
   41136   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
   41137   ** page pgno before the 'move' operation, it needs to be retained
   41138   ** for the page moved there.
   41139   */
   41140   pPg->flags &= ~PGHDR_NEED_SYNC;
   41141   pPgOld = pager_lookup(pPager, pgno);
   41142   assert( !pPgOld || pPgOld->nRef==1 );
   41143   if( pPgOld ){
   41144     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
   41145     if( MEMDB ){
   41146       /* Do not discard pages from an in-memory database since we might
   41147       ** need to rollback later.  Just move the page out of the way. */
   41148       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
   41149     }else{
   41150       sqlite3PcacheDrop(pPgOld);
   41151     }
   41152   }
   41153 
   41154   origPgno = pPg->pgno;
   41155   sqlite3PcacheMove(pPg, pgno);
   41156   sqlite3PcacheMakeDirty(pPg);
   41157 
   41158   /* For an in-memory database, make sure the original page continues
   41159   ** to exist, in case the transaction needs to roll back.  Use pPgOld
   41160   ** as the original page since it has already been allocated.
   41161   */
   41162   if( MEMDB ){
   41163     assert( pPgOld );
   41164     sqlite3PcacheMove(pPgOld, origPgno);
   41165     sqlite3PagerUnref(pPgOld);
   41166   }
   41167 
   41168   if( needSyncPgno ){
   41169     /* If needSyncPgno is non-zero, then the journal file needs to be
   41170     ** sync()ed before any data is written to database file page needSyncPgno.
   41171     ** Currently, no such page exists in the page-cache and the
   41172     ** "is journaled" bitvec flag has been set. This needs to be remedied by
   41173     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
   41174     ** flag.
   41175     **
   41176     ** If the attempt to load the page into the page-cache fails, (due
   41177     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
   41178     ** array. Otherwise, if the page is loaded and written again in
   41179     ** this transaction, it may be written to the database file before
   41180     ** it is synced into the journal file. This way, it may end up in
   41181     ** the journal file twice, but that is not a problem.
   41182     */
   41183     PgHdr *pPgHdr;
   41184     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
   41185     if( rc!=SQLITE_OK ){
   41186       if( needSyncPgno<=pPager->dbOrigSize ){
   41187         assert( pPager->pTmpSpace!=0 );
   41188         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
   41189       }
   41190       return rc;
   41191     }
   41192     pPgHdr->flags |= PGHDR_NEED_SYNC;
   41193     sqlite3PcacheMakeDirty(pPgHdr);
   41194     sqlite3PagerUnref(pPgHdr);
   41195   }
   41196 
   41197   return SQLITE_OK;
   41198 }
   41199 #endif
   41200 
   41201 /*
   41202 ** Return a pointer to the data for the specified page.
   41203 */
   41204 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
   41205   assert( pPg->nRef>0 || pPg->pPager->memDb );
   41206   return pPg->pData;
   41207 }
   41208 
   41209 /*
   41210 ** Return a pointer to the Pager.nExtra bytes of "extra" space
   41211 ** allocated along with the specified page.
   41212 */
   41213 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
   41214   return pPg->pExtra;
   41215 }
   41216 
   41217 /*
   41218 ** Get/set the locking-mode for this pager. Parameter eMode must be one
   41219 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
   41220 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
   41221 ** the locking-mode is set to the value specified.
   41222 **
   41223 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
   41224 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
   41225 ** locking-mode.
   41226 */
   41227 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
   41228   assert( eMode==PAGER_LOCKINGMODE_QUERY
   41229             || eMode==PAGER_LOCKINGMODE_NORMAL
   41230             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
   41231   assert( PAGER_LOCKINGMODE_QUERY<0 );
   41232   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
   41233   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
   41234   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
   41235     pPager->exclusiveMode = (u8)eMode;
   41236   }
   41237   return (int)pPager->exclusiveMode;
   41238 }
   41239 
   41240 /*
   41241 ** Set the journal-mode for this pager. Parameter eMode must be one of:
   41242 **
   41243 **    PAGER_JOURNALMODE_DELETE
   41244 **    PAGER_JOURNALMODE_TRUNCATE
   41245 **    PAGER_JOURNALMODE_PERSIST
   41246 **    PAGER_JOURNALMODE_OFF
   41247 **    PAGER_JOURNALMODE_MEMORY
   41248 **    PAGER_JOURNALMODE_WAL
   41249 **
   41250 ** The journalmode is set to the value specified if the change is allowed.
   41251 ** The change may be disallowed for the following reasons:
   41252 **
   41253 **   *  An in-memory database can only have its journal_mode set to _OFF
   41254 **      or _MEMORY.
   41255 **
   41256 **   *  Temporary databases cannot have _WAL journalmode.
   41257 **
   41258 ** The returned indicate the current (possibly updated) journal-mode.
   41259 */
   41260 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   41261   u8 eOld = pPager->journalMode;    /* Prior journalmode */
   41262 
   41263 #ifdef SQLITE_DEBUG
   41264   /* The print_pager_state() routine is intended to be used by the debugger
   41265   ** only.  We invoke it once here to suppress a compiler warning. */
   41266   print_pager_state(pPager);
   41267 #endif
   41268 
   41269 
   41270   /* The eMode parameter is always valid */
   41271   assert(      eMode==PAGER_JOURNALMODE_DELETE
   41272             || eMode==PAGER_JOURNALMODE_TRUNCATE
   41273             || eMode==PAGER_JOURNALMODE_PERSIST
   41274             || eMode==PAGER_JOURNALMODE_OFF
   41275             || eMode==PAGER_JOURNALMODE_WAL
   41276             || eMode==PAGER_JOURNALMODE_MEMORY );
   41277 
   41278   /* This routine is only called from the OP_JournalMode opcode, and
   41279   ** the logic there will never allow a temporary file to be changed
   41280   ** to WAL mode.
   41281   */
   41282   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
   41283 
   41284   /* Do allow the journalmode of an in-memory database to be set to
   41285   ** anything other than MEMORY or OFF
   41286   */
   41287   if( MEMDB ){
   41288     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
   41289     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
   41290       eMode = eOld;
   41291     }
   41292   }
   41293 
   41294   if( eMode!=eOld ){
   41295 
   41296     /* Change the journal mode. */
   41297     assert( pPager->eState!=PAGER_ERROR );
   41298     pPager->journalMode = (u8)eMode;
   41299 
   41300     /* When transistioning from TRUNCATE or PERSIST to any other journal
   41301     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
   41302     ** delete the journal file.
   41303     */
   41304     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
   41305     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
   41306     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
   41307     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
   41308     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
   41309     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
   41310 
   41311     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
   41312     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
   41313 
   41314       /* In this case we would like to delete the journal file. If it is
   41315       ** not possible, then that is not a problem. Deleting the journal file
   41316       ** here is an optimization only.
   41317       **
   41318       ** Before deleting the journal file, obtain a RESERVED lock on the
   41319       ** database file. This ensures that the journal file is not deleted
   41320       ** while it is in use by some other client.
   41321       */
   41322       sqlite3OsClose(pPager->jfd);
   41323       if( pPager->eLock>=RESERVED_LOCK ){
   41324         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   41325       }else{
   41326         int rc = SQLITE_OK;
   41327         int state = pPager->eState;
   41328         assert( state==PAGER_OPEN || state==PAGER_READER );
   41329         if( state==PAGER_OPEN ){
   41330           rc = sqlite3PagerSharedLock(pPager);
   41331         }
   41332         if( pPager->eState==PAGER_READER ){
   41333           assert( rc==SQLITE_OK );
   41334           rc = pagerLockDb(pPager, RESERVED_LOCK);
   41335         }
   41336         if( rc==SQLITE_OK ){
   41337           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
   41338         }
   41339         if( rc==SQLITE_OK && state==PAGER_READER ){
   41340           pagerUnlockDb(pPager, SHARED_LOCK);
   41341         }else if( state==PAGER_OPEN ){
   41342           pager_unlock(pPager);
   41343         }
   41344         assert( state==pPager->eState );
   41345       }
   41346     }
   41347   }
   41348 
   41349   /* Return the new journal mode */
   41350   return (int)pPager->journalMode;
   41351 }
   41352 
   41353 /*
   41354 ** Return the current journal mode.
   41355 */
   41356 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
   41357   return (int)pPager->journalMode;
   41358 }
   41359 
   41360 /*
   41361 ** Return TRUE if the pager is in a state where it is OK to change the
   41362 ** journalmode.  Journalmode changes can only happen when the database
   41363 ** is unmodified.
   41364 */
   41365 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
   41366   assert( assert_pager_state(pPager) );
   41367   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
   41368   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
   41369   return 1;
   41370 }
   41371 
   41372 /*
   41373 ** Get/set the size-limit used for persistent journal files.
   41374 **
   41375 ** Setting the size limit to -1 means no limit is enforced.
   41376 ** An attempt to set a limit smaller than -1 is a no-op.
   41377 */
   41378 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
   41379   if( iLimit>=-1 ){
   41380     pPager->journalSizeLimit = iLimit;
   41381   }
   41382   return pPager->journalSizeLimit;
   41383 }
   41384 
   41385 /*
   41386 ** Return a pointer to the pPager->pBackup variable. The backup module
   41387 ** in backup.c maintains the content of this variable. This module
   41388 ** uses it opaquely as an argument to sqlite3BackupRestart() and
   41389 ** sqlite3BackupUpdate() only.
   41390 */
   41391 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
   41392   return &pPager->pBackup;
   41393 }
   41394 
   41395 #ifndef SQLITE_OMIT_WAL
   41396 /*
   41397 ** This function is called when the user invokes "PRAGMA checkpoint".
   41398 */
   41399 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
   41400   int rc = SQLITE_OK;
   41401   if( pPager->pWal ){
   41402     u8 *zBuf = (u8 *)pPager->pTmpSpace;
   41403     rc = sqlite3WalCheckpoint(pPager->pWal, pPager->ckptSyncFlags,
   41404                               pPager->pageSize, zBuf);
   41405   }
   41406   return rc;
   41407 }
   41408 
   41409 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
   41410   return sqlite3WalCallback(pPager->pWal);
   41411 }
   41412 
   41413 /*
   41414 ** Return true if the underlying VFS for the given pager supports the
   41415 ** primitives necessary for write-ahead logging.
   41416 */
   41417 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
   41418   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
   41419   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
   41420 }
   41421 
   41422 /*
   41423 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
   41424 ** is obtained instead, immediately release it.
   41425 */
   41426 static int pagerExclusiveLock(Pager *pPager){
   41427   int rc;                         /* Return code */
   41428 
   41429   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   41430   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   41431   if( rc!=SQLITE_OK ){
   41432     /* If the attempt to grab the pending lock failed, release the
   41433     ** exclusive lock that may have been obtained instead.  */
   41434     pagerUnlockDb(pPager, SHARED_LOCK);
   41435   }
   41436 
   41437   return rc;
   41438 }
   41439 
   41440 /*
   41441 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
   41442 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
   41443 ** lock on the database file and use heap-memory to store the wal-index
   41444 ** in. Otherwise, use the normal shared-memory.
   41445 */
   41446 static int pagerOpenWal(Pager *pPager){
   41447   int rc = SQLITE_OK;
   41448 
   41449   assert( pPager->pWal==0 && pPager->tempFile==0 );
   41450   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
   41451 
   41452   /* If the pager is already in exclusive-mode, the WAL module will use
   41453   ** heap-memory for the wal-index instead of the VFS shared-memory
   41454   ** implementation. Take the exclusive lock now, before opening the WAL
   41455   ** file, to make sure this is safe.
   41456   */
   41457   if( pPager->exclusiveMode ){
   41458     rc = pagerExclusiveLock(pPager);
   41459   }
   41460 
   41461   /* Open the connection to the log file. If this operation fails,
   41462   ** (e.g. due to malloc() failure), return an error code.
   41463   */
   41464   if( rc==SQLITE_OK ){
   41465     rc = sqlite3WalOpen(pPager->pVfs,
   41466         pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
   41467     );
   41468   }
   41469 
   41470   return rc;
   41471 }
   41472 
   41473 
   41474 /*
   41475 ** The caller must be holding a SHARED lock on the database file to call
   41476 ** this function.
   41477 **
   41478 ** If the pager passed as the first argument is open on a real database
   41479 ** file (not a temp file or an in-memory database), and the WAL file
   41480 ** is not already open, make an attempt to open it now. If successful,
   41481 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
   41482 ** not support the xShmXXX() methods, return an error code. *pbOpen is
   41483 ** not modified in either case.
   41484 **
   41485 ** If the pager is open on a temp-file (or in-memory database), or if
   41486 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
   41487 ** without doing anything.
   41488 */
   41489 SQLITE_PRIVATE int sqlite3PagerOpenWal(
   41490   Pager *pPager,                  /* Pager object */
   41491   int *pbOpen                     /* OUT: Set to true if call is a no-op */
   41492 ){
   41493   int rc = SQLITE_OK;             /* Return code */
   41494 
   41495   assert( assert_pager_state(pPager) );
   41496   assert( pPager->eState==PAGER_OPEN   || pbOpen );
   41497   assert( pPager->eState==PAGER_READER || !pbOpen );
   41498   assert( pbOpen==0 || *pbOpen==0 );
   41499   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
   41500 
   41501   if( !pPager->tempFile && !pPager->pWal ){
   41502     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
   41503 
   41504     /* Close any rollback journal previously open */
   41505     sqlite3OsClose(pPager->jfd);
   41506 
   41507     rc = pagerOpenWal(pPager);
   41508     if( rc==SQLITE_OK ){
   41509       pPager->journalMode = PAGER_JOURNALMODE_WAL;
   41510       pPager->eState = PAGER_OPEN;
   41511     }
   41512   }else{
   41513     *pbOpen = 1;
   41514   }
   41515 
   41516   return rc;
   41517 }
   41518 
   41519 /*
   41520 ** This function is called to close the connection to the log file prior
   41521 ** to switching from WAL to rollback mode.
   41522 **
   41523 ** Before closing the log file, this function attempts to take an
   41524 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
   41525 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
   41526 ** If successful, the EXCLUSIVE lock is not released before returning.
   41527 */
   41528 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
   41529   int rc = SQLITE_OK;
   41530 
   41531   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
   41532 
   41533   /* If the log file is not already open, but does exist in the file-system,
   41534   ** it may need to be checkpointed before the connection can switch to
   41535   ** rollback mode. Open it now so this can happen.
   41536   */
   41537   if( !pPager->pWal ){
   41538     int logexists = 0;
   41539     rc = pagerLockDb(pPager, SHARED_LOCK);
   41540     if( rc==SQLITE_OK ){
   41541       rc = sqlite3OsAccess(
   41542           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
   41543       );
   41544     }
   41545     if( rc==SQLITE_OK && logexists ){
   41546       rc = pagerOpenWal(pPager);
   41547     }
   41548   }
   41549 
   41550   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   41551   ** the database file, the log and log-summary files will be deleted.
   41552   */
   41553   if( rc==SQLITE_OK && pPager->pWal ){
   41554     rc = pagerExclusiveLock(pPager);
   41555     if( rc==SQLITE_OK ){
   41556       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
   41557                            pPager->pageSize, (u8*)pPager->pTmpSpace);
   41558       pPager->pWal = 0;
   41559     }
   41560   }
   41561   return rc;
   41562 }
   41563 
   41564 #ifdef SQLITE_HAS_CODEC
   41565 /*
   41566 ** This function is called by the wal module when writing page content
   41567 ** into the log file.
   41568 **
   41569 ** This function returns a pointer to a buffer containing the encrypted
   41570 ** page content. If a malloc fails, this function may return NULL.
   41571 */
   41572 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
   41573   void *aData = 0;
   41574   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
   41575   return aData;
   41576 }
   41577 #endif /* SQLITE_HAS_CODEC */
   41578 
   41579 #endif /* !SQLITE_OMIT_WAL */
   41580 
   41581 #endif /* SQLITE_OMIT_DISKIO */
   41582 
   41583 /************** End of pager.c ***********************************************/
   41584 /************** Begin file wal.c *********************************************/
   41585 /*
   41586 ** 2010 February 1
   41587 **
   41588 ** The author disclaims copyright to this source code.  In place of
   41589 ** a legal notice, here is a blessing:
   41590 **
   41591 **    May you do good and not evil.
   41592 **    May you find forgiveness for yourself and forgive others.
   41593 **    May you share freely, never taking more than you give.
   41594 **
   41595 *************************************************************************
   41596 **
   41597 ** This file contains the implementation of a write-ahead log (WAL) used in
   41598 ** "journal_mode=WAL" mode.
   41599 **
   41600 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
   41601 **
   41602 ** A WAL file consists of a header followed by zero or more "frames".
   41603 ** Each frame records the revised content of a single page from the
   41604 ** database file.  All changes to the database are recorded by writing
   41605 ** frames into the WAL.  Transactions commit when a frame is written that
   41606 ** contains a commit marker.  A single WAL can and usually does record
   41607 ** multiple transactions.  Periodically, the content of the WAL is
   41608 ** transferred back into the database file in an operation called a
   41609 ** "checkpoint".
   41610 **
   41611 ** A single WAL file can be used multiple times.  In other words, the
   41612 ** WAL can fill up with frames and then be checkpointed and then new
   41613 ** frames can overwrite the old ones.  A WAL always grows from beginning
   41614 ** toward the end.  Checksums and counters attached to each frame are
   41615 ** used to determine which frames within the WAL are valid and which
   41616 ** are leftovers from prior checkpoints.
   41617 **
   41618 ** The WAL header is 32 bytes in size and consists of the following eight
   41619 ** big-endian 32-bit unsigned integer values:
   41620 **
   41621 **     0: Magic number.  0x377f0682 or 0x377f0683
   41622 **     4: File format version.  Currently 3007000
   41623 **     8: Database page size.  Example: 1024
   41624 **    12: Checkpoint sequence number
   41625 **    16: Salt-1, random integer incremented with each checkpoint
   41626 **    20: Salt-2, a different random integer changing with each ckpt
   41627 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
   41628 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
   41629 **
   41630 ** Immediately following the wal-header are zero or more frames. Each
   41631 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
   41632 ** of page data. The frame-header is six big-endian 32-bit unsigned
   41633 ** integer values, as follows:
   41634 **
   41635 **     0: Page number.
   41636 **     4: For commit records, the size of the database image in pages
   41637 **        after the commit. For all other records, zero.
   41638 **     8: Salt-1 (copied from the header)
   41639 **    12: Salt-2 (copied from the header)
   41640 **    16: Checksum-1.
   41641 **    20: Checksum-2.
   41642 **
   41643 ** A frame is considered valid if and only if the following conditions are
   41644 ** true:
   41645 **
   41646 **    (1) The salt-1 and salt-2 values in the frame-header match
   41647 **        salt values in the wal-header
   41648 **
   41649 **    (2) The checksum values in the final 8 bytes of the frame-header
   41650 **        exactly match the checksum computed consecutively on the
   41651 **        WAL header and the first 8 bytes and the content of all frames
   41652 **        up to and including the current frame.
   41653 **
   41654 ** The checksum is computed using 32-bit big-endian integers if the
   41655 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
   41656 ** is computed using little-endian if the magic number is 0x377f0682.
   41657 ** The checksum values are always stored in the frame header in a
   41658 ** big-endian format regardless of which byte order is used to compute
   41659 ** the checksum.  The checksum is computed by interpreting the input as
   41660 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
   41661 ** algorithm used for the checksum is as follows:
   41662 **
   41663 **   for i from 0 to n-1 step 2:
   41664 **     s0 += x[i] + s1;
   41665 **     s1 += x[i+1] + s0;
   41666 **   endfor
   41667 **
   41668 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
   41669 ** in reverse order (the largest fibonacci weight occurs on the first element
   41670 ** of the sequence being summed.)  The s1 value spans all 32-bit
   41671 ** terms of the sequence whereas s0 omits the final term.
   41672 **
   41673 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
   41674 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
   41675 ** The VFS.xSync operations serve as write barriers - all writes launched
   41676 ** before the xSync must complete before any write that launches after the
   41677 ** xSync begins.
   41678 **
   41679 ** After each checkpoint, the salt-1 value is incremented and the salt-2
   41680 ** value is randomized.  This prevents old and new frames in the WAL from
   41681 ** being considered valid at the same time and being checkpointing together
   41682 ** following a crash.
   41683 **
   41684 ** READER ALGORITHM
   41685 **
   41686 ** To read a page from the database (call it page number P), a reader
   41687 ** first checks the WAL to see if it contains page P.  If so, then the
   41688 ** last valid instance of page P that is a followed by a commit frame
   41689 ** or is a commit frame itself becomes the value read.  If the WAL
   41690 ** contains no copies of page P that are valid and which are a commit
   41691 ** frame or are followed by a commit frame, then page P is read from
   41692 ** the database file.
   41693 **
   41694 ** To start a read transaction, the reader records the index of the last
   41695 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
   41696 ** for all subsequent read operations.  New transactions can be appended
   41697 ** to the WAL, but as long as the reader uses its original mxFrame value
   41698 ** and ignores the newly appended content, it will see a consistent snapshot
   41699 ** of the database from a single point in time.  This technique allows
   41700 ** multiple concurrent readers to view different versions of the database
   41701 ** content simultaneously.
   41702 **
   41703 ** The reader algorithm in the previous paragraphs works correctly, but
   41704 ** because frames for page P can appear anywhere within the WAL, the
   41705 ** reader has to scan the entire WAL looking for page P frames.  If the
   41706 ** WAL is large (multiple megabytes is typical) that scan can be slow,
   41707 ** and read performance suffers.  To overcome this problem, a separate
   41708 ** data structure called the wal-index is maintained to expedite the
   41709 ** search for frames of a particular page.
   41710 **
   41711 ** WAL-INDEX FORMAT
   41712 **
   41713 ** Conceptually, the wal-index is shared memory, though VFS implementations
   41714 ** might choose to implement the wal-index using a mmapped file.  Because
   41715 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
   41716 ** on a network filesystem.  All users of the database must be able to
   41717 ** share memory.
   41718 **
   41719 ** The wal-index is transient.  After a crash, the wal-index can (and should
   41720 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
   41721 ** to either truncate or zero the header of the wal-index when the last
   41722 ** connection to it closes.  Because the wal-index is transient, it can
   41723 ** use an architecture-specific format; it does not have to be cross-platform.
   41724 ** Hence, unlike the database and WAL file formats which store all values
   41725 ** as big endian, the wal-index can store multi-byte values in the native
   41726 ** byte order of the host computer.
   41727 **
   41728 ** The purpose of the wal-index is to answer this question quickly:  Given
   41729 ** a page number P, return the index of the last frame for page P in the WAL,
   41730 ** or return NULL if there are no frames for page P in the WAL.
   41731 **
   41732 ** The wal-index consists of a header region, followed by an one or
   41733 ** more index blocks.
   41734 **
   41735 ** The wal-index header contains the total number of frames within the WAL
   41736 ** in the the mxFrame field.
   41737 **
   41738 ** Each index block except for the first contains information on
   41739 ** HASHTABLE_NPAGE frames. The first index block contains information on
   41740 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
   41741 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
   41742 ** first index block are the same size as all other index blocks in the
   41743 ** wal-index.
   41744 **
   41745 ** Each index block contains two sections, a page-mapping that contains the
   41746 ** database page number associated with each wal frame, and a hash-table
   41747 ** that allows readers to query an index block for a specific page number.
   41748 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
   41749 ** for the first index block) 32-bit page numbers. The first entry in the
   41750 ** first index-block contains the database page number corresponding to the
   41751 ** first frame in the WAL file. The first entry in the second index block
   41752 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
   41753 ** the log, and so on.
   41754 **
   41755 ** The last index block in a wal-index usually contains less than the full
   41756 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
   41757 ** depending on the contents of the WAL file. This does not change the
   41758 ** allocated size of the page-mapping array - the page-mapping array merely
   41759 ** contains unused entries.
   41760 **
   41761 ** Even without using the hash table, the last frame for page P
   41762 ** can be found by scanning the page-mapping sections of each index block
   41763 ** starting with the last index block and moving toward the first, and
   41764 ** within each index block, starting at the end and moving toward the
   41765 ** beginning.  The first entry that equals P corresponds to the frame
   41766 ** holding the content for that page.
   41767 **
   41768 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
   41769 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
   41770 ** hash table for each page number in the mapping section, so the hash
   41771 ** table is never more than half full.  The expected number of collisions
   41772 ** prior to finding a match is 1.  Each entry of the hash table is an
   41773 ** 1-based index of an entry in the mapping section of the same
   41774 ** index block.   Let K be the 1-based index of the largest entry in
   41775 ** the mapping section.  (For index blocks other than the last, K will
   41776 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
   41777 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
   41778 ** contain a value of 0.
   41779 **
   41780 ** To look for page P in the hash table, first compute a hash iKey on
   41781 ** P as follows:
   41782 **
   41783 **      iKey = (P * 383) % HASHTABLE_NSLOT
   41784 **
   41785 ** Then start scanning entries of the hash table, starting with iKey
   41786 ** (wrapping around to the beginning when the end of the hash table is
   41787 ** reached) until an unused hash slot is found. Let the first unused slot
   41788 ** be at index iUnused.  (iUnused might be less than iKey if there was
   41789 ** wrap-around.) Because the hash table is never more than half full,
   41790 ** the search is guaranteed to eventually hit an unused entry.  Let
   41791 ** iMax be the value between iKey and iUnused, closest to iUnused,
   41792 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
   41793 ** no hash slot such that aHash[i]==p) then page P is not in the
   41794 ** current index block.  Otherwise the iMax-th mapping entry of the
   41795 ** current index block corresponds to the last entry that references
   41796 ** page P.
   41797 **
   41798 ** A hash search begins with the last index block and moves toward the
   41799 ** first index block, looking for entries corresponding to page P.  On
   41800 ** average, only two or three slots in each index block need to be
   41801 ** examined in order to either find the last entry for page P, or to
   41802 ** establish that no such entry exists in the block.  Each index block
   41803 ** holds over 4000 entries.  So two or three index blocks are sufficient
   41804 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
   41805 ** comparisons (on average) suffice to either locate a frame in the
   41806 ** WAL or to establish that the frame does not exist in the WAL.  This
   41807 ** is much faster than scanning the entire 10MB WAL.
   41808 **
   41809 ** Note that entries are added in order of increasing K.  Hence, one
   41810 ** reader might be using some value K0 and a second reader that started
   41811 ** at a later time (after additional transactions were added to the WAL
   41812 ** and to the wal-index) might be using a different value K1, where K1>K0.
   41813 ** Both readers can use the same hash table and mapping section to get
   41814 ** the correct result.  There may be entries in the hash table with
   41815 ** K>K0 but to the first reader, those entries will appear to be unused
   41816 ** slots in the hash table and so the first reader will get an answer as
   41817 ** if no values greater than K0 had ever been inserted into the hash table
   41818 ** in the first place - which is what reader one wants.  Meanwhile, the
   41819 ** second reader using K1 will see additional values that were inserted
   41820 ** later, which is exactly what reader two wants.
   41821 **
   41822 ** When a rollback occurs, the value of K is decreased. Hash table entries
   41823 ** that correspond to frames greater than the new K value are removed
   41824 ** from the hash table at this point.
   41825 */
   41826 #ifndef SQLITE_OMIT_WAL
   41827 
   41828 
   41829 /*
   41830 ** Trace output macros
   41831 */
   41832 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   41833 SQLITE_PRIVATE int sqlite3WalTrace = 0;
   41834 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
   41835 #else
   41836 # define WALTRACE(X)
   41837 #endif
   41838 
   41839 /*
   41840 ** The maximum (and only) versions of the wal and wal-index formats
   41841 ** that may be interpreted by this version of SQLite.
   41842 **
   41843 ** If a client begins recovering a WAL file and finds that (a) the checksum
   41844 ** values in the wal-header are correct and (b) the version field is not
   41845 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
   41846 **
   41847 ** Similarly, if a client successfully reads a wal-index header (i.e. the
   41848 ** checksum test is successful) and finds that the version field is not
   41849 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
   41850 ** returns SQLITE_CANTOPEN.
   41851 */
   41852 #define WAL_MAX_VERSION      3007000
   41853 #define WALINDEX_MAX_VERSION 3007000
   41854 
   41855 /*
   41856 ** Indices of various locking bytes.   WAL_NREADER is the number
   41857 ** of available reader locks and should be at least 3.
   41858 */
   41859 #define WAL_WRITE_LOCK         0
   41860 #define WAL_ALL_BUT_WRITE      1
   41861 #define WAL_CKPT_LOCK          1
   41862 #define WAL_RECOVER_LOCK       2
   41863 #define WAL_READ_LOCK(I)       (3+(I))
   41864 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
   41865 
   41866 
   41867 /* Object declarations */
   41868 typedef struct WalIndexHdr WalIndexHdr;
   41869 typedef struct WalIterator WalIterator;
   41870 typedef struct WalCkptInfo WalCkptInfo;
   41871 
   41872 
   41873 /*
   41874 ** The following object holds a copy of the wal-index header content.
   41875 **
   41876 ** The actual header in the wal-index consists of two copies of this
   41877 ** object.
   41878 **
   41879 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
   41880 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
   41881 ** added in 3.7.1 when support for 64K pages was added.
   41882 */
   41883 struct WalIndexHdr {
   41884   u32 iVersion;                   /* Wal-index version */
   41885   u32 unused;                     /* Unused (padding) field */
   41886   u32 iChange;                    /* Counter incremented each transaction */
   41887   u8 isInit;                      /* 1 when initialized */
   41888   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
   41889   u16 szPage;                     /* Database page size in bytes. 1==64K */
   41890   u32 mxFrame;                    /* Index of last valid frame in the WAL */
   41891   u32 nPage;                      /* Size of database in pages */
   41892   u32 aFrameCksum[2];             /* Checksum of last frame in log */
   41893   u32 aSalt[2];                   /* Two salt values copied from WAL header */
   41894   u32 aCksum[2];                  /* Checksum over all prior fields */
   41895 };
   41896 
   41897 /*
   41898 ** A copy of the following object occurs in the wal-index immediately
   41899 ** following the second copy of the WalIndexHdr.  This object stores
   41900 ** information used by checkpoint.
   41901 **
   41902 ** nBackfill is the number of frames in the WAL that have been written
   41903 ** back into the database. (We call the act of moving content from WAL to
   41904 ** database "backfilling".)  The nBackfill number is never greater than
   41905 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
   41906 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
   41907 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
   41908 ** mxFrame back to zero when the WAL is reset.
   41909 **
   41910 ** There is one entry in aReadMark[] for each reader lock.  If a reader
   41911 ** holds read-lock K, then the value in aReadMark[K] is no greater than
   41912 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
   41913 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
   41914 ** a special case; its value is never used and it exists as a place-holder
   41915 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
   41916 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
   41917 ** directly from the database.
   41918 **
   41919 ** The value of aReadMark[K] may only be changed by a thread that
   41920 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
   41921 ** aReadMark[K] cannot changed while there is a reader is using that mark
   41922 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
   41923 **
   41924 ** The checkpointer may only transfer frames from WAL to database where
   41925 ** the frame numbers are less than or equal to every aReadMark[] that is
   41926 ** in use (that is, every aReadMark[j] for which there is a corresponding
   41927 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
   41928 ** largest value and will increase an unused aReadMark[] to mxFrame if there
   41929 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
   41930 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
   41931 ** in the WAL has been backfilled into the database) then new readers
   41932 ** will choose aReadMark[0] which has value 0 and hence such reader will
   41933 ** get all their all content directly from the database file and ignore
   41934 ** the WAL.
   41935 **
   41936 ** Writers normally append new frames to the end of the WAL.  However,
   41937 ** if nBackfill equals mxFrame (meaning that all WAL content has been
   41938 ** written back into the database) and if no readers are using the WAL
   41939 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
   41940 ** the writer will first "reset" the WAL back to the beginning and start
   41941 ** writing new content beginning at frame 1.
   41942 **
   41943 ** We assume that 32-bit loads are atomic and so no locks are needed in
   41944 ** order to read from any aReadMark[] entries.
   41945 */
   41946 struct WalCkptInfo {
   41947   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
   41948   u32 aReadMark[WAL_NREADER];     /* Reader marks */
   41949 };
   41950 #define READMARK_NOT_USED  0xffffffff
   41951 
   41952 
   41953 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
   41954 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
   41955 ** only support mandatory file-locks, we do not read or write data
   41956 ** from the region of the file on which locks are applied.
   41957 */
   41958 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
   41959 #define WALINDEX_LOCK_RESERVED 16
   41960 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
   41961 
   41962 /* Size of header before each frame in wal */
   41963 #define WAL_FRAME_HDRSIZE 24
   41964 
   41965 /* Size of write ahead log header, including checksum. */
   41966 /* #define WAL_HDRSIZE 24 */
   41967 #define WAL_HDRSIZE 32
   41968 
   41969 /* WAL magic value. Either this value, or the same value with the least
   41970 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
   41971 ** big-endian format in the first 4 bytes of a WAL file.
   41972 **
   41973 ** If the LSB is set, then the checksums for each frame within the WAL
   41974 ** file are calculated by treating all data as an array of 32-bit
   41975 ** big-endian words. Otherwise, they are calculated by interpreting
   41976 ** all data as 32-bit little-endian words.
   41977 */
   41978 #define WAL_MAGIC 0x377f0682
   41979 
   41980 /*
   41981 ** Return the offset of frame iFrame in the write-ahead log file,
   41982 ** assuming a database page size of szPage bytes. The offset returned
   41983 ** is to the start of the write-ahead log frame-header.
   41984 */
   41985 #define walFrameOffset(iFrame, szPage) (                               \
   41986   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
   41987 )
   41988 
   41989 /*
   41990 ** An open write-ahead log file is represented by an instance of the
   41991 ** following object.
   41992 */
   41993 struct Wal {
   41994   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
   41995   sqlite3_file *pDbFd;       /* File handle for the database file */
   41996   sqlite3_file *pWalFd;      /* File handle for WAL file */
   41997   u32 iCallback;             /* Value to pass to log callback (or 0) */
   41998   int nWiData;               /* Size of array apWiData */
   41999   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
   42000   u32 szPage;                /* Database page size */
   42001   i16 readLock;              /* Which read lock is being held.  -1 for none */
   42002   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
   42003   u8 writeLock;              /* True if in a write transaction */
   42004   u8 ckptLock;               /* True if holding a checkpoint lock */
   42005   u8 readOnly;               /* True if the WAL file is open read-only */
   42006   WalIndexHdr hdr;           /* Wal-index header for current transaction */
   42007   const char *zWalName;      /* Name of WAL file */
   42008   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
   42009 #ifdef SQLITE_DEBUG
   42010   u8 lockError;              /* True if a locking error has occurred */
   42011 #endif
   42012 };
   42013 
   42014 /*
   42015 ** Candidate values for Wal.exclusiveMode.
   42016 */
   42017 #define WAL_NORMAL_MODE     0
   42018 #define WAL_EXCLUSIVE_MODE  1
   42019 #define WAL_HEAPMEMORY_MODE 2
   42020 
   42021 /*
   42022 ** Each page of the wal-index mapping contains a hash-table made up of
   42023 ** an array of HASHTABLE_NSLOT elements of the following type.
   42024 */
   42025 typedef u16 ht_slot;
   42026 
   42027 /*
   42028 ** This structure is used to implement an iterator that loops through
   42029 ** all frames in the WAL in database page order. Where two or more frames
   42030 ** correspond to the same database page, the iterator visits only the
   42031 ** frame most recently written to the WAL (in other words, the frame with
   42032 ** the largest index).
   42033 **
   42034 ** The internals of this structure are only accessed by:
   42035 **
   42036 **   walIteratorInit() - Create a new iterator,
   42037 **   walIteratorNext() - Step an iterator,
   42038 **   walIteratorFree() - Free an iterator.
   42039 **
   42040 ** This functionality is used by the checkpoint code (see walCheckpoint()).
   42041 */
   42042 struct WalIterator {
   42043   int iPrior;                     /* Last result returned from the iterator */
   42044   int nSegment;                   /* Size of the aSegment[] array */
   42045   struct WalSegment {
   42046     int iNext;                    /* Next slot in aIndex[] not yet returned */
   42047     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
   42048     u32 *aPgno;                   /* Array of page numbers. */
   42049     int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
   42050     int iZero;                    /* Frame number associated with aPgno[0] */
   42051   } aSegment[1];                  /* One for every 32KB page in the WAL */
   42052 };
   42053 
   42054 /*
   42055 ** Define the parameters of the hash tables in the wal-index file. There
   42056 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
   42057 ** wal-index.
   42058 **
   42059 ** Changing any of these constants will alter the wal-index format and
   42060 ** create incompatibilities.
   42061 */
   42062 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
   42063 #define HASHTABLE_HASH_1     383                  /* Should be prime */
   42064 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
   42065 
   42066 /*
   42067 ** The block of page numbers associated with the first hash-table in a
   42068 ** wal-index is smaller than usual. This is so that there is a complete
   42069 ** hash-table on each aligned 32KB page of the wal-index.
   42070 */
   42071 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
   42072 
   42073 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
   42074 #define WALINDEX_PGSZ   (                                         \
   42075     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
   42076 )
   42077 
   42078 /*
   42079 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
   42080 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
   42081 ** numbered from zero.
   42082 **
   42083 ** If this call is successful, *ppPage is set to point to the wal-index
   42084 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
   42085 ** then an SQLite error code is returned and *ppPage is set to 0.
   42086 */
   42087 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
   42088   int rc = SQLITE_OK;
   42089 
   42090   /* Enlarge the pWal->apWiData[] array if required */
   42091   if( pWal->nWiData<=iPage ){
   42092     int nByte = sizeof(u32*)*(iPage+1);
   42093     volatile u32 **apNew;
   42094     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
   42095     if( !apNew ){
   42096       *ppPage = 0;
   42097       return SQLITE_NOMEM;
   42098     }
   42099     memset((void*)&apNew[pWal->nWiData], 0,
   42100            sizeof(u32*)*(iPage+1-pWal->nWiData));
   42101     pWal->apWiData = apNew;
   42102     pWal->nWiData = iPage+1;
   42103   }
   42104 
   42105   /* Request a pointer to the required page from the VFS */
   42106   if( pWal->apWiData[iPage]==0 ){
   42107     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   42108       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
   42109       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
   42110     }else{
   42111       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
   42112           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
   42113       );
   42114     }
   42115   }
   42116 
   42117   *ppPage = pWal->apWiData[iPage];
   42118   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
   42119   return rc;
   42120 }
   42121 
   42122 /*
   42123 ** Return a pointer to the WalCkptInfo structure in the wal-index.
   42124 */
   42125 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
   42126   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   42127   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
   42128 }
   42129 
   42130 /*
   42131 ** Return a pointer to the WalIndexHdr structure in the wal-index.
   42132 */
   42133 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
   42134   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   42135   return (volatile WalIndexHdr*)pWal->apWiData[0];
   42136 }
   42137 
   42138 /*
   42139 ** The argument to this macro must be of type u32. On a little-endian
   42140 ** architecture, it returns the u32 value that results from interpreting
   42141 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
   42142 ** returns the value that would be produced by intepreting the 4 bytes
   42143 ** of the input value as a little-endian integer.
   42144 */
   42145 #define BYTESWAP32(x) ( \
   42146     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
   42147   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
   42148 )
   42149 
   42150 /*
   42151 ** Generate or extend an 8 byte checksum based on the data in
   42152 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
   42153 ** initial values of 0 and 0 if aIn==NULL).
   42154 **
   42155 ** The checksum is written back into aOut[] before returning.
   42156 **
   42157 ** nByte must be a positive multiple of 8.
   42158 */
   42159 static void walChecksumBytes(
   42160   int nativeCksum, /* True for native byte-order, false for non-native */
   42161   u8 *a,           /* Content to be checksummed */
   42162   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
   42163   const u32 *aIn,  /* Initial checksum value input */
   42164   u32 *aOut        /* OUT: Final checksum value output */
   42165 ){
   42166   u32 s1, s2;
   42167   u32 *aData = (u32 *)a;
   42168   u32 *aEnd = (u32 *)&a[nByte];
   42169 
   42170   if( aIn ){
   42171     s1 = aIn[0];
   42172     s2 = aIn[1];
   42173   }else{
   42174     s1 = s2 = 0;
   42175   }
   42176 
   42177   assert( nByte>=8 );
   42178   assert( (nByte&0x00000007)==0 );
   42179 
   42180   if( nativeCksum ){
   42181     do {
   42182       s1 += *aData++ + s2;
   42183       s2 += *aData++ + s1;
   42184     }while( aData<aEnd );
   42185   }else{
   42186     do {
   42187       s1 += BYTESWAP32(aData[0]) + s2;
   42188       s2 += BYTESWAP32(aData[1]) + s1;
   42189       aData += 2;
   42190     }while( aData<aEnd );
   42191   }
   42192 
   42193   aOut[0] = s1;
   42194   aOut[1] = s2;
   42195 }
   42196 
   42197 static void walShmBarrier(Wal *pWal){
   42198   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
   42199     sqlite3OsShmBarrier(pWal->pDbFd);
   42200   }
   42201 }
   42202 
   42203 /*
   42204 ** Write the header information in pWal->hdr into the wal-index.
   42205 **
   42206 ** The checksum on pWal->hdr is updated before it is written.
   42207 */
   42208 static void walIndexWriteHdr(Wal *pWal){
   42209   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   42210   const int nCksum = offsetof(WalIndexHdr, aCksum);
   42211 
   42212   assert( pWal->writeLock );
   42213   pWal->hdr.isInit = 1;
   42214   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   42215   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
   42216   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   42217   walShmBarrier(pWal);
   42218   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
   42219 }
   42220 
   42221 /*
   42222 ** This function encodes a single frame header and writes it to a buffer
   42223 ** supplied by the caller. A frame-header is made up of a series of
   42224 ** 4-byte big-endian integers, as follows:
   42225 **
   42226 **     0: Page number.
   42227 **     4: For commit records, the size of the database image in pages
   42228 **        after the commit. For all other records, zero.
   42229 **     8: Salt-1 (copied from the wal-header)
   42230 **    12: Salt-2 (copied from the wal-header)
   42231 **    16: Checksum-1.
   42232 **    20: Checksum-2.
   42233 */
   42234 static void walEncodeFrame(
   42235   Wal *pWal,                      /* The write-ahead log */
   42236   u32 iPage,                      /* Database page number for frame */
   42237   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
   42238   u8 *aData,                      /* Pointer to page data */
   42239   u8 *aFrame                      /* OUT: Write encoded frame here */
   42240 ){
   42241   int nativeCksum;                /* True for native byte-order checksums */
   42242   u32 *aCksum = pWal->hdr.aFrameCksum;
   42243   assert( WAL_FRAME_HDRSIZE==24 );
   42244   sqlite3Put4byte(&aFrame[0], iPage);
   42245   sqlite3Put4byte(&aFrame[4], nTruncate);
   42246   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
   42247 
   42248   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   42249   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   42250   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   42251 
   42252   sqlite3Put4byte(&aFrame[16], aCksum[0]);
   42253   sqlite3Put4byte(&aFrame[20], aCksum[1]);
   42254 }
   42255 
   42256 /*
   42257 ** Check to see if the frame with header in aFrame[] and content
   42258 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
   42259 ** *pnTruncate and return true.  Return if the frame is not valid.
   42260 */
   42261 static int walDecodeFrame(
   42262   Wal *pWal,                      /* The write-ahead log */
   42263   u32 *piPage,                    /* OUT: Database page number for frame */
   42264   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
   42265   u8 *aData,                      /* Pointer to page data (for checksum) */
   42266   u8 *aFrame                      /* Frame data */
   42267 ){
   42268   int nativeCksum;                /* True for native byte-order checksums */
   42269   u32 *aCksum = pWal->hdr.aFrameCksum;
   42270   u32 pgno;                       /* Page number of the frame */
   42271   assert( WAL_FRAME_HDRSIZE==24 );
   42272 
   42273   /* A frame is only valid if the salt values in the frame-header
   42274   ** match the salt values in the wal-header.
   42275   */
   42276   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
   42277     return 0;
   42278   }
   42279 
   42280   /* A frame is only valid if the page number is creater than zero.
   42281   */
   42282   pgno = sqlite3Get4byte(&aFrame[0]);
   42283   if( pgno==0 ){
   42284     return 0;
   42285   }
   42286 
   42287   /* A frame is only valid if a checksum of the WAL header,
   42288   ** all prior frams, the first 16 bytes of this frame-header,
   42289   ** and the frame-data matches the checksum in the last 8
   42290   ** bytes of this frame-header.
   42291   */
   42292   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   42293   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   42294   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
   42295   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
   42296    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   42297   ){
   42298     /* Checksum failed. */
   42299     return 0;
   42300   }
   42301 
   42302   /* If we reach this point, the frame is valid.  Return the page number
   42303   ** and the new database size.
   42304   */
   42305   *piPage = pgno;
   42306   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
   42307   return 1;
   42308 }
   42309 
   42310 
   42311 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   42312 /*
   42313 ** Names of locks.  This routine is used to provide debugging output and is not
   42314 ** a part of an ordinary build.
   42315 */
   42316 static const char *walLockName(int lockIdx){
   42317   if( lockIdx==WAL_WRITE_LOCK ){
   42318     return "WRITE-LOCK";
   42319   }else if( lockIdx==WAL_CKPT_LOCK ){
   42320     return "CKPT-LOCK";
   42321   }else if( lockIdx==WAL_RECOVER_LOCK ){
   42322     return "RECOVER-LOCK";
   42323   }else{
   42324     static char zName[15];
   42325     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
   42326                      lockIdx-WAL_READ_LOCK(0));
   42327     return zName;
   42328   }
   42329 }
   42330 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   42331 
   42332 
   42333 /*
   42334 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
   42335 ** A lock cannot be moved directly between shared and exclusive - it must go
   42336 ** through the unlocked state first.
   42337 **
   42338 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
   42339 */
   42340 static int walLockShared(Wal *pWal, int lockIdx){
   42341   int rc;
   42342   if( pWal->exclusiveMode ) return SQLITE_OK;
   42343   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   42344                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   42345   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
   42346             walLockName(lockIdx), rc ? "failed" : "ok"));
   42347   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   42348   return rc;
   42349 }
   42350 static void walUnlockShared(Wal *pWal, int lockIdx){
   42351   if( pWal->exclusiveMode ) return;
   42352   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
   42353                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
   42354   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
   42355 }
   42356 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
   42357   int rc;
   42358   if( pWal->exclusiveMode ) return SQLITE_OK;
   42359   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   42360                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   42361   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
   42362             walLockName(lockIdx), n, rc ? "failed" : "ok"));
   42363   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
   42364   return rc;
   42365 }
   42366 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
   42367   if( pWal->exclusiveMode ) return;
   42368   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
   42369                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
   42370   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
   42371              walLockName(lockIdx), n));
   42372 }
   42373 
   42374 /*
   42375 ** Compute a hash on a page number.  The resulting hash value must land
   42376 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
   42377 ** the hash to the next value in the event of a collision.
   42378 */
   42379 static int walHash(u32 iPage){
   42380   assert( iPage>0 );
   42381   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
   42382   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
   42383 }
   42384 static int walNextHash(int iPriorHash){
   42385   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
   42386 }
   42387 
   42388 /*
   42389 ** Return pointers to the hash table and page number array stored on
   42390 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
   42391 ** numbered starting from 0.
   42392 **
   42393 ** Set output variable *paHash to point to the start of the hash table
   42394 ** in the wal-index file. Set *piZero to one less than the frame
   42395 ** number of the first frame indexed by this hash table. If a
   42396 ** slot in the hash table is set to N, it refers to frame number
   42397 ** (*piZero+N) in the log.
   42398 **
   42399 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
   42400 ** first frame indexed by the hash table, frame (*piZero+1).
   42401 */
   42402 static int walHashGet(
   42403   Wal *pWal,                      /* WAL handle */
   42404   int iHash,                      /* Find the iHash'th table */
   42405   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
   42406   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
   42407   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
   42408 ){
   42409   int rc;                         /* Return code */
   42410   volatile u32 *aPgno;
   42411 
   42412   rc = walIndexPage(pWal, iHash, &aPgno);
   42413   assert( rc==SQLITE_OK || iHash>0 );
   42414 
   42415   if( rc==SQLITE_OK ){
   42416     u32 iZero;
   42417     volatile ht_slot *aHash;
   42418 
   42419     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
   42420     if( iHash==0 ){
   42421       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
   42422       iZero = 0;
   42423     }else{
   42424       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
   42425     }
   42426 
   42427     *paPgno = &aPgno[-1];
   42428     *paHash = aHash;
   42429     *piZero = iZero;
   42430   }
   42431   return rc;
   42432 }
   42433 
   42434 /*
   42435 ** Return the number of the wal-index page that contains the hash-table
   42436 ** and page-number array that contain entries corresponding to WAL frame
   42437 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
   42438 ** are numbered starting from 0.
   42439 */
   42440 static int walFramePage(u32 iFrame){
   42441   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
   42442   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
   42443        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
   42444        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
   42445        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
   42446        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   42447   );
   42448   return iHash;
   42449 }
   42450 
   42451 /*
   42452 ** Return the page number associated with frame iFrame in this WAL.
   42453 */
   42454 static u32 walFramePgno(Wal *pWal, u32 iFrame){
   42455   int iHash = walFramePage(iFrame);
   42456   if( iHash==0 ){
   42457     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
   42458   }
   42459   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
   42460 }
   42461 
   42462 /*
   42463 ** Remove entries from the hash table that point to WAL slots greater
   42464 ** than pWal->hdr.mxFrame.
   42465 **
   42466 ** This function is called whenever pWal->hdr.mxFrame is decreased due
   42467 ** to a rollback or savepoint.
   42468 **
   42469 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
   42470 ** updated.  Any later hash tables will be automatically cleared when
   42471 ** pWal->hdr.mxFrame advances to the point where those hash tables are
   42472 ** actually needed.
   42473 */
   42474 static void walCleanupHash(Wal *pWal){
   42475   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
   42476   volatile u32 *aPgno = 0;        /* Page number array for hash table */
   42477   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
   42478   int iLimit = 0;                 /* Zero values greater than this */
   42479   int nByte;                      /* Number of bytes to zero in aPgno[] */
   42480   int i;                          /* Used to iterate through aHash[] */
   42481 
   42482   assert( pWal->writeLock );
   42483   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
   42484   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
   42485   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
   42486 
   42487   if( pWal->hdr.mxFrame==0 ) return;
   42488 
   42489   /* Obtain pointers to the hash-table and page-number array containing
   42490   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   42491   ** that the page said hash-table and array reside on is already mapped.
   42492   */
   42493   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
   42494   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
   42495   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
   42496 
   42497   /* Zero all hash-table entries that correspond to frame numbers greater
   42498   ** than pWal->hdr.mxFrame.
   42499   */
   42500   iLimit = pWal->hdr.mxFrame - iZero;
   42501   assert( iLimit>0 );
   42502   for(i=0; i<HASHTABLE_NSLOT; i++){
   42503     if( aHash[i]>iLimit ){
   42504       aHash[i] = 0;
   42505     }
   42506   }
   42507 
   42508   /* Zero the entries in the aPgno array that correspond to frames with
   42509   ** frame numbers greater than pWal->hdr.mxFrame.
   42510   */
   42511   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
   42512   memset((void *)&aPgno[iLimit+1], 0, nByte);
   42513 
   42514 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   42515   /* Verify that the every entry in the mapping region is still reachable
   42516   ** via the hash table even after the cleanup.
   42517   */
   42518   if( iLimit ){
   42519     int i;           /* Loop counter */
   42520     int iKey;        /* Hash key */
   42521     for(i=1; i<=iLimit; i++){
   42522       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   42523         if( aHash[iKey]==i ) break;
   42524       }
   42525       assert( aHash[iKey]==i );
   42526     }
   42527   }
   42528 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   42529 }
   42530 
   42531 
   42532 /*
   42533 ** Set an entry in the wal-index that will map database page number
   42534 ** pPage into WAL frame iFrame.
   42535 */
   42536 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
   42537   int rc;                         /* Return code */
   42538   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
   42539   volatile u32 *aPgno = 0;        /* Page number array */
   42540   volatile ht_slot *aHash = 0;    /* Hash table */
   42541 
   42542   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
   42543 
   42544   /* Assuming the wal-index file was successfully mapped, populate the
   42545   ** page number array and hash table entry.
   42546   */
   42547   if( rc==SQLITE_OK ){
   42548     int iKey;                     /* Hash table key */
   42549     int idx;                      /* Value to write to hash-table slot */
   42550     int nCollide;                 /* Number of hash collisions */
   42551 
   42552     idx = iFrame - iZero;
   42553     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
   42554 
   42555     /* If this is the first entry to be added to this hash-table, zero the
   42556     ** entire hash table and aPgno[] array before proceding.
   42557     */
   42558     if( idx==1 ){
   42559       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
   42560       memset((void*)&aPgno[1], 0, nByte);
   42561     }
   42562 
   42563     /* If the entry in aPgno[] is already set, then the previous writer
   42564     ** must have exited unexpectedly in the middle of a transaction (after
   42565     ** writing one or more dirty pages to the WAL to free up memory).
   42566     ** Remove the remnants of that writers uncommitted transaction from
   42567     ** the hash-table before writing any new entries.
   42568     */
   42569     if( aPgno[idx] ){
   42570       walCleanupHash(pWal);
   42571       assert( !aPgno[idx] );
   42572     }
   42573 
   42574     /* Write the aPgno[] array entry and the hash-table slot. */
   42575     nCollide = idx;
   42576     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
   42577       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
   42578     }
   42579     aPgno[idx] = iPage;
   42580     aHash[iKey] = (ht_slot)idx;
   42581 
   42582 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   42583     /* Verify that the number of entries in the hash table exactly equals
   42584     ** the number of entries in the mapping region.
   42585     */
   42586     {
   42587       int i;           /* Loop counter */
   42588       int nEntry = 0;  /* Number of entries in the hash table */
   42589       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
   42590       assert( nEntry==idx );
   42591     }
   42592 
   42593     /* Verify that the every entry in the mapping region is reachable
   42594     ** via the hash table.  This turns out to be a really, really expensive
   42595     ** thing to check, so only do this occasionally - not on every
   42596     ** iteration.
   42597     */
   42598     if( (idx&0x3ff)==0 ){
   42599       int i;           /* Loop counter */
   42600       for(i=1; i<=idx; i++){
   42601         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
   42602           if( aHash[iKey]==i ) break;
   42603         }
   42604         assert( aHash[iKey]==i );
   42605       }
   42606     }
   42607 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
   42608   }
   42609 
   42610 
   42611   return rc;
   42612 }
   42613 
   42614 
   42615 /*
   42616 ** Recover the wal-index by reading the write-ahead log file.
   42617 **
   42618 ** This routine first tries to establish an exclusive lock on the
   42619 ** wal-index to prevent other threads/processes from doing anything
   42620 ** with the WAL or wal-index while recovery is running.  The
   42621 ** WAL_RECOVER_LOCK is also held so that other threads will know
   42622 ** that this thread is running recovery.  If unable to establish
   42623 ** the necessary locks, this routine returns SQLITE_BUSY.
   42624 */
   42625 static int walIndexRecover(Wal *pWal){
   42626   int rc;                         /* Return Code */
   42627   i64 nSize;                      /* Size of log file */
   42628   u32 aFrameCksum[2] = {0, 0};
   42629   int iLock;                      /* Lock offset to lock for checkpoint */
   42630   int nLock;                      /* Number of locks to hold */
   42631 
   42632   /* Obtain an exclusive lock on all byte in the locking range not already
   42633   ** locked by the caller. The caller is guaranteed to have locked the
   42634   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
   42635   ** If successful, the same bytes that are locked here are unlocked before
   42636   ** this function returns.
   42637   */
   42638   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
   42639   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
   42640   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
   42641   assert( pWal->writeLock );
   42642   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   42643   nLock = SQLITE_SHM_NLOCK - iLock;
   42644   rc = walLockExclusive(pWal, iLock, nLock);
   42645   if( rc ){
   42646     return rc;
   42647   }
   42648   WALTRACE(("WAL%p: recovery begin...\n", pWal));
   42649 
   42650   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   42651 
   42652   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
   42653   if( rc!=SQLITE_OK ){
   42654     goto recovery_error;
   42655   }
   42656 
   42657   if( nSize>WAL_HDRSIZE ){
   42658     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
   42659     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
   42660     int szFrame;                  /* Number of bytes in buffer aFrame[] */
   42661     u8 *aData;                    /* Pointer to data part of aFrame buffer */
   42662     int iFrame;                   /* Index of last frame read */
   42663     i64 iOffset;                  /* Next offset to read from log file */
   42664     int szPage;                   /* Page size according to the log */
   42665     u32 magic;                    /* Magic value read from WAL header */
   42666     u32 version;                  /* Magic value read from WAL header */
   42667 
   42668     /* Read in the WAL header. */
   42669     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
   42670     if( rc!=SQLITE_OK ){
   42671       goto recovery_error;
   42672     }
   42673 
   42674     /* If the database page size is not a power of two, or is greater than
   42675     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
   42676     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
   42677     ** WAL file.
   42678     */
   42679     magic = sqlite3Get4byte(&aBuf[0]);
   42680     szPage = sqlite3Get4byte(&aBuf[8]);
   42681     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
   42682      || szPage&(szPage-1)
   42683      || szPage>SQLITE_MAX_PAGE_SIZE
   42684      || szPage<512
   42685     ){
   42686       goto finished;
   42687     }
   42688     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
   42689     pWal->szPage = szPage;
   42690     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
   42691     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
   42692 
   42693     /* Verify that the WAL header checksum is correct */
   42694     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
   42695         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
   42696     );
   42697     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
   42698      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
   42699     ){
   42700       goto finished;
   42701     }
   42702 
   42703     /* Verify that the version number on the WAL format is one that
   42704     ** are able to understand */
   42705     version = sqlite3Get4byte(&aBuf[4]);
   42706     if( version!=WAL_MAX_VERSION ){
   42707       rc = SQLITE_CANTOPEN_BKPT;
   42708       goto finished;
   42709     }
   42710 
   42711     /* Malloc a buffer to read frames into. */
   42712     szFrame = szPage + WAL_FRAME_HDRSIZE;
   42713     aFrame = (u8 *)sqlite3_malloc(szFrame);
   42714     if( !aFrame ){
   42715       rc = SQLITE_NOMEM;
   42716       goto recovery_error;
   42717     }
   42718     aData = &aFrame[WAL_FRAME_HDRSIZE];
   42719 
   42720     /* Read all frames from the log file. */
   42721     iFrame = 0;
   42722     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
   42723       u32 pgno;                   /* Database page number for frame */
   42724       u32 nTruncate;              /* dbsize field from frame header */
   42725       int isValid;                /* True if this frame is valid */
   42726 
   42727       /* Read and decode the next log frame. */
   42728       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
   42729       if( rc!=SQLITE_OK ) break;
   42730       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
   42731       if( !isValid ) break;
   42732       rc = walIndexAppend(pWal, ++iFrame, pgno);
   42733       if( rc!=SQLITE_OK ) break;
   42734 
   42735       /* If nTruncate is non-zero, this is a commit record. */
   42736       if( nTruncate ){
   42737         pWal->hdr.mxFrame = iFrame;
   42738         pWal->hdr.nPage = nTruncate;
   42739         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   42740         testcase( szPage<=32768 );
   42741         testcase( szPage>=65536 );
   42742         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
   42743         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
   42744       }
   42745     }
   42746 
   42747     sqlite3_free(aFrame);
   42748   }
   42749 
   42750 finished:
   42751   if( rc==SQLITE_OK ){
   42752     volatile WalCkptInfo *pInfo;
   42753     int i;
   42754     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
   42755     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
   42756     walIndexWriteHdr(pWal);
   42757 
   42758     /* Reset the checkpoint-header. This is safe because this thread is
   42759     ** currently holding locks that exclude all other readers, writers and
   42760     ** checkpointers.
   42761     */
   42762     pInfo = walCkptInfo(pWal);
   42763     pInfo->nBackfill = 0;
   42764     pInfo->aReadMark[0] = 0;
   42765     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   42766 
   42767     /* If more than one frame was recovered from the log file, report an
   42768     ** event via sqlite3_log(). This is to help with identifying performance
   42769     ** problems caused by applications routinely shutting down without
   42770     ** checkpointing the log file.
   42771     */
   42772     if( pWal->hdr.nPage ){
   42773       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
   42774           pWal->hdr.nPage, pWal->zWalName
   42775       );
   42776     }
   42777   }
   42778 
   42779 recovery_error:
   42780   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   42781   walUnlockExclusive(pWal, iLock, nLock);
   42782   return rc;
   42783 }
   42784 
   42785 /*
   42786 ** Close an open wal-index.
   42787 */
   42788 static void walIndexClose(Wal *pWal, int isDelete){
   42789   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
   42790     int i;
   42791     for(i=0; i<pWal->nWiData; i++){
   42792       sqlite3_free((void *)pWal->apWiData[i]);
   42793       pWal->apWiData[i] = 0;
   42794     }
   42795   }else{
   42796     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
   42797   }
   42798 }
   42799 
   42800 /*
   42801 ** Open a connection to the WAL file zWalName. The database file must
   42802 ** already be opened on connection pDbFd. The buffer that zWalName points
   42803 ** to must remain valid for the lifetime of the returned Wal* handle.
   42804 **
   42805 ** A SHARED lock should be held on the database file when this function
   42806 ** is called. The purpose of this SHARED lock is to prevent any other
   42807 ** client from unlinking the WAL or wal-index file. If another process
   42808 ** were to do this just after this client opened one of these files, the
   42809 ** system would be badly broken.
   42810 **
   42811 ** If the log file is successfully opened, SQLITE_OK is returned and
   42812 ** *ppWal is set to point to a new WAL handle. If an error occurs,
   42813 ** an SQLite error code is returned and *ppWal is left unmodified.
   42814 */
   42815 SQLITE_PRIVATE int sqlite3WalOpen(
   42816   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
   42817   sqlite3_file *pDbFd,            /* The open database file */
   42818   const char *zWalName,           /* Name of the WAL file */
   42819   int bNoShm,                     /* True to run in heap-memory mode */
   42820   Wal **ppWal                     /* OUT: Allocated Wal handle */
   42821 ){
   42822   int rc;                         /* Return Code */
   42823   Wal *pRet;                      /* Object to allocate and return */
   42824   int flags;                      /* Flags passed to OsOpen() */
   42825 
   42826   assert( zWalName && zWalName[0] );
   42827   assert( pDbFd );
   42828 
   42829   /* In the amalgamation, the os_unix.c and os_win.c source files come before
   42830   ** this source file.  Verify that the #defines of the locking byte offsets
   42831   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
   42832   */
   42833 #ifdef WIN_SHM_BASE
   42834   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
   42835 #endif
   42836 #ifdef UNIX_SHM_BASE
   42837   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
   42838 #endif
   42839 
   42840 
   42841   /* Allocate an instance of struct Wal to return. */
   42842   *ppWal = 0;
   42843   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
   42844   if( !pRet ){
   42845     return SQLITE_NOMEM;
   42846   }
   42847 
   42848   pRet->pVfs = pVfs;
   42849   pRet->pWalFd = (sqlite3_file *)&pRet[1];
   42850   pRet->pDbFd = pDbFd;
   42851   pRet->readLock = -1;
   42852   pRet->zWalName = zWalName;
   42853   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
   42854 
   42855   /* Open file handle on the write-ahead log file. */
   42856   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
   42857   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
   42858   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
   42859     pRet->readOnly = 1;
   42860   }
   42861 
   42862   if( rc!=SQLITE_OK ){
   42863     walIndexClose(pRet, 0);
   42864     sqlite3OsClose(pRet->pWalFd);
   42865     sqlite3_free(pRet);
   42866   }else{
   42867     *ppWal = pRet;
   42868     WALTRACE(("WAL%d: opened\n", pRet));
   42869   }
   42870   return rc;
   42871 }
   42872 
   42873 /*
   42874 ** Find the smallest page number out of all pages held in the WAL that
   42875 ** has not been returned by any prior invocation of this method on the
   42876 ** same WalIterator object.   Write into *piFrame the frame index where
   42877 ** that page was last written into the WAL.  Write into *piPage the page
   42878 ** number.
   42879 **
   42880 ** Return 0 on success.  If there are no pages in the WAL with a page
   42881 ** number larger than *piPage, then return 1.
   42882 */
   42883 static int walIteratorNext(
   42884   WalIterator *p,               /* Iterator */
   42885   u32 *piPage,                  /* OUT: The page number of the next page */
   42886   u32 *piFrame                  /* OUT: Wal frame index of next page */
   42887 ){
   42888   u32 iMin;                     /* Result pgno must be greater than iMin */
   42889   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
   42890   int i;                        /* For looping through segments */
   42891 
   42892   iMin = p->iPrior;
   42893   assert( iMin<0xffffffff );
   42894   for(i=p->nSegment-1; i>=0; i--){
   42895     struct WalSegment *pSegment = &p->aSegment[i];
   42896     while( pSegment->iNext<pSegment->nEntry ){
   42897       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
   42898       if( iPg>iMin ){
   42899         if( iPg<iRet ){
   42900           iRet = iPg;
   42901           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
   42902         }
   42903         break;
   42904       }
   42905       pSegment->iNext++;
   42906     }
   42907   }
   42908 
   42909   *piPage = p->iPrior = iRet;
   42910   return (iRet==0xFFFFFFFF);
   42911 }
   42912 
   42913 /*
   42914 ** This function merges two sorted lists into a single sorted list.
   42915 */
   42916 static void walMerge(
   42917   u32 *aContent,                  /* Pages in wal */
   42918   ht_slot *aLeft,                 /* IN: Left hand input list */
   42919   int nLeft,                      /* IN: Elements in array *paLeft */
   42920   ht_slot **paRight,              /* IN/OUT: Right hand input list */
   42921   int *pnRight,                   /* IN/OUT: Elements in *paRight */
   42922   ht_slot *aTmp                   /* Temporary buffer */
   42923 ){
   42924   int iLeft = 0;                  /* Current index in aLeft */
   42925   int iRight = 0;                 /* Current index in aRight */
   42926   int iOut = 0;                   /* Current index in output buffer */
   42927   int nRight = *pnRight;
   42928   ht_slot *aRight = *paRight;
   42929 
   42930   assert( nLeft>0 && nRight>0 );
   42931   while( iRight<nRight || iLeft<nLeft ){
   42932     ht_slot logpage;
   42933     Pgno dbpage;
   42934 
   42935     if( (iLeft<nLeft)
   42936      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
   42937     ){
   42938       logpage = aLeft[iLeft++];
   42939     }else{
   42940       logpage = aRight[iRight++];
   42941     }
   42942     dbpage = aContent[logpage];
   42943 
   42944     aTmp[iOut++] = logpage;
   42945     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
   42946 
   42947     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
   42948     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
   42949   }
   42950 
   42951   *paRight = aLeft;
   42952   *pnRight = iOut;
   42953   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
   42954 }
   42955 
   42956 /*
   42957 ** Sort the elements in list aList, removing any duplicates.
   42958 */
   42959 static void walMergesort(
   42960   u32 *aContent,                  /* Pages in wal */
   42961   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
   42962   ht_slot *aList,                 /* IN/OUT: List to sort */
   42963   int *pnList                     /* IN/OUT: Number of elements in aList[] */
   42964 ){
   42965   struct Sublist {
   42966     int nList;                    /* Number of elements in aList */
   42967     ht_slot *aList;               /* Pointer to sub-list content */
   42968   };
   42969 
   42970   const int nList = *pnList;      /* Size of input list */
   42971   int nMerge = 0;                 /* Number of elements in list aMerge */
   42972   ht_slot *aMerge = 0;            /* List to be merged */
   42973   int iList;                      /* Index into input list */
   42974   int iSub = 0;                   /* Index into aSub array */
   42975   struct Sublist aSub[13];        /* Array of sub-lists */
   42976 
   42977   memset(aSub, 0, sizeof(aSub));
   42978   assert( nList<=HASHTABLE_NPAGE && nList>0 );
   42979   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
   42980 
   42981   for(iList=0; iList<nList; iList++){
   42982     nMerge = 1;
   42983     aMerge = &aList[iList];
   42984     for(iSub=0; iList & (1<<iSub); iSub++){
   42985       struct Sublist *p = &aSub[iSub];
   42986       assert( p->aList && p->nList<=(1<<iSub) );
   42987       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
   42988       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   42989     }
   42990     aSub[iSub].aList = aMerge;
   42991     aSub[iSub].nList = nMerge;
   42992   }
   42993 
   42994   for(iSub++; iSub<ArraySize(aSub); iSub++){
   42995     if( nList & (1<<iSub) ){
   42996       struct Sublist *p = &aSub[iSub];
   42997       assert( p->nList<=(1<<iSub) );
   42998       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
   42999       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
   43000     }
   43001   }
   43002   assert( aMerge==aList );
   43003   *pnList = nMerge;
   43004 
   43005 #ifdef SQLITE_DEBUG
   43006   {
   43007     int i;
   43008     for(i=1; i<*pnList; i++){
   43009       assert( aContent[aList[i]] > aContent[aList[i-1]] );
   43010     }
   43011   }
   43012 #endif
   43013 }
   43014 
   43015 /*
   43016 ** Free an iterator allocated by walIteratorInit().
   43017 */
   43018 static void walIteratorFree(WalIterator *p){
   43019   sqlite3ScratchFree(p);
   43020 }
   43021 
   43022 /*
   43023 ** Construct a WalInterator object that can be used to loop over all
   43024 ** pages in the WAL in ascending order. The caller must hold the checkpoint
   43025 **
   43026 ** On success, make *pp point to the newly allocated WalInterator object
   43027 ** return SQLITE_OK. Otherwise, return an error code. If this routine
   43028 ** returns an error, the value of *pp is undefined.
   43029 **
   43030 ** The calling routine should invoke walIteratorFree() to destroy the
   43031 ** WalIterator object when it has finished with it.
   43032 */
   43033 static int walIteratorInit(Wal *pWal, WalIterator **pp){
   43034   WalIterator *p;                 /* Return value */
   43035   int nSegment;                   /* Number of segments to merge */
   43036   u32 iLast;                      /* Last frame in log */
   43037   int nByte;                      /* Number of bytes to allocate */
   43038   int i;                          /* Iterator variable */
   43039   ht_slot *aTmp;                  /* Temp space used by merge-sort */
   43040   int rc = SQLITE_OK;             /* Return Code */
   43041 
   43042   /* This routine only runs while holding the checkpoint lock. And
   43043   ** it only runs if there is actually content in the log (mxFrame>0).
   43044   */
   43045   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
   43046   iLast = pWal->hdr.mxFrame;
   43047 
   43048   /* Allocate space for the WalIterator object. */
   43049   nSegment = walFramePage(iLast) + 1;
   43050   nByte = sizeof(WalIterator)
   43051         + (nSegment-1)*sizeof(struct WalSegment)
   43052         + iLast*sizeof(ht_slot);
   43053   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
   43054   if( !p ){
   43055     return SQLITE_NOMEM;
   43056   }
   43057   memset(p, 0, nByte);
   43058   p->nSegment = nSegment;
   43059 
   43060   /* Allocate temporary space used by the merge-sort routine. This block
   43061   ** of memory will be freed before this function returns.
   43062   */
   43063   aTmp = (ht_slot *)sqlite3ScratchMalloc(
   43064       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
   43065   );
   43066   if( !aTmp ){
   43067     rc = SQLITE_NOMEM;
   43068   }
   43069 
   43070   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
   43071     volatile ht_slot *aHash;
   43072     u32 iZero;
   43073     volatile u32 *aPgno;
   43074 
   43075     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
   43076     if( rc==SQLITE_OK ){
   43077       int j;                      /* Counter variable */
   43078       int nEntry;                 /* Number of entries in this segment */
   43079       ht_slot *aIndex;            /* Sorted index for this segment */
   43080 
   43081       aPgno++;
   43082       if( (i+1)==nSegment ){
   43083         nEntry = (int)(iLast - iZero);
   43084       }else{
   43085         nEntry = (int)((u32*)aHash - (u32*)aPgno);
   43086       }
   43087       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
   43088       iZero++;
   43089 
   43090       for(j=0; j<nEntry; j++){
   43091         aIndex[j] = (ht_slot)j;
   43092       }
   43093       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
   43094       p->aSegment[i].iZero = iZero;
   43095       p->aSegment[i].nEntry = nEntry;
   43096       p->aSegment[i].aIndex = aIndex;
   43097       p->aSegment[i].aPgno = (u32 *)aPgno;
   43098     }
   43099   }
   43100   sqlite3ScratchFree(aTmp);
   43101 
   43102   if( rc!=SQLITE_OK ){
   43103     walIteratorFree(p);
   43104   }
   43105   *pp = p;
   43106   return rc;
   43107 }
   43108 
   43109 /*
   43110 ** Copy as much content as we can from the WAL back into the database file
   43111 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
   43112 **
   43113 ** The amount of information copies from WAL to database might be limited
   43114 ** by active readers.  This routine will never overwrite a database page
   43115 ** that a concurrent reader might be using.
   43116 **
   43117 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
   43118 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
   43119 ** checkpoints are always run by a background thread or background
   43120 ** process, foreground threads will never block on a lengthy fsync call.
   43121 **
   43122 ** Fsync is called on the WAL before writing content out of the WAL and
   43123 ** into the database.  This ensures that if the new content is persistent
   43124 ** in the WAL and can be recovered following a power-loss or hard reset.
   43125 **
   43126 ** Fsync is also called on the database file if (and only if) the entire
   43127 ** WAL content is copied into the database file.  This second fsync makes
   43128 ** it safe to delete the WAL since the new content will persist in the
   43129 ** database file.
   43130 **
   43131 ** This routine uses and updates the nBackfill field of the wal-index header.
   43132 ** This is the only routine tha will increase the value of nBackfill.
   43133 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
   43134 ** its value.)
   43135 **
   43136 ** The caller must be holding sufficient locks to ensure that no other
   43137 ** checkpoint is running (in any other thread or process) at the same
   43138 ** time.
   43139 */
   43140 static int walCheckpoint(
   43141   Wal *pWal,                      /* Wal connection */
   43142   int sync_flags,                 /* Flags for OsSync() (or 0) */
   43143   int nBuf,                       /* Size of zBuf in bytes */
   43144   u8 *zBuf                        /* Temporary buffer to use */
   43145 ){
   43146   int rc;                         /* Return code */
   43147   int szPage;                     /* Database page-size */
   43148   WalIterator *pIter = 0;         /* Wal iterator context */
   43149   u32 iDbpage = 0;                /* Next database page to write */
   43150   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
   43151   u32 mxSafeFrame;                /* Max frame that can be backfilled */
   43152   u32 mxPage;                     /* Max database page to write */
   43153   int i;                          /* Loop counter */
   43154   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
   43155 
   43156   szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   43157   testcase( szPage<=32768 );
   43158   testcase( szPage>=65536 );
   43159   pInfo = walCkptInfo(pWal);
   43160   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
   43161 
   43162   /* Allocate the iterator */
   43163   rc = walIteratorInit(pWal, &pIter);
   43164   if( rc!=SQLITE_OK ){
   43165     return rc;
   43166   }
   43167   assert( pIter );
   43168 
   43169   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
   43170   if( szPage!=nBuf ){
   43171     rc = SQLITE_CORRUPT_BKPT;
   43172     goto walcheckpoint_out;
   43173   }
   43174 
   43175   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
   43176   ** safe to write into the database.  Frames beyond mxSafeFrame might
   43177   ** overwrite database pages that are in use by active readers and thus
   43178   ** cannot be backfilled from the WAL.
   43179   */
   43180   mxSafeFrame = pWal->hdr.mxFrame;
   43181   mxPage = pWal->hdr.nPage;
   43182   for(i=1; i<WAL_NREADER; i++){
   43183     u32 y = pInfo->aReadMark[i];
   43184     if( mxSafeFrame>=y ){
   43185       assert( y<=pWal->hdr.mxFrame );
   43186       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   43187       if( rc==SQLITE_OK ){
   43188         pInfo->aReadMark[i] = READMARK_NOT_USED;
   43189         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   43190       }else if( rc==SQLITE_BUSY ){
   43191         mxSafeFrame = y;
   43192       }else{
   43193         goto walcheckpoint_out;
   43194       }
   43195     }
   43196   }
   43197 
   43198   if( pInfo->nBackfill<mxSafeFrame
   43199    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
   43200   ){
   43201     i64 nSize;                    /* Current size of database file */
   43202     u32 nBackfill = pInfo->nBackfill;
   43203 
   43204     /* Sync the WAL to disk */
   43205     if( sync_flags ){
   43206       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   43207     }
   43208 
   43209     /* If the database file may grow as a result of this checkpoint, hint
   43210     ** about the eventual size of the db file to the VFS layer.
   43211     */
   43212     if( rc==SQLITE_OK ){
   43213       i64 nReq = ((i64)mxPage * szPage);
   43214       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
   43215       if( rc==SQLITE_OK && nSize<nReq ){
   43216         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
   43217       }
   43218     }
   43219 
   43220     /* Iterate through the contents of the WAL, copying data to the db file. */
   43221     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
   43222       i64 iOffset;
   43223       assert( walFramePgno(pWal, iFrame)==iDbpage );
   43224       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
   43225       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
   43226       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
   43227       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
   43228       if( rc!=SQLITE_OK ) break;
   43229       iOffset = (iDbpage-1)*(i64)szPage;
   43230       testcase( IS_BIG_INT(iOffset) );
   43231       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
   43232       if( rc!=SQLITE_OK ) break;
   43233     }
   43234 
   43235     /* If work was actually accomplished... */
   43236     if( rc==SQLITE_OK ){
   43237       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
   43238         i64 szDb = pWal->hdr.nPage*(i64)szPage;
   43239         testcase( IS_BIG_INT(szDb) );
   43240         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
   43241         if( rc==SQLITE_OK && sync_flags ){
   43242           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
   43243         }
   43244       }
   43245       if( rc==SQLITE_OK ){
   43246         pInfo->nBackfill = mxSafeFrame;
   43247       }
   43248     }
   43249 
   43250     /* Release the reader lock held while backfilling */
   43251     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
   43252   }else if( rc==SQLITE_BUSY ){
   43253     /* Reset the return code so as not to report a checkpoint failure
   43254     ** just because active readers prevent any backfill.
   43255     */
   43256     rc = SQLITE_OK;
   43257   }
   43258 
   43259  walcheckpoint_out:
   43260   walIteratorFree(pIter);
   43261   return rc;
   43262 }
   43263 
   43264 /*
   43265 ** Close a connection to a log file.
   43266 */
   43267 SQLITE_PRIVATE int sqlite3WalClose(
   43268   Wal *pWal,                      /* Wal to close */
   43269   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
   43270   int nBuf,
   43271   u8 *zBuf                        /* Buffer of at least nBuf bytes */
   43272 ){
   43273   int rc = SQLITE_OK;
   43274   if( pWal ){
   43275     int isDelete = 0;             /* True to unlink wal and wal-index files */
   43276 
   43277     /* If an EXCLUSIVE lock can be obtained on the database file (using the
   43278     ** ordinary, rollback-mode locking methods, this guarantees that the
   43279     ** connection associated with this log file is the only connection to
   43280     ** the database. In this case checkpoint the database and unlink both
   43281     ** the wal and wal-index files.
   43282     **
   43283     ** The EXCLUSIVE lock is not released before returning.
   43284     */
   43285     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
   43286     if( rc==SQLITE_OK ){
   43287       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
   43288         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
   43289       }
   43290       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
   43291       if( rc==SQLITE_OK ){
   43292         isDelete = 1;
   43293       }
   43294     }
   43295 
   43296     walIndexClose(pWal, isDelete);
   43297     sqlite3OsClose(pWal->pWalFd);
   43298     if( isDelete ){
   43299       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
   43300     }
   43301     WALTRACE(("WAL%p: closed\n", pWal));
   43302     sqlite3_free((void *)pWal->apWiData);
   43303     sqlite3_free(pWal);
   43304   }
   43305   return rc;
   43306 }
   43307 
   43308 /*
   43309 ** Try to read the wal-index header.  Return 0 on success and 1 if
   43310 ** there is a problem.
   43311 **
   43312 ** The wal-index is in shared memory.  Another thread or process might
   43313 ** be writing the header at the same time this procedure is trying to
   43314 ** read it, which might result in inconsistency.  A dirty read is detected
   43315 ** by verifying that both copies of the header are the same and also by
   43316 ** a checksum on the header.
   43317 **
   43318 ** If and only if the read is consistent and the header is different from
   43319 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
   43320 ** and *pChanged is set to 1.
   43321 **
   43322 ** If the checksum cannot be verified return non-zero. If the header
   43323 ** is read successfully and the checksum verified, return zero.
   43324 */
   43325 static int walIndexTryHdr(Wal *pWal, int *pChanged){
   43326   u32 aCksum[2];                  /* Checksum on the header content */
   43327   WalIndexHdr h1, h2;             /* Two copies of the header content */
   43328   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
   43329 
   43330   /* The first page of the wal-index must be mapped at this point. */
   43331   assert( pWal->nWiData>0 && pWal->apWiData[0] );
   43332 
   43333   /* Read the header. This might happen concurrently with a write to the
   43334   ** same area of shared memory on a different CPU in a SMP,
   43335   ** meaning it is possible that an inconsistent snapshot is read
   43336   ** from the file. If this happens, return non-zero.
   43337   **
   43338   ** There are two copies of the header at the beginning of the wal-index.
   43339   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   43340   ** Memory barriers are used to prevent the compiler or the hardware from
   43341   ** reordering the reads and writes.
   43342   */
   43343   aHdr = walIndexHdr(pWal);
   43344   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
   43345   walShmBarrier(pWal);
   43346   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
   43347 
   43348   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
   43349     return 1;   /* Dirty read */
   43350   }
   43351   if( h1.isInit==0 ){
   43352     return 1;   /* Malformed header - probably all zeros */
   43353   }
   43354   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
   43355   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
   43356     return 1;   /* Checksum does not match */
   43357   }
   43358 
   43359   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
   43360     *pChanged = 1;
   43361     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
   43362     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   43363     testcase( pWal->szPage<=32768 );
   43364     testcase( pWal->szPage>=65536 );
   43365   }
   43366 
   43367   /* The header was successfully read. Return zero. */
   43368   return 0;
   43369 }
   43370 
   43371 /*
   43372 ** Read the wal-index header from the wal-index and into pWal->hdr.
   43373 ** If the wal-header appears to be corrupt, try to reconstruct the
   43374 ** wal-index from the WAL before returning.
   43375 **
   43376 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
   43377 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
   43378 ** to 0.
   43379 **
   43380 ** If the wal-index header is successfully read, return SQLITE_OK.
   43381 ** Otherwise an SQLite error code.
   43382 */
   43383 static int walIndexReadHdr(Wal *pWal, int *pChanged){
   43384   int rc;                         /* Return code */
   43385   int badHdr;                     /* True if a header read failed */
   43386   volatile u32 *page0;            /* Chunk of wal-index containing header */
   43387 
   43388   /* Ensure that page 0 of the wal-index (the page that contains the
   43389   ** wal-index header) is mapped. Return early if an error occurs here.
   43390   */
   43391   assert( pChanged );
   43392   rc = walIndexPage(pWal, 0, &page0);
   43393   if( rc!=SQLITE_OK ){
   43394     return rc;
   43395   };
   43396   assert( page0 || pWal->writeLock==0 );
   43397 
   43398   /* If the first page of the wal-index has been mapped, try to read the
   43399   ** wal-index header immediately, without holding any lock. This usually
   43400   ** works, but may fail if the wal-index header is corrupt or currently
   43401   ** being modified by another thread or process.
   43402   */
   43403   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
   43404 
   43405   /* If the first attempt failed, it might have been due to a race
   43406   ** with a writer.  So get a WRITE lock and try again.
   43407   */
   43408   assert( badHdr==0 || pWal->writeLock==0 );
   43409   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
   43410     pWal->writeLock = 1;
   43411     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
   43412       badHdr = walIndexTryHdr(pWal, pChanged);
   43413       if( badHdr ){
   43414         /* If the wal-index header is still malformed even while holding
   43415         ** a WRITE lock, it can only mean that the header is corrupted and
   43416         ** needs to be reconstructed.  So run recovery to do exactly that.
   43417         */
   43418         rc = walIndexRecover(pWal);
   43419         *pChanged = 1;
   43420       }
   43421     }
   43422     pWal->writeLock = 0;
   43423     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   43424   }
   43425 
   43426   /* If the header is read successfully, check the version number to make
   43427   ** sure the wal-index was not constructed with some future format that
   43428   ** this version of SQLite cannot understand.
   43429   */
   43430   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
   43431     rc = SQLITE_CANTOPEN_BKPT;
   43432   }
   43433 
   43434   return rc;
   43435 }
   43436 
   43437 /*
   43438 ** This is the value that walTryBeginRead returns when it needs to
   43439 ** be retried.
   43440 */
   43441 #define WAL_RETRY  (-1)
   43442 
   43443 /*
   43444 ** Attempt to start a read transaction.  This might fail due to a race or
   43445 ** other transient condition.  When that happens, it returns WAL_RETRY to
   43446 ** indicate to the caller that it is safe to retry immediately.
   43447 **
   43448 ** On success return SQLITE_OK.  On a permanent failure (such an
   43449 ** I/O error or an SQLITE_BUSY because another process is running
   43450 ** recovery) return a positive error code.
   43451 **
   43452 ** The useWal parameter is true to force the use of the WAL and disable
   43453 ** the case where the WAL is bypassed because it has been completely
   43454 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
   43455 ** to make a copy of the wal-index header into pWal->hdr.  If the
   43456 ** wal-index header has changed, *pChanged is set to 1 (as an indication
   43457 ** to the caller that the local paget cache is obsolete and needs to be
   43458 ** flushed.)  When useWal==1, the wal-index header is assumed to already
   43459 ** be loaded and the pChanged parameter is unused.
   43460 **
   43461 ** The caller must set the cnt parameter to the number of prior calls to
   43462 ** this routine during the current read attempt that returned WAL_RETRY.
   43463 ** This routine will start taking more aggressive measures to clear the
   43464 ** race conditions after multiple WAL_RETRY returns, and after an excessive
   43465 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
   43466 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
   43467 ** and is not honoring the locking protocol.  There is a vanishingly small
   43468 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
   43469 ** bad luck when there is lots of contention for the wal-index, but that
   43470 ** possibility is so small that it can be safely neglected, we believe.
   43471 **
   43472 ** On success, this routine obtains a read lock on
   43473 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
   43474 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
   43475 ** that means the Wal does not hold any read lock.  The reader must not
   43476 ** access any database page that is modified by a WAL frame up to and
   43477 ** including frame number aReadMark[pWal->readLock].  The reader will
   43478 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
   43479 ** Or if pWal->readLock==0, then the reader will ignore the WAL
   43480 ** completely and get all content directly from the database file.
   43481 ** If the useWal parameter is 1 then the WAL will never be ignored and
   43482 ** this routine will always set pWal->readLock>0 on success.
   43483 ** When the read transaction is completed, the caller must release the
   43484 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
   43485 **
   43486 ** This routine uses the nBackfill and aReadMark[] fields of the header
   43487 ** to select a particular WAL_READ_LOCK() that strives to let the
   43488 ** checkpoint process do as much work as possible.  This routine might
   43489 ** update values of the aReadMark[] array in the header, but if it does
   43490 ** so it takes care to hold an exclusive lock on the corresponding
   43491 ** WAL_READ_LOCK() while changing values.
   43492 */
   43493 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   43494   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
   43495   u32 mxReadMark;                 /* Largest aReadMark[] value */
   43496   int mxI;                        /* Index of largest aReadMark[] value */
   43497   int i;                          /* Loop counter */
   43498   int rc = SQLITE_OK;             /* Return code  */
   43499 
   43500   assert( pWal->readLock<0 );     /* Not currently locked */
   43501 
   43502   /* Take steps to avoid spinning forever if there is a protocol error.
   43503   **
   43504   ** Circumstances that cause a RETRY should only last for the briefest
   43505   ** instances of time.  No I/O or other system calls are done while the
   43506   ** locks are held, so the locks should not be held for very long. But
   43507   ** if we are unlucky, another process that is holding a lock might get
   43508   ** paged out or take a page-fault that is time-consuming to resolve,
   43509   ** during the few nanoseconds that it is holding the lock.  In that case,
   43510   ** it might take longer than normal for the lock to free.
   43511   **
   43512   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   43513   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   43514   ** is more of a scheduler yield than an actual delay.  But on the 10th
   43515   ** an subsequent retries, the delays start becoming longer and longer,
   43516   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
   43517   ** The total delay time before giving up is less than 1 second.
   43518   */
   43519   if( cnt>5 ){
   43520     int nDelay = 1;                      /* Pause time in microseconds */
   43521     if( cnt>100 ){
   43522       VVA_ONLY( pWal->lockError = 1; )
   43523       return SQLITE_PROTOCOL;
   43524     }
   43525     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
   43526     sqlite3OsSleep(pWal->pVfs, nDelay);
   43527   }
   43528 
   43529   if( !useWal ){
   43530     rc = walIndexReadHdr(pWal, pChanged);
   43531     if( rc==SQLITE_BUSY ){
   43532       /* If there is not a recovery running in another thread or process
   43533       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
   43534       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
   43535       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
   43536       ** would be technically correct.  But the race is benign since with
   43537       ** WAL_RETRY this routine will be called again and will probably be
   43538       ** right on the second iteration.
   43539       */
   43540       if( pWal->apWiData[0]==0 ){
   43541         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
   43542         ** We assume this is a transient condition, so return WAL_RETRY. The
   43543         ** xShmMap() implementation used by the default unix and win32 VFS
   43544         ** modules may return SQLITE_BUSY due to a race condition in the
   43545         ** code that determines whether or not the shared-memory region
   43546         ** must be zeroed before the requested page is returned.
   43547         */
   43548         rc = WAL_RETRY;
   43549       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
   43550         walUnlockShared(pWal, WAL_RECOVER_LOCK);
   43551         rc = WAL_RETRY;
   43552       }else if( rc==SQLITE_BUSY ){
   43553         rc = SQLITE_BUSY_RECOVERY;
   43554       }
   43555     }
   43556     if( rc!=SQLITE_OK ){
   43557       return rc;
   43558     }
   43559   }
   43560 
   43561   pInfo = walCkptInfo(pWal);
   43562   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
   43563     /* The WAL has been completely backfilled (or it is empty).
   43564     ** and can be safely ignored.
   43565     */
   43566     rc = walLockShared(pWal, WAL_READ_LOCK(0));
   43567     walShmBarrier(pWal);
   43568     if( rc==SQLITE_OK ){
   43569       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
   43570         /* It is not safe to allow the reader to continue here if frames
   43571         ** may have been appended to the log before READ_LOCK(0) was obtained.
   43572         ** When holding READ_LOCK(0), the reader ignores the entire log file,
   43573         ** which implies that the database file contains a trustworthy
   43574         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
   43575         ** happening, this is usually correct.
   43576         **
   43577         ** However, if frames have been appended to the log (or if the log
   43578         ** is wrapped and written for that matter) before the READ_LOCK(0)
   43579         ** is obtained, that is not necessarily true. A checkpointer may
   43580         ** have started to backfill the appended frames but crashed before
   43581         ** it finished. Leaving a corrupt image in the database file.
   43582         */
   43583         walUnlockShared(pWal, WAL_READ_LOCK(0));
   43584         return WAL_RETRY;
   43585       }
   43586       pWal->readLock = 0;
   43587       return SQLITE_OK;
   43588     }else if( rc!=SQLITE_BUSY ){
   43589       return rc;
   43590     }
   43591   }
   43592 
   43593   /* If we get this far, it means that the reader will want to use
   43594   ** the WAL to get at content from recent commits.  The job now is
   43595   ** to select one of the aReadMark[] entries that is closest to
   43596   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
   43597   */
   43598   mxReadMark = 0;
   43599   mxI = 0;
   43600   for(i=1; i<WAL_NREADER; i++){
   43601     u32 thisMark = pInfo->aReadMark[i];
   43602     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
   43603       assert( thisMark!=READMARK_NOT_USED );
   43604       mxReadMark = thisMark;
   43605       mxI = i;
   43606     }
   43607   }
   43608   /* There was once an "if" here. The extra "{" is to preserve indentation. */
   43609   {
   43610     if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
   43611       for(i=1; i<WAL_NREADER; i++){
   43612         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
   43613         if( rc==SQLITE_OK ){
   43614           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
   43615           mxI = i;
   43616           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
   43617           break;
   43618         }else if( rc!=SQLITE_BUSY ){
   43619           return rc;
   43620         }
   43621       }
   43622     }
   43623     if( mxI==0 ){
   43624       assert( rc==SQLITE_BUSY );
   43625       return WAL_RETRY;
   43626     }
   43627 
   43628     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
   43629     if( rc ){
   43630       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
   43631     }
   43632     /* Now that the read-lock has been obtained, check that neither the
   43633     ** value in the aReadMark[] array or the contents of the wal-index
   43634     ** header have changed.
   43635     **
   43636     ** It is necessary to check that the wal-index header did not change
   43637     ** between the time it was read and when the shared-lock was obtained
   43638     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
   43639     ** that the log file may have been wrapped by a writer, or that frames
   43640     ** that occur later in the log than pWal->hdr.mxFrame may have been
   43641     ** copied into the database by a checkpointer. If either of these things
   43642     ** happened, then reading the database with the current value of
   43643     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
   43644     ** instead.
   43645     **
   43646     ** This does not guarantee that the copy of the wal-index header is up to
   43647     ** date before proceeding. That would not be possible without somehow
   43648     ** blocking writers. It only guarantees that a dangerous checkpoint or
   43649     ** log-wrap (either of which would require an exclusive lock on
   43650     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
   43651     */
   43652     walShmBarrier(pWal);
   43653     if( pInfo->aReadMark[mxI]!=mxReadMark
   43654      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
   43655     ){
   43656       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
   43657       return WAL_RETRY;
   43658     }else{
   43659       assert( mxReadMark<=pWal->hdr.mxFrame );
   43660       pWal->readLock = (i16)mxI;
   43661     }
   43662   }
   43663   return rc;
   43664 }
   43665 
   43666 /*
   43667 ** Begin a read transaction on the database.
   43668 **
   43669 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
   43670 ** it takes a snapshot of the state of the WAL and wal-index for the current
   43671 ** instant in time.  The current thread will continue to use this snapshot.
   43672 ** Other threads might append new content to the WAL and wal-index but
   43673 ** that extra content is ignored by the current thread.
   43674 **
   43675 ** If the database contents have changes since the previous read
   43676 ** transaction, then *pChanged is set to 1 before returning.  The
   43677 ** Pager layer will use this to know that is cache is stale and
   43678 ** needs to be flushed.
   43679 */
   43680 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   43681   int rc;                         /* Return code */
   43682   int cnt = 0;                    /* Number of TryBeginRead attempts */
   43683 
   43684   do{
   43685     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
   43686   }while( rc==WAL_RETRY );
   43687   testcase( (rc&0xff)==SQLITE_BUSY );
   43688   testcase( (rc&0xff)==SQLITE_IOERR );
   43689   testcase( rc==SQLITE_PROTOCOL );
   43690   testcase( rc==SQLITE_OK );
   43691   return rc;
   43692 }
   43693 
   43694 /*
   43695 ** Finish with a read transaction.  All this does is release the
   43696 ** read-lock.
   43697 */
   43698 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
   43699   sqlite3WalEndWriteTransaction(pWal);
   43700   if( pWal->readLock>=0 ){
   43701     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   43702     pWal->readLock = -1;
   43703   }
   43704 }
   43705 
   43706 /*
   43707 ** Read a page from the WAL, if it is present in the WAL and if the
   43708 ** current read transaction is configured to use the WAL.
   43709 **
   43710 ** The *pInWal is set to 1 if the requested page is in the WAL and
   43711 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
   43712 ** the WAL and needs to be read out of the database.
   43713 */
   43714 SQLITE_PRIVATE int sqlite3WalRead(
   43715   Wal *pWal,                      /* WAL handle */
   43716   Pgno pgno,                      /* Database page number to read data for */
   43717   int *pInWal,                    /* OUT: True if data is read from WAL */
   43718   int nOut,                       /* Size of buffer pOut in bytes */
   43719   u8 *pOut                        /* Buffer to write page data to */
   43720 ){
   43721   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
   43722   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
   43723   int iHash;                      /* Used to loop through N hash tables */
   43724 
   43725   /* This routine is only be called from within a read transaction. */
   43726   assert( pWal->readLock>=0 || pWal->lockError );
   43727 
   43728   /* If the "last page" field of the wal-index header snapshot is 0, then
   43729   ** no data will be read from the wal under any circumstances. Return early
   43730   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
   43731   ** then the WAL is ignored by the reader so return early, as if the
   43732   ** WAL were empty.
   43733   */
   43734   if( iLast==0 || pWal->readLock==0 ){
   43735     *pInWal = 0;
   43736     return SQLITE_OK;
   43737   }
   43738 
   43739   /* Search the hash table or tables for an entry matching page number
   43740   ** pgno. Each iteration of the following for() loop searches one
   43741   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   43742   **
   43743   ** This code might run concurrently to the code in walIndexAppend()
   43744   ** that adds entries to the wal-index (and possibly to this hash
   43745   ** table). This means the value just read from the hash
   43746   ** slot (aHash[iKey]) may have been added before or after the
   43747   ** current read transaction was opened. Values added after the
   43748   ** read transaction was opened may have been written incorrectly -
   43749   ** i.e. these slots may contain garbage data. However, we assume
   43750   ** that any slots written before the current read transaction was
   43751   ** opened remain unmodified.
   43752   **
   43753   ** For the reasons above, the if(...) condition featured in the inner
   43754   ** loop of the following block is more stringent that would be required
   43755   ** if we had exclusive access to the hash-table:
   43756   **
   43757   **   (aPgno[iFrame]==pgno):
   43758   **     This condition filters out normal hash-table collisions.
   43759   **
   43760   **   (iFrame<=iLast):
   43761   **     This condition filters out entries that were added to the hash
   43762   **     table after the current read-transaction had started.
   43763   */
   43764   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
   43765     volatile ht_slot *aHash;      /* Pointer to hash table */
   43766     volatile u32 *aPgno;          /* Pointer to array of page numbers */
   43767     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
   43768     int iKey;                     /* Hash slot index */
   43769     int nCollide;                 /* Number of hash collisions remaining */
   43770     int rc;                       /* Error code */
   43771 
   43772     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
   43773     if( rc!=SQLITE_OK ){
   43774       return rc;
   43775     }
   43776     nCollide = HASHTABLE_NSLOT;
   43777     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
   43778       u32 iFrame = aHash[iKey] + iZero;
   43779       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
   43780         assert( iFrame>iRead );
   43781         iRead = iFrame;
   43782       }
   43783       if( (nCollide--)==0 ){
   43784         return SQLITE_CORRUPT_BKPT;
   43785       }
   43786     }
   43787   }
   43788 
   43789 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
   43790   /* If expensive assert() statements are available, do a linear search
   43791   ** of the wal-index file content. Make sure the results agree with the
   43792   ** result obtained using the hash indexes above.  */
   43793   {
   43794     u32 iRead2 = 0;
   43795     u32 iTest;
   43796     for(iTest=iLast; iTest>0; iTest--){
   43797       if( walFramePgno(pWal, iTest)==pgno ){
   43798         iRead2 = iTest;
   43799         break;
   43800       }
   43801     }
   43802     assert( iRead==iRead2 );
   43803   }
   43804 #endif
   43805 
   43806   /* If iRead is non-zero, then it is the log frame number that contains the
   43807   ** required page. Read and return data from the log file.
   43808   */
   43809   if( iRead ){
   43810     int sz;
   43811     i64 iOffset;
   43812     sz = pWal->hdr.szPage;
   43813     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
   43814     testcase( sz<=32768 );
   43815     testcase( sz>=65536 );
   43816     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
   43817     *pInWal = 1;
   43818     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   43819     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
   43820   }
   43821 
   43822   *pInWal = 0;
   43823   return SQLITE_OK;
   43824 }
   43825 
   43826 
   43827 /*
   43828 ** Return the size of the database in pages (or zero, if unknown).
   43829 */
   43830 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
   43831   if( pWal && ALWAYS(pWal->readLock>=0) ){
   43832     return pWal->hdr.nPage;
   43833   }
   43834   return 0;
   43835 }
   43836 
   43837 
   43838 /*
   43839 ** This function starts a write transaction on the WAL.
   43840 **
   43841 ** A read transaction must have already been started by a prior call
   43842 ** to sqlite3WalBeginReadTransaction().
   43843 **
   43844 ** If another thread or process has written into the database since
   43845 ** the read transaction was started, then it is not possible for this
   43846 ** thread to write as doing so would cause a fork.  So this routine
   43847 ** returns SQLITE_BUSY in that case and no write transaction is started.
   43848 **
   43849 ** There can only be a single writer active at a time.
   43850 */
   43851 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   43852   int rc;
   43853 
   43854   /* Cannot start a write transaction without first holding a read
   43855   ** transaction. */
   43856   assert( pWal->readLock>=0 );
   43857 
   43858   if( pWal->readOnly ){
   43859     return SQLITE_READONLY;
   43860   }
   43861 
   43862   /* Only one writer allowed at a time.  Get the write lock.  Return
   43863   ** SQLITE_BUSY if unable.
   43864   */
   43865   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
   43866   if( rc ){
   43867     return rc;
   43868   }
   43869   pWal->writeLock = 1;
   43870 
   43871   /* If another connection has written to the database file since the
   43872   ** time the read transaction on this connection was started, then
   43873   ** the write is disallowed.
   43874   */
   43875   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
   43876     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   43877     pWal->writeLock = 0;
   43878     rc = SQLITE_BUSY;
   43879   }
   43880 
   43881   return rc;
   43882 }
   43883 
   43884 /*
   43885 ** End a write transaction.  The commit has already been done.  This
   43886 ** routine merely releases the lock.
   43887 */
   43888 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
   43889   if( pWal->writeLock ){
   43890     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
   43891     pWal->writeLock = 0;
   43892   }
   43893   return SQLITE_OK;
   43894 }
   43895 
   43896 /*
   43897 ** If any data has been written (but not committed) to the log file, this
   43898 ** function moves the write-pointer back to the start of the transaction.
   43899 **
   43900 ** Additionally, the callback function is invoked for each frame written
   43901 ** to the WAL since the start of the transaction. If the callback returns
   43902 ** other than SQLITE_OK, it is not invoked again and the error code is
   43903 ** returned to the caller.
   43904 **
   43905 ** Otherwise, if the callback function does not return an error, this
   43906 ** function returns SQLITE_OK.
   43907 */
   43908 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
   43909   int rc = SQLITE_OK;
   43910   if( ALWAYS(pWal->writeLock) ){
   43911     Pgno iMax = pWal->hdr.mxFrame;
   43912     Pgno iFrame;
   43913 
   43914     /* Restore the clients cache of the wal-index header to the state it
   43915     ** was in before the client began writing to the database.
   43916     */
   43917     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
   43918 
   43919     for(iFrame=pWal->hdr.mxFrame+1;
   43920         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
   43921         iFrame++
   43922     ){
   43923       /* This call cannot fail. Unless the page for which the page number
   43924       ** is passed as the second argument is (a) in the cache and
   43925       ** (b) has an outstanding reference, then xUndo is either a no-op
   43926       ** (if (a) is false) or simply expels the page from the cache (if (b)
   43927       ** is false).
   43928       **
   43929       ** If the upper layer is doing a rollback, it is guaranteed that there
   43930       ** are no outstanding references to any page other than page 1. And
   43931       ** page 1 is never written to the log until the transaction is
   43932       ** committed. As a result, the call to xUndo may not fail.
   43933       */
   43934       assert( walFramePgno(pWal, iFrame)!=1 );
   43935       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
   43936     }
   43937     walCleanupHash(pWal);
   43938   }
   43939   assert( rc==SQLITE_OK );
   43940   return rc;
   43941 }
   43942 
   43943 /*
   43944 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
   43945 ** values. This function populates the array with values required to
   43946 ** "rollback" the write position of the WAL handle back to the current
   43947 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
   43948 */
   43949 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   43950   assert( pWal->writeLock );
   43951   aWalData[0] = pWal->hdr.mxFrame;
   43952   aWalData[1] = pWal->hdr.aFrameCksum[0];
   43953   aWalData[2] = pWal->hdr.aFrameCksum[1];
   43954   aWalData[3] = pWal->nCkpt;
   43955 }
   43956 
   43957 /*
   43958 ** Move the write position of the WAL back to the point identified by
   43959 ** the values in the aWalData[] array. aWalData must point to an array
   43960 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
   43961 ** by a call to WalSavepoint().
   43962 */
   43963 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
   43964   int rc = SQLITE_OK;
   43965 
   43966   assert( pWal->writeLock );
   43967   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
   43968 
   43969   if( aWalData[3]!=pWal->nCkpt ){
   43970     /* This savepoint was opened immediately after the write-transaction
   43971     ** was started. Right after that, the writer decided to wrap around
   43972     ** to the start of the log. Update the savepoint values to match.
   43973     */
   43974     aWalData[0] = 0;
   43975     aWalData[3] = pWal->nCkpt;
   43976   }
   43977 
   43978   if( aWalData[0]<pWal->hdr.mxFrame ){
   43979     pWal->hdr.mxFrame = aWalData[0];
   43980     pWal->hdr.aFrameCksum[0] = aWalData[1];
   43981     pWal->hdr.aFrameCksum[1] = aWalData[2];
   43982     walCleanupHash(pWal);
   43983   }
   43984 
   43985   return rc;
   43986 }
   43987 
   43988 /*
   43989 ** This function is called just before writing a set of frames to the log
   43990 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
   43991 ** to the current log file, it is possible to overwrite the start of the
   43992 ** existing log file with the new frames (i.e. "reset" the log). If so,
   43993 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
   43994 ** unchanged.
   43995 **
   43996 ** SQLITE_OK is returned if no error is encountered (regardless of whether
   43997 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
   43998 ** if an error occurs.
   43999 */
   44000 static int walRestartLog(Wal *pWal){
   44001   int rc = SQLITE_OK;
   44002   int cnt;
   44003 
   44004   if( pWal->readLock==0 ){
   44005     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
   44006     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
   44007     if( pInfo->nBackfill>0 ){
   44008       u32 salt1;
   44009       sqlite3_randomness(4, &salt1);
   44010       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   44011       if( rc==SQLITE_OK ){
   44012         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
   44013         ** readers are currently using the WAL), then the transactions
   44014         ** frames will overwrite the start of the existing log. Update the
   44015         ** wal-index header to reflect this.
   44016         **
   44017         ** In theory it would be Ok to update the cache of the header only
   44018         ** at this point. But updating the actual wal-index header is also
   44019         ** safe and means there is no special case for sqlite3WalUndo()
   44020         ** to handle if this transaction is rolled back.
   44021         */
   44022         int i;                    /* Loop counter */
   44023         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
   44024         pWal->nCkpt++;
   44025         pWal->hdr.mxFrame = 0;
   44026         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   44027         aSalt[1] = salt1;
   44028         walIndexWriteHdr(pWal);
   44029         pInfo->nBackfill = 0;
   44030         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
   44031         assert( pInfo->aReadMark[0]==0 );
   44032         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   44033       }else if( rc!=SQLITE_BUSY ){
   44034         return rc;
   44035       }
   44036     }
   44037     walUnlockShared(pWal, WAL_READ_LOCK(0));
   44038     pWal->readLock = -1;
   44039     cnt = 0;
   44040     do{
   44041       int notUsed;
   44042       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
   44043     }while( rc==WAL_RETRY );
   44044     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
   44045     testcase( (rc&0xff)==SQLITE_IOERR );
   44046     testcase( rc==SQLITE_PROTOCOL );
   44047     testcase( rc==SQLITE_OK );
   44048   }
   44049   return rc;
   44050 }
   44051 
   44052 /*
   44053 ** Write a set of frames to the log. The caller must hold the write-lock
   44054 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
   44055 */
   44056 SQLITE_PRIVATE int sqlite3WalFrames(
   44057   Wal *pWal,                      /* Wal handle to write to */
   44058   int szPage,                     /* Database page-size in bytes */
   44059   PgHdr *pList,                   /* List of dirty pages to write */
   44060   Pgno nTruncate,                 /* Database size after this commit */
   44061   int isCommit,                   /* True if this is a commit */
   44062   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
   44063 ){
   44064   int rc;                         /* Used to catch return codes */
   44065   u32 iFrame;                     /* Next frame address */
   44066   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
   44067   PgHdr *p;                       /* Iterator to run through pList with. */
   44068   PgHdr *pLast = 0;               /* Last frame in list */
   44069   int nLast = 0;                  /* Number of extra copies of last page */
   44070 
   44071   assert( pList );
   44072   assert( pWal->writeLock );
   44073 
   44074 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   44075   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
   44076     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
   44077               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
   44078   }
   44079 #endif
   44080 
   44081   /* See if it is possible to write these frames into the start of the
   44082   ** log file, instead of appending to it at pWal->hdr.mxFrame.
   44083   */
   44084   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
   44085     return rc;
   44086   }
   44087 
   44088   /* If this is the first frame written into the log, write the WAL
   44089   ** header to the start of the WAL file. See comments at the top of
   44090   ** this source file for a description of the WAL header format.
   44091   */
   44092   iFrame = pWal->hdr.mxFrame;
   44093   if( iFrame==0 ){
   44094     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
   44095     u32 aCksum[2];                /* Checksum for wal-header */
   44096 
   44097     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
   44098     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
   44099     sqlite3Put4byte(&aWalHdr[8], szPage);
   44100     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
   44101     sqlite3_randomness(8, pWal->hdr.aSalt);
   44102     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
   44103     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
   44104     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
   44105     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
   44106 
   44107     pWal->szPage = szPage;
   44108     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
   44109     pWal->hdr.aFrameCksum[0] = aCksum[0];
   44110     pWal->hdr.aFrameCksum[1] = aCksum[1];
   44111 
   44112     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
   44113     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
   44114     if( rc!=SQLITE_OK ){
   44115       return rc;
   44116     }
   44117   }
   44118   assert( (int)pWal->szPage==szPage );
   44119 
   44120   /* Write the log file. */
   44121   for(p=pList; p; p=p->pDirty){
   44122     u32 nDbsize;                  /* Db-size field for frame header */
   44123     i64 iOffset;                  /* Write offset in log file */
   44124     void *pData;
   44125 
   44126     iOffset = walFrameOffset(++iFrame, szPage);
   44127     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   44128 
   44129     /* Populate and write the frame header */
   44130     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
   44131 #if defined(SQLITE_HAS_CODEC)
   44132     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
   44133 #else
   44134     pData = p->pData;
   44135 #endif
   44136     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
   44137     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
   44138     if( rc!=SQLITE_OK ){
   44139       return rc;
   44140     }
   44141 
   44142     /* Write the page data */
   44143     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
   44144     if( rc!=SQLITE_OK ){
   44145       return rc;
   44146     }
   44147     pLast = p;
   44148   }
   44149 
   44150   /* Sync the log file if the 'isSync' flag was specified. */
   44151   if( sync_flags ){
   44152     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
   44153     i64 iOffset = walFrameOffset(iFrame+1, szPage);
   44154 
   44155     assert( isCommit );
   44156     assert( iSegment>0 );
   44157 
   44158     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
   44159     while( iOffset<iSegment ){
   44160       void *pData;
   44161 #if defined(SQLITE_HAS_CODEC)
   44162       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
   44163 #else
   44164       pData = pLast->pData;
   44165 #endif
   44166       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
   44167       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
   44168       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
   44169       if( rc!=SQLITE_OK ){
   44170         return rc;
   44171       }
   44172       iOffset += WAL_FRAME_HDRSIZE;
   44173       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
   44174       if( rc!=SQLITE_OK ){
   44175         return rc;
   44176       }
   44177       nLast++;
   44178       iOffset += szPage;
   44179     }
   44180 
   44181     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
   44182   }
   44183 
   44184   /* Append data to the wal-index. It is not necessary to lock the
   44185   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   44186   ** guarantees that there are no other writers, and no data that may
   44187   ** be in use by existing readers is being overwritten.
   44188   */
   44189   iFrame = pWal->hdr.mxFrame;
   44190   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
   44191     iFrame++;
   44192     rc = walIndexAppend(pWal, iFrame, p->pgno);
   44193   }
   44194   while( nLast>0 && rc==SQLITE_OK ){
   44195     iFrame++;
   44196     nLast--;
   44197     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
   44198   }
   44199 
   44200   if( rc==SQLITE_OK ){
   44201     /* Update the private copy of the header. */
   44202     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
   44203     testcase( szPage<=32768 );
   44204     testcase( szPage>=65536 );
   44205     pWal->hdr.mxFrame = iFrame;
   44206     if( isCommit ){
   44207       pWal->hdr.iChange++;
   44208       pWal->hdr.nPage = nTruncate;
   44209     }
   44210     /* If this is a commit, update the wal-index header too. */
   44211     if( isCommit ){
   44212       walIndexWriteHdr(pWal);
   44213       pWal->iCallback = iFrame;
   44214     }
   44215   }
   44216 
   44217   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
   44218   return rc;
   44219 }
   44220 
   44221 /*
   44222 ** This routine is called to implement sqlite3_wal_checkpoint() and
   44223 ** related interfaces.
   44224 **
   44225 ** Obtain a CHECKPOINT lock and then backfill as much information as
   44226 ** we can from WAL into the database.
   44227 */
   44228 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   44229   Wal *pWal,                      /* Wal connection */
   44230   int sync_flags,                 /* Flags to sync db file with (or 0) */
   44231   int nBuf,                       /* Size of temporary buffer */
   44232   u8 *zBuf                        /* Temporary buffer to use */
   44233 ){
   44234   int rc;                         /* Return code */
   44235   int isChanged = 0;              /* True if a new wal-index header is loaded */
   44236 
   44237   assert( pWal->ckptLock==0 );
   44238 
   44239   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
   44240   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
   44241   if( rc ){
   44242     /* Usually this is SQLITE_BUSY meaning that another thread or process
   44243     ** is already running a checkpoint, or maybe a recovery.  But it might
   44244     ** also be SQLITE_IOERR. */
   44245     return rc;
   44246   }
   44247   pWal->ckptLock = 1;
   44248 
   44249   /* Copy data from the log to the database file. */
   44250   rc = walIndexReadHdr(pWal, &isChanged);
   44251   if( rc==SQLITE_OK ){
   44252     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
   44253   }
   44254   if( isChanged ){
   44255     /* If a new wal-index header was loaded before the checkpoint was
   44256     ** performed, then the pager-cache associated with pWal is now
   44257     ** out of date. So zero the cached wal-index header to ensure that
   44258     ** next time the pager opens a snapshot on this database it knows that
   44259     ** the cache needs to be reset.
   44260     */
   44261     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   44262   }
   44263 
   44264   /* Release the locks. */
   44265   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
   44266   pWal->ckptLock = 0;
   44267   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
   44268   return rc;
   44269 }
   44270 
   44271 /* Return the value to pass to a sqlite3_wal_hook callback, the
   44272 ** number of frames in the WAL at the point of the last commit since
   44273 ** sqlite3WalCallback() was called.  If no commits have occurred since
   44274 ** the last call, then return 0.
   44275 */
   44276 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
   44277   u32 ret = 0;
   44278   if( pWal ){
   44279     ret = pWal->iCallback;
   44280     pWal->iCallback = 0;
   44281   }
   44282   return (int)ret;
   44283 }
   44284 
   44285 /*
   44286 ** This function is called to change the WAL subsystem into or out
   44287 ** of locking_mode=EXCLUSIVE.
   44288 **
   44289 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
   44290 ** into locking_mode=NORMAL.  This means that we must acquire a lock
   44291 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
   44292 ** or if the acquisition of the lock fails, then return 0.  If the
   44293 ** transition out of exclusive-mode is successful, return 1.  This
   44294 ** operation must occur while the pager is still holding the exclusive
   44295 ** lock on the main database file.
   44296 **
   44297 ** If op is one, then change from locking_mode=NORMAL into
   44298 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
   44299 ** be released.  Return 1 if the transition is made and 0 if the
   44300 ** WAL is already in exclusive-locking mode - meaning that this
   44301 ** routine is a no-op.  The pager must already hold the exclusive lock
   44302 ** on the main database file before invoking this operation.
   44303 **
   44304 ** If op is negative, then do a dry-run of the op==1 case but do
   44305 ** not actually change anything. The pager uses this to see if it
   44306 ** should acquire the database exclusive lock prior to invoking
   44307 ** the op==1 case.
   44308 */
   44309 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   44310   int rc;
   44311   assert( pWal->writeLock==0 );
   44312   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
   44313 
   44314   /* pWal->readLock is usually set, but might be -1 if there was a
   44315   ** prior error while attempting to acquire are read-lock. This cannot
   44316   ** happen if the connection is actually in exclusive mode (as no xShmLock
   44317   ** locks are taken in this case). Nor should the pager attempt to
   44318   ** upgrade to exclusive-mode following such an error.
   44319   */
   44320   assert( pWal->readLock>=0 || pWal->lockError );
   44321   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
   44322 
   44323   if( op==0 ){
   44324     if( pWal->exclusiveMode ){
   44325       pWal->exclusiveMode = 0;
   44326       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
   44327         pWal->exclusiveMode = 1;
   44328       }
   44329       rc = pWal->exclusiveMode==0;
   44330     }else{
   44331       /* Already in locking_mode=NORMAL */
   44332       rc = 0;
   44333     }
   44334   }else if( op>0 ){
   44335     assert( pWal->exclusiveMode==0 );
   44336     assert( pWal->readLock>=0 );
   44337     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
   44338     pWal->exclusiveMode = 1;
   44339     rc = 1;
   44340   }else{
   44341     rc = pWal->exclusiveMode==0;
   44342   }
   44343   return rc;
   44344 }
   44345 
   44346 /*
   44347 ** Return true if the argument is non-NULL and the WAL module is using
   44348 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
   44349 ** WAL module is using shared-memory, return false.
   44350 */
   44351 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   44352   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
   44353 }
   44354 
   44355 #endif /* #ifndef SQLITE_OMIT_WAL */
   44356 
   44357 /************** End of wal.c *************************************************/
   44358 /************** Begin file btmutex.c *****************************************/
   44359 /*
   44360 ** 2007 August 27
   44361 **
   44362 ** The author disclaims copyright to this source code.  In place of
   44363 ** a legal notice, here is a blessing:
   44364 **
   44365 **    May you do good and not evil.
   44366 **    May you find forgiveness for yourself and forgive others.
   44367 **    May you share freely, never taking more than you give.
   44368 **
   44369 *************************************************************************
   44370 **
   44371 ** This file contains code used to implement mutexes on Btree objects.
   44372 ** This code really belongs in btree.c.  But btree.c is getting too
   44373 ** big and we want to break it down some.  This packaged seemed like
   44374 ** a good breakout.
   44375 */
   44376 /************** Include btreeInt.h in the middle of btmutex.c ****************/
   44377 /************** Begin file btreeInt.h ****************************************/
   44378 /*
   44379 ** 2004 April 6
   44380 **
   44381 ** The author disclaims copyright to this source code.  In place of
   44382 ** a legal notice, here is a blessing:
   44383 **
   44384 **    May you do good and not evil.
   44385 **    May you find forgiveness for yourself and forgive others.
   44386 **    May you share freely, never taking more than you give.
   44387 **
   44388 *************************************************************************
   44389 ** This file implements a external (disk-based) database using BTrees.
   44390 ** For a detailed discussion of BTrees, refer to
   44391 **
   44392 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
   44393 **     "Sorting And Searching", pages 473-480. Addison-Wesley
   44394 **     Publishing Company, Reading, Massachusetts.
   44395 **
   44396 ** The basic idea is that each page of the file contains N database
   44397 ** entries and N+1 pointers to subpages.
   44398 **
   44399 **   ----------------------------------------------------------------
   44400 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
   44401 **   ----------------------------------------------------------------
   44402 **
   44403 ** All of the keys on the page that Ptr(0) points to have values less
   44404 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
   44405 ** values greater than Key(0) and less than Key(1).  All of the keys
   44406 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
   44407 ** so forth.
   44408 **
   44409 ** Finding a particular key requires reading O(log(M)) pages from the
   44410 ** disk where M is the number of entries in the tree.
   44411 **
   44412 ** In this implementation, a single file can hold one or more separate
   44413 ** BTrees.  Each BTree is identified by the index of its root page.  The
   44414 ** key and data for any entry are combined to form the "payload".  A
   44415 ** fixed amount of payload can be carried directly on the database
   44416 ** page.  If the payload is larger than the preset amount then surplus
   44417 ** bytes are stored on overflow pages.  The payload for an entry
   44418 ** and the preceding pointer are combined to form a "Cell".  Each
   44419 ** page has a small header which contains the Ptr(N) pointer and other
   44420 ** information such as the size of key and data.
   44421 **
   44422 ** FORMAT DETAILS
   44423 **
   44424 ** The file is divided into pages.  The first page is called page 1,
   44425 ** the second is page 2, and so forth.  A page number of zero indicates
   44426 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
   44427 ** Each page can be either a btree page, a freelist page, an overflow
   44428 ** page, or a pointer-map page.
   44429 **
   44430 ** The first page is always a btree page.  The first 100 bytes of the first
   44431 ** page contain a special header (the "file header") that describes the file.
   44432 ** The format of the file header is as follows:
   44433 **
   44434 **   OFFSET   SIZE    DESCRIPTION
   44435 **      0      16     Header string: "SQLite format 3\000"
   44436 **     16       2     Page size in bytes.
   44437 **     18       1     File format write version
   44438 **     19       1     File format read version
   44439 **     20       1     Bytes of unused space at the end of each page
   44440 **     21       1     Max embedded payload fraction
   44441 **     22       1     Min embedded payload fraction
   44442 **     23       1     Min leaf payload fraction
   44443 **     24       4     File change counter
   44444 **     28       4     Reserved for future use
   44445 **     32       4     First freelist page
   44446 **     36       4     Number of freelist pages in the file
   44447 **     40      60     15 4-byte meta values passed to higher layers
   44448 **
   44449 **     40       4     Schema cookie
   44450 **     44       4     File format of schema layer
   44451 **     48       4     Size of page cache
   44452 **     52       4     Largest root-page (auto/incr_vacuum)
   44453 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
   44454 **     60       4     User version
   44455 **     64       4     Incremental vacuum mode
   44456 **     68       4     unused
   44457 **     72       4     unused
   44458 **     76       4     unused
   44459 **
   44460 ** All of the integer values are big-endian (most significant byte first).
   44461 **
   44462 ** The file change counter is incremented when the database is changed
   44463 ** This counter allows other processes to know when the file has changed
   44464 ** and thus when they need to flush their cache.
   44465 **
   44466 ** The max embedded payload fraction is the amount of the total usable
   44467 ** space in a page that can be consumed by a single cell for standard
   44468 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
   44469 ** is to limit the maximum cell size so that at least 4 cells will fit
   44470 ** on one page.  Thus the default max embedded payload fraction is 64.
   44471 **
   44472 ** If the payload for a cell is larger than the max payload, then extra
   44473 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
   44474 ** as many bytes as possible are moved into the overflow pages without letting
   44475 ** the cell size drop below the min embedded payload fraction.
   44476 **
   44477 ** The min leaf payload fraction is like the min embedded payload fraction
   44478 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
   44479 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
   44480 ** not specified in the header.
   44481 **
   44482 ** Each btree pages is divided into three sections:  The header, the
   44483 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
   44484 ** file header that occurs before the page header.
   44485 **
   44486 **      |----------------|
   44487 **      | file header    |   100 bytes.  Page 1 only.
   44488 **      |----------------|
   44489 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
   44490 **      |----------------|
   44491 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
   44492 **      | array          |   |  Grows downward
   44493 **      |                |   v
   44494 **      |----------------|
   44495 **      | unallocated    |
   44496 **      | space          |
   44497 **      |----------------|   ^  Grows upwards
   44498 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
   44499 **      | area           |   |  and free space fragments.
   44500 **      |----------------|
   44501 **
   44502 ** The page headers looks like this:
   44503 **
   44504 **   OFFSET   SIZE     DESCRIPTION
   44505 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
   44506 **      1       2      byte offset to the first freeblock
   44507 **      3       2      number of cells on this page
   44508 **      5       2      first byte of the cell content area
   44509 **      7       1      number of fragmented free bytes
   44510 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
   44511 **
   44512 ** The flags define the format of this btree page.  The leaf flag means that
   44513 ** this page has no children.  The zerodata flag means that this page carries
   44514 ** only keys and no data.  The intkey flag means that the key is a integer
   44515 ** which is stored in the key size entry of the cell header rather than in
   44516 ** the payload area.
   44517 **
   44518 ** The cell pointer array begins on the first byte after the page header.
   44519 ** The cell pointer array contains zero or more 2-byte numbers which are
   44520 ** offsets from the beginning of the page to the cell content in the cell
   44521 ** content area.  The cell pointers occur in sorted order.  The system strives
   44522 ** to keep free space after the last cell pointer so that new cells can
   44523 ** be easily added without having to defragment the page.
   44524 **
   44525 ** Cell content is stored at the very end of the page and grows toward the
   44526 ** beginning of the page.
   44527 **
   44528 ** Unused space within the cell content area is collected into a linked list of
   44529 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
   44530 ** to the first freeblock is given in the header.  Freeblocks occur in
   44531 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
   44532 ** any group of 3 or fewer unused bytes in the cell content area cannot
   44533 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
   44534 ** a fragment.  The total number of bytes in all fragments is recorded.
   44535 ** in the page header at offset 7.
   44536 **
   44537 **    SIZE    DESCRIPTION
   44538 **      2     Byte offset of the next freeblock
   44539 **      2     Bytes in this freeblock
   44540 **
   44541 ** Cells are of variable length.  Cells are stored in the cell content area at
   44542 ** the end of the page.  Pointers to the cells are in the cell pointer array
   44543 ** that immediately follows the page header.  Cells is not necessarily
   44544 ** contiguous or in order, but cell pointers are contiguous and in order.
   44545 **
   44546 ** Cell content makes use of variable length integers.  A variable
   44547 ** length integer is 1 to 9 bytes where the lower 7 bits of each
   44548 ** byte are used.  The integer consists of all bytes that have bit 8 set and
   44549 ** the first byte with bit 8 clear.  The most significant byte of the integer
   44550 ** appears first.  A variable-length integer may not be more than 9 bytes long.
   44551 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
   44552 ** allows a 64-bit integer to be encoded in 9 bytes.
   44553 **
   44554 **    0x00                      becomes  0x00000000
   44555 **    0x7f                      becomes  0x0000007f
   44556 **    0x81 0x00                 becomes  0x00000080
   44557 **    0x82 0x00                 becomes  0x00000100
   44558 **    0x80 0x7f                 becomes  0x0000007f
   44559 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
   44560 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
   44561 **
   44562 ** Variable length integers are used for rowids and to hold the number of
   44563 ** bytes of key and data in a btree cell.
   44564 **
   44565 ** The content of a cell looks like this:
   44566 **
   44567 **    SIZE    DESCRIPTION
   44568 **      4     Page number of the left child. Omitted if leaf flag is set.
   44569 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
   44570 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
   44571 **      *     Payload
   44572 **      4     First page of the overflow chain.  Omitted if no overflow
   44573 **
   44574 ** Overflow pages form a linked list.  Each page except the last is completely
   44575 ** filled with data (pagesize - 4 bytes).  The last page can have as little
   44576 ** as 1 byte of data.
   44577 **
   44578 **    SIZE    DESCRIPTION
   44579 **      4     Page number of next overflow page
   44580 **      *     Data
   44581 **
   44582 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
   44583 ** file header points to the first in a linked list of trunk page.  Each trunk
   44584 ** page points to multiple leaf pages.  The content of a leaf page is
   44585 ** unspecified.  A trunk page looks like this:
   44586 **
   44587 **    SIZE    DESCRIPTION
   44588 **      4     Page number of next trunk page
   44589 **      4     Number of leaf pointers on this page
   44590 **      *     zero or more pages numbers of leaves
   44591 */
   44592 
   44593 
   44594 /* The following value is the maximum cell size assuming a maximum page
   44595 ** size give above.
   44596 */
   44597 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
   44598 
   44599 /* The maximum number of cells on a single page of the database.  This
   44600 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
   44601 ** plus 2 bytes for the index to the cell in the page header).  Such
   44602 ** small cells will be rare, but they are possible.
   44603 */
   44604 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
   44605 
   44606 /* Forward declarations */
   44607 typedef struct MemPage MemPage;
   44608 typedef struct BtLock BtLock;
   44609 
   44610 /*
   44611 ** This is a magic string that appears at the beginning of every
   44612 ** SQLite database in order to identify the file as a real database.
   44613 **
   44614 ** You can change this value at compile-time by specifying a
   44615 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
   44616 ** header must be exactly 16 bytes including the zero-terminator so
   44617 ** the string itself should be 15 characters long.  If you change
   44618 ** the header, then your custom library will not be able to read
   44619 ** databases generated by the standard tools and the standard tools
   44620 ** will not be able to read databases created by your custom library.
   44621 */
   44622 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
   44623 #  define SQLITE_FILE_HEADER "SQLite format 3"
   44624 #endif
   44625 
   44626 /*
   44627 ** Page type flags.  An ORed combination of these flags appear as the
   44628 ** first byte of on-disk image of every BTree page.
   44629 */
   44630 #define PTF_INTKEY    0x01
   44631 #define PTF_ZERODATA  0x02
   44632 #define PTF_LEAFDATA  0x04
   44633 #define PTF_LEAF      0x08
   44634 
   44635 /*
   44636 ** As each page of the file is loaded into memory, an instance of the following
   44637 ** structure is appended and initialized to zero.  This structure stores
   44638 ** information about the page that is decoded from the raw file page.
   44639 **
   44640 ** The pParent field points back to the parent page.  This allows us to
   44641 ** walk up the BTree from any leaf to the root.  Care must be taken to
   44642 ** unref() the parent page pointer when this page is no longer referenced.
   44643 ** The pageDestructor() routine handles that chore.
   44644 **
   44645 ** Access to all fields of this structure is controlled by the mutex
   44646 ** stored in MemPage.pBt->mutex.
   44647 */
   44648 struct MemPage {
   44649   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   44650   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   44651   u8 intKey;           /* True if intkey flag is set */
   44652   u8 leaf;             /* True if leaf flag is set */
   44653   u8 hasData;          /* True if this page stores data */
   44654   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   44655   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   44656   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   44657   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   44658   u16 cellOffset;      /* Index in aData of first cell pointer */
   44659   u16 nFree;           /* Number of free bytes on the page */
   44660   u16 nCell;           /* Number of cells on this page, local and ovfl */
   44661   u16 maskPage;        /* Mask for page offset */
   44662   struct _OvflCell {   /* Cells that will not fit on aData[] */
   44663     u8 *pCell;          /* Pointers to the body of the overflow cell */
   44664     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
   44665   } aOvfl[5];
   44666   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   44667   u8 *aData;           /* Pointer to disk image of the page data */
   44668   DbPage *pDbPage;     /* Pager page handle */
   44669   Pgno pgno;           /* Page number for this page */
   44670 };
   44671 
   44672 /*
   44673 ** The in-memory image of a disk page has the auxiliary information appended
   44674 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
   44675 ** that extra information.
   44676 */
   44677 #define EXTRA_SIZE sizeof(MemPage)
   44678 
   44679 /*
   44680 ** A linked list of the following structures is stored at BtShared.pLock.
   44681 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
   44682 ** is opened on the table with root page BtShared.iTable. Locks are removed
   44683 ** from this list when a transaction is committed or rolled back, or when
   44684 ** a btree handle is closed.
   44685 */
   44686 struct BtLock {
   44687   Btree *pBtree;        /* Btree handle holding this lock */
   44688   Pgno iTable;          /* Root page of table */
   44689   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
   44690   BtLock *pNext;        /* Next in BtShared.pLock list */
   44691 };
   44692 
   44693 /* Candidate values for BtLock.eLock */
   44694 #define READ_LOCK     1
   44695 #define WRITE_LOCK    2
   44696 
   44697 /* A Btree handle
   44698 **
   44699 ** A database connection contains a pointer to an instance of
   44700 ** this object for every database file that it has open.  This structure
   44701 ** is opaque to the database connection.  The database connection cannot
   44702 ** see the internals of this structure and only deals with pointers to
   44703 ** this structure.
   44704 **
   44705 ** For some database files, the same underlying database cache might be
   44706 ** shared between multiple connections.  In that case, each connection
   44707 ** has it own instance of this object.  But each instance of this object
   44708 ** points to the same BtShared object.  The database cache and the
   44709 ** schema associated with the database file are all contained within
   44710 ** the BtShared object.
   44711 **
   44712 ** All fields in this structure are accessed under sqlite3.mutex.
   44713 ** The pBt pointer itself may not be changed while there exists cursors
   44714 ** in the referenced BtShared that point back to this Btree since those
   44715 ** cursors have to do go through this Btree to find their BtShared and
   44716 ** they often do so without holding sqlite3.mutex.
   44717 */
   44718 struct Btree {
   44719   sqlite3 *db;       /* The database connection holding this btree */
   44720   BtShared *pBt;     /* Sharable content of this btree */
   44721   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
   44722   u8 sharable;       /* True if we can share pBt with another db */
   44723   u8 locked;         /* True if db currently has pBt locked */
   44724   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
   44725   int nBackup;       /* Number of backup operations reading this btree */
   44726   Btree *pNext;      /* List of other sharable Btrees from the same db */
   44727   Btree *pPrev;      /* Back pointer of the same list */
   44728 #ifndef SQLITE_OMIT_SHARED_CACHE
   44729   BtLock lock;       /* Object used to lock page 1 */
   44730 #endif
   44731 };
   44732 
   44733 /*
   44734 ** Btree.inTrans may take one of the following values.
   44735 **
   44736 ** If the shared-data extension is enabled, there may be multiple users
   44737 ** of the Btree structure. At most one of these may open a write transaction,
   44738 ** but any number may have active read transactions.
   44739 */
   44740 #define TRANS_NONE  0
   44741 #define TRANS_READ  1
   44742 #define TRANS_WRITE 2
   44743 
   44744 /*
   44745 ** An instance of this object represents a single database file.
   44746 **
   44747 ** A single database file can be in use as the same time by two
   44748 ** or more database connections.  When two or more connections are
   44749 ** sharing the same database file, each connection has it own
   44750 ** private Btree object for the file and each of those Btrees points
   44751 ** to this one BtShared object.  BtShared.nRef is the number of
   44752 ** connections currently sharing this database file.
   44753 **
   44754 ** Fields in this structure are accessed under the BtShared.mutex
   44755 ** mutex, except for nRef and pNext which are accessed under the
   44756 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
   44757 ** may not be modified once it is initially set as long as nRef>0.
   44758 ** The pSchema field may be set once under BtShared.mutex and
   44759 ** thereafter is unchanged as long as nRef>0.
   44760 **
   44761 ** isPending:
   44762 **
   44763 **   If a BtShared client fails to obtain a write-lock on a database
   44764 **   table (because there exists one or more read-locks on the table),
   44765 **   the shared-cache enters 'pending-lock' state and isPending is
   44766 **   set to true.
   44767 **
   44768 **   The shared-cache leaves the 'pending lock' state when either of
   44769 **   the following occur:
   44770 **
   44771 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
   44772 **     2) The number of locks held by other connections drops to zero.
   44773 **
   44774 **   while in the 'pending-lock' state, no connection may start a new
   44775 **   transaction.
   44776 **
   44777 **   This feature is included to help prevent writer-starvation.
   44778 */
   44779 struct BtShared {
   44780   Pager *pPager;        /* The page cache */
   44781   sqlite3 *db;          /* Database connection currently using this Btree */
   44782   BtCursor *pCursor;    /* A list of all open cursors */
   44783   MemPage *pPage1;      /* First page of the database */
   44784   u8 readOnly;          /* True if the underlying file is readonly */
   44785   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
   44786   u8 secureDelete;      /* True if secure_delete is enabled */
   44787   u8 initiallyEmpty;    /* Database is empty at start of transaction */
   44788   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
   44789 #ifndef SQLITE_OMIT_AUTOVACUUM
   44790   u8 autoVacuum;        /* True if auto-vacuum is enabled */
   44791   u8 incrVacuum;        /* True if incr-vacuum is enabled */
   44792 #endif
   44793   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   44794   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
   44795   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
   44796   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
   44797   u8 inTransaction;     /* Transaction state */
   44798   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
   44799   u32 pageSize;         /* Total number of bytes on a page */
   44800   u32 usableSize;       /* Number of usable bytes on each page */
   44801   int nTransaction;     /* Number of open transactions (read + write) */
   44802   u32 nPage;            /* Number of pages in the database */
   44803   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
   44804   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
   44805   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
   44806   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
   44807 #ifndef SQLITE_OMIT_SHARED_CACHE
   44808   int nRef;             /* Number of references to this structure */
   44809   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
   44810   BtLock *pLock;        /* List of locks held on this shared-btree struct */
   44811   Btree *pWriter;       /* Btree with currently open write transaction */
   44812   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
   44813   u8 isPending;         /* If waiting for read-locks to clear */
   44814 #endif
   44815   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
   44816 };
   44817 
   44818 /*
   44819 ** An instance of the following structure is used to hold information
   44820 ** about a cell.  The parseCellPtr() function fills in this structure
   44821 ** based on information extract from the raw disk page.
   44822 */
   44823 typedef struct CellInfo CellInfo;
   44824 struct CellInfo {
   44825   u8 *pCell;     /* Pointer to the start of cell content */
   44826   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   44827   u32 nData;     /* Number of bytes of data */
   44828   u32 nPayload;  /* Total amount of payload */
   44829   u16 nHeader;   /* Size of the cell content header in bytes */
   44830   u16 nLocal;    /* Amount of payload held locally */
   44831   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   44832   u16 nSize;     /* Size of the cell content on the main b-tree page */
   44833 };
   44834 
   44835 /*
   44836 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   44837 ** this will be declared corrupt. This value is calculated based on a
   44838 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
   44839 ** root-node and 3 for all other internal nodes.
   44840 **
   44841 ** If a tree that appears to be taller than this is encountered, it is
   44842 ** assumed that the database is corrupt.
   44843 */
   44844 #define BTCURSOR_MAX_DEPTH 20
   44845 
   44846 /*
   44847 ** A cursor is a pointer to a particular entry within a particular
   44848 ** b-tree within a database file.
   44849 **
   44850 ** The entry is identified by its MemPage and the index in
   44851 ** MemPage.aCell[] of the entry.
   44852 **
   44853 ** A single database file can shared by two more database connections,
   44854 ** but cursors cannot be shared.  Each cursor is associated with a
   44855 ** particular database connection identified BtCursor.pBtree.db.
   44856 **
   44857 ** Fields in this structure are accessed under the BtShared.mutex
   44858 ** found at self->pBt->mutex.
   44859 */
   44860 struct BtCursor {
   44861   Btree *pBtree;            /* The Btree to which this cursor belongs */
   44862   BtShared *pBt;            /* The BtShared this cursor points to */
   44863   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   44864   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   44865   Pgno pgnoRoot;            /* The root page of this tree */
   44866   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
   44867   CellInfo info;            /* A parse of the cell we are pointing at */
   44868   u8 wrFlag;                /* True if writable */
   44869   u8 atLast;                /* Cursor pointing to the last entry */
   44870   u8 validNKey;             /* True if info.nKey is valid */
   44871   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
   44872   void *pKey;      /* Saved key that was cursor's last known position */
   44873   i64 nKey;        /* Size of pKey, or last integer key */
   44874   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   44875 #ifndef SQLITE_OMIT_INCRBLOB
   44876   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
   44877   Pgno *aOverflow;          /* Cache of overflow page locations */
   44878 #endif
   44879   i16 iPage;                            /* Index of current page in apPage */
   44880   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
   44881   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
   44882 };
   44883 
   44884 /*
   44885 ** Potential values for BtCursor.eState.
   44886 **
   44887 ** CURSOR_VALID:
   44888 **   Cursor points to a valid entry. getPayload() etc. may be called.
   44889 **
   44890 ** CURSOR_INVALID:
   44891 **   Cursor does not point to a valid entry. This can happen (for example)
   44892 **   because the table is empty or because BtreeCursorFirst() has not been
   44893 **   called.
   44894 **
   44895 ** CURSOR_REQUIRESEEK:
   44896 **   The table that this cursor was opened on still exists, but has been
   44897 **   modified since the cursor was last used. The cursor position is saved
   44898 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
   44899 **   this state, restoreCursorPosition() can be called to attempt to
   44900 **   seek the cursor to the saved position.
   44901 **
   44902 ** CURSOR_FAULT:
   44903 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
   44904 **   on a different connection that shares the BtShared cache with this
   44905 **   cursor.  The error has left the cache in an inconsistent state.
   44906 **   Do nothing else with this cursor.  Any attempt to use the cursor
   44907 **   should return the error code stored in BtCursor.skip
   44908 */
   44909 #define CURSOR_INVALID           0
   44910 #define CURSOR_VALID             1
   44911 #define CURSOR_REQUIRESEEK       2
   44912 #define CURSOR_FAULT             3
   44913 
   44914 /*
   44915 ** The database page the PENDING_BYTE occupies. This page is never used.
   44916 */
   44917 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
   44918 
   44919 /*
   44920 ** These macros define the location of the pointer-map entry for a
   44921 ** database page. The first argument to each is the number of usable
   44922 ** bytes on each page of the database (often 1024). The second is the
   44923 ** page number to look up in the pointer map.
   44924 **
   44925 ** PTRMAP_PAGENO returns the database page number of the pointer-map
   44926 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
   44927 ** the offset of the requested map entry.
   44928 **
   44929 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
   44930 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
   44931 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
   44932 ** this test.
   44933 */
   44934 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
   44935 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
   44936 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
   44937 
   44938 /*
   44939 ** The pointer map is a lookup table that identifies the parent page for
   44940 ** each child page in the database file.  The parent page is the page that
   44941 ** contains a pointer to the child.  Every page in the database contains
   44942 ** 0 or 1 parent pages.  (In this context 'database page' refers
   44943 ** to any page that is not part of the pointer map itself.)  Each pointer map
   44944 ** entry consists of a single byte 'type' and a 4 byte parent page number.
   44945 ** The PTRMAP_XXX identifiers below are the valid types.
   44946 **
   44947 ** The purpose of the pointer map is to facility moving pages from one
   44948 ** position in the file to another as part of autovacuum.  When a page
   44949 ** is moved, the pointer in its parent must be updated to point to the
   44950 ** new location.  The pointer map is used to locate the parent page quickly.
   44951 **
   44952 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
   44953 **                  used in this case.
   44954 **
   44955 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
   44956 **                  is not used in this case.
   44957 **
   44958 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
   44959 **                   overflow pages. The page number identifies the page that
   44960 **                   contains the cell with a pointer to this overflow page.
   44961 **
   44962 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
   44963 **                   overflow pages. The page-number identifies the previous
   44964 **                   page in the overflow page list.
   44965 **
   44966 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
   44967 **               identifies the parent page in the btree.
   44968 */
   44969 #define PTRMAP_ROOTPAGE 1
   44970 #define PTRMAP_FREEPAGE 2
   44971 #define PTRMAP_OVERFLOW1 3
   44972 #define PTRMAP_OVERFLOW2 4
   44973 #define PTRMAP_BTREE 5
   44974 
   44975 /* A bunch of assert() statements to check the transaction state variables
   44976 ** of handle p (type Btree*) are internally consistent.
   44977 */
   44978 #define btreeIntegrity(p) \
   44979   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
   44980   assert( p->pBt->inTransaction>=p->inTrans );
   44981 
   44982 
   44983 /*
   44984 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
   44985 ** if the database supports auto-vacuum or not. Because it is used
   44986 ** within an expression that is an argument to another macro
   44987 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
   44988 ** So, this macro is defined instead.
   44989 */
   44990 #ifndef SQLITE_OMIT_AUTOVACUUM
   44991 #define ISAUTOVACUUM (pBt->autoVacuum)
   44992 #else
   44993 #define ISAUTOVACUUM 0
   44994 #endif
   44995 
   44996 
   44997 /*
   44998 ** This structure is passed around through all the sanity checking routines
   44999 ** in order to keep track of some global state information.
   45000 */
   45001 typedef struct IntegrityCk IntegrityCk;
   45002 struct IntegrityCk {
   45003   BtShared *pBt;    /* The tree being checked out */
   45004   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   45005   Pgno nPage;       /* Number of pages in the database */
   45006   int *anRef;       /* Number of times each page is referenced */
   45007   int mxErr;        /* Stop accumulating errors when this reaches zero */
   45008   int nErr;         /* Number of messages written to zErrMsg so far */
   45009   int mallocFailed; /* A memory allocation error has occurred */
   45010   StrAccum errMsg;  /* Accumulate the error message text here */
   45011 };
   45012 
   45013 /*
   45014 ** Read or write a two- and four-byte big-endian integer values.
   45015 */
   45016 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   45017 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   45018 #define get4byte sqlite3Get4byte
   45019 #define put4byte sqlite3Put4byte
   45020 
   45021 /************** End of btreeInt.h ********************************************/
   45022 /************** Continuing where we left off in btmutex.c ********************/
   45023 #ifndef SQLITE_OMIT_SHARED_CACHE
   45024 #if SQLITE_THREADSAFE
   45025 
   45026 /*
   45027 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
   45028 ** set BtShared.db to the database handle associated with p and the
   45029 ** p->locked boolean to true.
   45030 */
   45031 static void lockBtreeMutex(Btree *p){
   45032   assert( p->locked==0 );
   45033   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
   45034   assert( sqlite3_mutex_held(p->db->mutex) );
   45035 
   45036   sqlite3_mutex_enter(p->pBt->mutex);
   45037   p->pBt->db = p->db;
   45038   p->locked = 1;
   45039 }
   45040 
   45041 /*
   45042 ** Release the BtShared mutex associated with B-Tree handle p and
   45043 ** clear the p->locked boolean.
   45044 */
   45045 static void unlockBtreeMutex(Btree *p){
   45046   assert( p->locked==1 );
   45047   assert( sqlite3_mutex_held(p->pBt->mutex) );
   45048   assert( sqlite3_mutex_held(p->db->mutex) );
   45049   assert( p->db==p->pBt->db );
   45050 
   45051   sqlite3_mutex_leave(p->pBt->mutex);
   45052   p->locked = 0;
   45053 }
   45054 
   45055 /*
   45056 ** Enter a mutex on the given BTree object.
   45057 **
   45058 ** If the object is not sharable, then no mutex is ever required
   45059 ** and this routine is a no-op.  The underlying mutex is non-recursive.
   45060 ** But we keep a reference count in Btree.wantToLock so the behavior
   45061 ** of this interface is recursive.
   45062 **
   45063 ** To avoid deadlocks, multiple Btrees are locked in the same order
   45064 ** by all database connections.  The p->pNext is a list of other
   45065 ** Btrees belonging to the same database connection as the p Btree
   45066 ** which need to be locked after p.  If we cannot get a lock on
   45067 ** p, then first unlock all of the others on p->pNext, then wait
   45068 ** for the lock to become available on p, then relock all of the
   45069 ** subsequent Btrees that desire a lock.
   45070 */
   45071 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   45072   Btree *pLater;
   45073 
   45074   /* Some basic sanity checking on the Btree.  The list of Btrees
   45075   ** connected by pNext and pPrev should be in sorted order by
   45076   ** Btree.pBt value. All elements of the list should belong to
   45077   ** the same connection. Only shared Btrees are on the list. */
   45078   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
   45079   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
   45080   assert( p->pNext==0 || p->pNext->db==p->db );
   45081   assert( p->pPrev==0 || p->pPrev->db==p->db );
   45082   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
   45083 
   45084   /* Check for locking consistency */
   45085   assert( !p->locked || p->wantToLock>0 );
   45086   assert( p->sharable || p->wantToLock==0 );
   45087 
   45088   /* We should already hold a lock on the database connection */
   45089   assert( sqlite3_mutex_held(p->db->mutex) );
   45090 
   45091   /* Unless the database is sharable and unlocked, then BtShared.db
   45092   ** should already be set correctly. */
   45093   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   45094 
   45095   if( !p->sharable ) return;
   45096   p->wantToLock++;
   45097   if( p->locked ) return;
   45098 
   45099   /* In most cases, we should be able to acquire the lock we
   45100   ** want without having to go throught the ascending lock
   45101   ** procedure that follows.  Just be sure not to block.
   45102   */
   45103   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
   45104     p->pBt->db = p->db;
   45105     p->locked = 1;
   45106     return;
   45107   }
   45108 
   45109   /* To avoid deadlock, first release all locks with a larger
   45110   ** BtShared address.  Then acquire our lock.  Then reacquire
   45111   ** the other BtShared locks that we used to hold in ascending
   45112   ** order.
   45113   */
   45114   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   45115     assert( pLater->sharable );
   45116     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
   45117     assert( !pLater->locked || pLater->wantToLock>0 );
   45118     if( pLater->locked ){
   45119       unlockBtreeMutex(pLater);
   45120     }
   45121   }
   45122   lockBtreeMutex(p);
   45123   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
   45124     if( pLater->wantToLock ){
   45125       lockBtreeMutex(pLater);
   45126     }
   45127   }
   45128 }
   45129 
   45130 /*
   45131 ** Exit the recursive mutex on a Btree.
   45132 */
   45133 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
   45134   if( p->sharable ){
   45135     assert( p->wantToLock>0 );
   45136     p->wantToLock--;
   45137     if( p->wantToLock==0 ){
   45138       unlockBtreeMutex(p);
   45139     }
   45140   }
   45141 }
   45142 
   45143 #ifndef NDEBUG
   45144 /*
   45145 ** Return true if the BtShared mutex is held on the btree, or if the
   45146 ** B-Tree is not marked as sharable.
   45147 **
   45148 ** This routine is used only from within assert() statements.
   45149 */
   45150 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
   45151   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
   45152   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
   45153   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
   45154   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
   45155 
   45156   return (p->sharable==0 || p->locked);
   45157 }
   45158 #endif
   45159 
   45160 
   45161 #ifndef SQLITE_OMIT_INCRBLOB
   45162 /*
   45163 ** Enter and leave a mutex on a Btree given a cursor owned by that
   45164 ** Btree.  These entry points are used by incremental I/O and can be
   45165 ** omitted if that module is not used.
   45166 */
   45167 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
   45168   sqlite3BtreeEnter(pCur->pBtree);
   45169 }
   45170 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
   45171   sqlite3BtreeLeave(pCur->pBtree);
   45172 }
   45173 #endif /* SQLITE_OMIT_INCRBLOB */
   45174 
   45175 
   45176 /*
   45177 ** Enter the mutex on every Btree associated with a database
   45178 ** connection.  This is needed (for example) prior to parsing
   45179 ** a statement since we will be comparing table and column names
   45180 ** against all schemas and we do not want those schemas being
   45181 ** reset out from under us.
   45182 **
   45183 ** There is a corresponding leave-all procedures.
   45184 **
   45185 ** Enter the mutexes in accending order by BtShared pointer address
   45186 ** to avoid the possibility of deadlock when two threads with
   45187 ** two or more btrees in common both try to lock all their btrees
   45188 ** at the same instant.
   45189 */
   45190 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   45191   int i;
   45192   Btree *p, *pLater;
   45193   assert( sqlite3_mutex_held(db->mutex) );
   45194   for(i=0; i<db->nDb; i++){
   45195     p = db->aDb[i].pBt;
   45196     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
   45197     if( p && p->sharable ){
   45198       p->wantToLock++;
   45199       if( !p->locked ){
   45200         assert( p->wantToLock==1 );
   45201         while( p->pPrev ) p = p->pPrev;
   45202         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
   45203         ** the chain.  Otherwise the !p->locked test above would have failed */
   45204         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
   45205         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
   45206           if( pLater->locked ){
   45207             unlockBtreeMutex(pLater);
   45208           }
   45209         }
   45210         while( p ){
   45211           lockBtreeMutex(p);
   45212           p = p->pNext;
   45213         }
   45214       }
   45215     }
   45216   }
   45217 }
   45218 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
   45219   int i;
   45220   Btree *p;
   45221   assert( sqlite3_mutex_held(db->mutex) );
   45222   for(i=0; i<db->nDb; i++){
   45223     p = db->aDb[i].pBt;
   45224     if( p && p->sharable ){
   45225       assert( p->wantToLock>0 );
   45226       p->wantToLock--;
   45227       if( p->wantToLock==0 ){
   45228         unlockBtreeMutex(p);
   45229       }
   45230     }
   45231   }
   45232 }
   45233 
   45234 #ifndef NDEBUG
   45235 /*
   45236 ** Return true if the current thread holds the database connection
   45237 ** mutex and all required BtShared mutexes.
   45238 **
   45239 ** This routine is used inside assert() statements only.
   45240 */
   45241 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
   45242   int i;
   45243   if( !sqlite3_mutex_held(db->mutex) ){
   45244     return 0;
   45245   }
   45246   for(i=0; i<db->nDb; i++){
   45247     Btree *p;
   45248     p = db->aDb[i].pBt;
   45249     if( p && p->sharable &&
   45250          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
   45251       return 0;
   45252     }
   45253   }
   45254   return 1;
   45255 }
   45256 #endif /* NDEBUG */
   45257 
   45258 /*
   45259 ** Add a new Btree pointer to a BtreeMutexArray.
   45260 ** if the pointer can possibly be shared with
   45261 ** another database connection.
   45262 **
   45263 ** The pointers are kept in sorted order by pBtree->pBt.  That
   45264 ** way when we go to enter all the mutexes, we can enter them
   45265 ** in order without every having to backup and retry and without
   45266 ** worrying about deadlock.
   45267 **
   45268 ** The number of shared btrees will always be small (usually 0 or 1)
   45269 ** so an insertion sort is an adequate algorithm here.
   45270 */
   45271 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
   45272   int i, j;
   45273   BtShared *pBt;
   45274   if( pBtree==0 || pBtree->sharable==0 ) return;
   45275 #ifndef NDEBUG
   45276   {
   45277     for(i=0; i<pArray->nMutex; i++){
   45278       assert( pArray->aBtree[i]!=pBtree );
   45279     }
   45280   }
   45281 #endif
   45282   assert( pArray->nMutex>=0 );
   45283   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
   45284   pBt = pBtree->pBt;
   45285   for(i=0; i<pArray->nMutex; i++){
   45286     assert( pArray->aBtree[i]!=pBtree );
   45287     if( pArray->aBtree[i]->pBt>pBt ){
   45288       for(j=pArray->nMutex; j>i; j--){
   45289         pArray->aBtree[j] = pArray->aBtree[j-1];
   45290       }
   45291       pArray->aBtree[i] = pBtree;
   45292       pArray->nMutex++;
   45293       return;
   45294     }
   45295   }
   45296   pArray->aBtree[pArray->nMutex++] = pBtree;
   45297 }
   45298 
   45299 /*
   45300 ** Enter the mutex of every btree in the array.  This routine is
   45301 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
   45302 ** exited at the end of the same function.
   45303 */
   45304 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
   45305   int i;
   45306   for(i=0; i<pArray->nMutex; i++){
   45307     Btree *p = pArray->aBtree[i];
   45308     /* Some basic sanity checking */
   45309     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
   45310     assert( !p->locked || p->wantToLock>0 );
   45311 
   45312     /* We should already hold a lock on the database connection */
   45313     assert( sqlite3_mutex_held(p->db->mutex) );
   45314 
   45315     /* The Btree is sharable because only sharable Btrees are entered
   45316     ** into the array in the first place. */
   45317     assert( p->sharable );
   45318 
   45319     p->wantToLock++;
   45320     if( !p->locked ){
   45321       lockBtreeMutex(p);
   45322     }
   45323   }
   45324 }
   45325 
   45326 /*
   45327 ** Leave the mutex of every btree in the group.
   45328 */
   45329 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
   45330   int i;
   45331   for(i=0; i<pArray->nMutex; i++){
   45332     Btree *p = pArray->aBtree[i];
   45333     /* Some basic sanity checking */
   45334     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
   45335     assert( p->locked );
   45336     assert( p->wantToLock>0 );
   45337 
   45338     /* We should already hold a lock on the database connection */
   45339     assert( sqlite3_mutex_held(p->db->mutex) );
   45340 
   45341     p->wantToLock--;
   45342     if( p->wantToLock==0 ){
   45343       unlockBtreeMutex(p);
   45344     }
   45345   }
   45346 }
   45347 
   45348 #else
   45349 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
   45350   p->pBt->db = p->db;
   45351 }
   45352 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
   45353   int i;
   45354   for(i=0; i<db->nDb; i++){
   45355     Btree *p = db->aDb[i].pBt;
   45356     if( p ){
   45357       p->pBt->db = p->db;
   45358     }
   45359   }
   45360 }
   45361 #endif /* if SQLITE_THREADSAFE */
   45362 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
   45363 
   45364 /************** End of btmutex.c *********************************************/
   45365 /************** Begin file btree.c *******************************************/
   45366 /*
   45367 ** 2004 April 6
   45368 **
   45369 ** The author disclaims copyright to this source code.  In place of
   45370 ** a legal notice, here is a blessing:
   45371 **
   45372 **    May you do good and not evil.
   45373 **    May you find forgiveness for yourself and forgive others.
   45374 **    May you share freely, never taking more than you give.
   45375 **
   45376 *************************************************************************
   45377 ** This file implements a external (disk-based) database using BTrees.
   45378 ** See the header comment on "btreeInt.h" for additional information.
   45379 ** Including a description of file format and an overview of operation.
   45380 */
   45381 
   45382 /*
   45383 ** The header string that appears at the beginning of every
   45384 ** SQLite database.
   45385 */
   45386 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
   45387 
   45388 /*
   45389 ** Set this global variable to 1 to enable tracing using the TRACE
   45390 ** macro.
   45391 */
   45392 #if 0
   45393 int sqlite3BtreeTrace=1;  /* True to enable tracing */
   45394 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
   45395 #else
   45396 # define TRACE(X)
   45397 #endif
   45398 
   45399 /*
   45400 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
   45401 ** But if the value is zero, make it 65536.
   45402 **
   45403 ** This routine is used to extract the "offset to cell content area" value
   45404 ** from the header of a btree page.  If the page size is 65536 and the page
   45405 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
   45406 ** This routine makes the necessary adjustment to 65536.
   45407 */
   45408 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
   45409 
   45410 #ifndef SQLITE_OMIT_SHARED_CACHE
   45411 /*
   45412 ** A list of BtShared objects that are eligible for participation
   45413 ** in shared cache.  This variable has file scope during normal builds,
   45414 ** but the test harness needs to access it so we make it global for
   45415 ** test builds.
   45416 **
   45417 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
   45418 */
   45419 #ifdef SQLITE_TEST
   45420 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   45421 #else
   45422 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
   45423 #endif
   45424 #endif /* SQLITE_OMIT_SHARED_CACHE */
   45425 
   45426 #ifndef SQLITE_OMIT_SHARED_CACHE
   45427 /*
   45428 ** Enable or disable the shared pager and schema features.
   45429 **
   45430 ** This routine has no effect on existing database connections.
   45431 ** The shared cache setting effects only future calls to
   45432 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
   45433 */
   45434 SQLITE_API int sqlite3_enable_shared_cache(int enable){
   45435   sqlite3GlobalConfig.sharedCacheEnabled = enable;
   45436   return SQLITE_OK;
   45437 }
   45438 #endif
   45439 
   45440 
   45441 
   45442 #ifdef SQLITE_OMIT_SHARED_CACHE
   45443   /*
   45444   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
   45445   ** and clearAllSharedCacheTableLocks()
   45446   ** manipulate entries in the BtShared.pLock linked list used to store
   45447   ** shared-cache table level locks. If the library is compiled with the
   45448   ** shared-cache feature disabled, then there is only ever one user
   45449   ** of each BtShared structure and so this locking is not necessary.
   45450   ** So define the lock related functions as no-ops.
   45451   */
   45452   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
   45453   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
   45454   #define clearAllSharedCacheTableLocks(a)
   45455   #define downgradeAllSharedCacheTableLocks(a)
   45456   #define hasSharedCacheTableLock(a,b,c,d) 1
   45457   #define hasReadConflicts(a, b) 0
   45458 #endif
   45459 
   45460 #ifndef SQLITE_OMIT_SHARED_CACHE
   45461 
   45462 #ifdef SQLITE_DEBUG
   45463 /*
   45464 **** This function is only used as part of an assert() statement. ***
   45465 **
   45466 ** Check to see if pBtree holds the required locks to read or write to the
   45467 ** table with root page iRoot.   Return 1 if it does and 0 if not.
   45468 **
   45469 ** For example, when writing to a table with root-page iRoot via
   45470 ** Btree connection pBtree:
   45471 **
   45472 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
   45473 **
   45474 ** When writing to an index that resides in a sharable database, the
   45475 ** caller should have first obtained a lock specifying the root page of
   45476 ** the corresponding table. This makes things a bit more complicated,
   45477 ** as this module treats each table as a separate structure. To determine
   45478 ** the table corresponding to the index being written, this
   45479 ** function has to search through the database schema.
   45480 **
   45481 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
   45482 ** hold a write-lock on the schema table (root page 1). This is also
   45483 ** acceptable.
   45484 */
   45485 static int hasSharedCacheTableLock(
   45486   Btree *pBtree,         /* Handle that must hold lock */
   45487   Pgno iRoot,            /* Root page of b-tree */
   45488   int isIndex,           /* True if iRoot is the root of an index b-tree */
   45489   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
   45490 ){
   45491   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
   45492   Pgno iTab = 0;
   45493   BtLock *pLock;
   45494 
   45495   /* If this database is not shareable, or if the client is reading
   45496   ** and has the read-uncommitted flag set, then no lock is required.
   45497   ** Return true immediately.
   45498   */
   45499   if( (pBtree->sharable==0)
   45500    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
   45501   ){
   45502     return 1;
   45503   }
   45504 
   45505   /* If the client is reading  or writing an index and the schema is
   45506   ** not loaded, then it is too difficult to actually check to see if
   45507   ** the correct locks are held.  So do not bother - just return true.
   45508   ** This case does not come up very often anyhow.
   45509   */
   45510   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
   45511     return 1;
   45512   }
   45513 
   45514   /* Figure out the root-page that the lock should be held on. For table
   45515   ** b-trees, this is just the root page of the b-tree being read or
   45516   ** written. For index b-trees, it is the root page of the associated
   45517   ** table.  */
   45518   if( isIndex ){
   45519     HashElem *p;
   45520     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
   45521       Index *pIdx = (Index *)sqliteHashData(p);
   45522       if( pIdx->tnum==(int)iRoot ){
   45523         iTab = pIdx->pTable->tnum;
   45524       }
   45525     }
   45526   }else{
   45527     iTab = iRoot;
   45528   }
   45529 
   45530   /* Search for the required lock. Either a write-lock on root-page iTab, a
   45531   ** write-lock on the schema table, or (if the client is reading) a
   45532   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   45533   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
   45534     if( pLock->pBtree==pBtree
   45535      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
   45536      && pLock->eLock>=eLockType
   45537     ){
   45538       return 1;
   45539     }
   45540   }
   45541 
   45542   /* Failed to find the required lock. */
   45543   return 0;
   45544 }
   45545 #endif /* SQLITE_DEBUG */
   45546 
   45547 #ifdef SQLITE_DEBUG
   45548 /*
   45549 **** This function may be used as part of assert() statements only. ****
   45550 **
   45551 ** Return true if it would be illegal for pBtree to write into the
   45552 ** table or index rooted at iRoot because other shared connections are
   45553 ** simultaneously reading that same table or index.
   45554 **
   45555 ** It is illegal for pBtree to write if some other Btree object that
   45556 ** shares the same BtShared object is currently reading or writing
   45557 ** the iRoot table.  Except, if the other Btree object has the
   45558 ** read-uncommitted flag set, then it is OK for the other object to
   45559 ** have a read cursor.
   45560 **
   45561 ** For example, before writing to any part of the table or index
   45562 ** rooted at page iRoot, one should call:
   45563 **
   45564 **    assert( !hasReadConflicts(pBtree, iRoot) );
   45565 */
   45566 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   45567   BtCursor *p;
   45568   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   45569     if( p->pgnoRoot==iRoot
   45570      && p->pBtree!=pBtree
   45571      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
   45572     ){
   45573       return 1;
   45574     }
   45575   }
   45576   return 0;
   45577 }
   45578 #endif    /* #ifdef SQLITE_DEBUG */
   45579 
   45580 /*
   45581 ** Query to see if Btree handle p may obtain a lock of type eLock
   45582 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
   45583 ** SQLITE_OK if the lock may be obtained (by calling
   45584 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
   45585 */
   45586 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   45587   BtShared *pBt = p->pBt;
   45588   BtLock *pIter;
   45589 
   45590   assert( sqlite3BtreeHoldsMutex(p) );
   45591   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   45592   assert( p->db!=0 );
   45593   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
   45594 
   45595   /* If requesting a write-lock, then the Btree must have an open write
   45596   ** transaction on this file. And, obviously, for this to be so there
   45597   ** must be an open write transaction on the file itself.
   45598   */
   45599   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   45600   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
   45601 
   45602   /* This routine is a no-op if the shared-cache is not enabled */
   45603   if( !p->sharable ){
   45604     return SQLITE_OK;
   45605   }
   45606 
   45607   /* If some other connection is holding an exclusive lock, the
   45608   ** requested lock may not be obtained.
   45609   */
   45610   if( pBt->pWriter!=p && pBt->isExclusive ){
   45611     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
   45612     return SQLITE_LOCKED_SHAREDCACHE;
   45613   }
   45614 
   45615   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   45616     /* The condition (pIter->eLock!=eLock) in the following if(...)
   45617     ** statement is a simplification of:
   45618     **
   45619     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
   45620     **
   45621     ** since we know that if eLock==WRITE_LOCK, then no other connection
   45622     ** may hold a WRITE_LOCK on any table in this file (since there can
   45623     ** only be a single writer).
   45624     */
   45625     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
   45626     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
   45627     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
   45628       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
   45629       if( eLock==WRITE_LOCK ){
   45630         assert( p==pBt->pWriter );
   45631         pBt->isPending = 1;
   45632       }
   45633       return SQLITE_LOCKED_SHAREDCACHE;
   45634     }
   45635   }
   45636   return SQLITE_OK;
   45637 }
   45638 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   45639 
   45640 #ifndef SQLITE_OMIT_SHARED_CACHE
   45641 /*
   45642 ** Add a lock on the table with root-page iTable to the shared-btree used
   45643 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
   45644 ** WRITE_LOCK.
   45645 **
   45646 ** This function assumes the following:
   45647 **
   45648 **   (a) The specified Btree object p is connected to a sharable
   45649 **       database (one with the BtShared.sharable flag set), and
   45650 **
   45651 **   (b) No other Btree objects hold a lock that conflicts
   45652 **       with the requested lock (i.e. querySharedCacheTableLock() has
   45653 **       already been called and returned SQLITE_OK).
   45654 **
   45655 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
   45656 ** is returned if a malloc attempt fails.
   45657 */
   45658 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
   45659   BtShared *pBt = p->pBt;
   45660   BtLock *pLock = 0;
   45661   BtLock *pIter;
   45662 
   45663   assert( sqlite3BtreeHoldsMutex(p) );
   45664   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   45665   assert( p->db!=0 );
   45666 
   45667   /* A connection with the read-uncommitted flag set will never try to
   45668   ** obtain a read-lock using this function. The only read-lock obtained
   45669   ** by a connection in read-uncommitted mode is on the sqlite_master
   45670   ** table, and that lock is obtained in BtreeBeginTrans().  */
   45671   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
   45672 
   45673   /* This function should only be called on a sharable b-tree after it
   45674   ** has been determined that no other b-tree holds a conflicting lock.  */
   45675   assert( p->sharable );
   45676   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
   45677 
   45678   /* First search the list for an existing lock on this table. */
   45679   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   45680     if( pIter->iTable==iTable && pIter->pBtree==p ){
   45681       pLock = pIter;
   45682       break;
   45683     }
   45684   }
   45685 
   45686   /* If the above search did not find a BtLock struct associating Btree p
   45687   ** with table iTable, allocate one and link it into the list.
   45688   */
   45689   if( !pLock ){
   45690     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
   45691     if( !pLock ){
   45692       return SQLITE_NOMEM;
   45693     }
   45694     pLock->iTable = iTable;
   45695     pLock->pBtree = p;
   45696     pLock->pNext = pBt->pLock;
   45697     pBt->pLock = pLock;
   45698   }
   45699 
   45700   /* Set the BtLock.eLock variable to the maximum of the current lock
   45701   ** and the requested lock. This means if a write-lock was already held
   45702   ** and a read-lock requested, we don't incorrectly downgrade the lock.
   45703   */
   45704   assert( WRITE_LOCK>READ_LOCK );
   45705   if( eLock>pLock->eLock ){
   45706     pLock->eLock = eLock;
   45707   }
   45708 
   45709   return SQLITE_OK;
   45710 }
   45711 #endif /* !SQLITE_OMIT_SHARED_CACHE */
   45712 
   45713 #ifndef SQLITE_OMIT_SHARED_CACHE
   45714 /*
   45715 ** Release all the table locks (locks obtained via calls to
   45716 ** the setSharedCacheTableLock() procedure) held by Btree object p.
   45717 **
   45718 ** This function assumes that Btree p has an open read or write
   45719 ** transaction. If it does not, then the BtShared.isPending variable
   45720 ** may be incorrectly cleared.
   45721 */
   45722 static void clearAllSharedCacheTableLocks(Btree *p){
   45723   BtShared *pBt = p->pBt;
   45724   BtLock **ppIter = &pBt->pLock;
   45725 
   45726   assert( sqlite3BtreeHoldsMutex(p) );
   45727   assert( p->sharable || 0==*ppIter );
   45728   assert( p->inTrans>0 );
   45729 
   45730   while( *ppIter ){
   45731     BtLock *pLock = *ppIter;
   45732     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
   45733     assert( pLock->pBtree->inTrans>=pLock->eLock );
   45734     if( pLock->pBtree==p ){
   45735       *ppIter = pLock->pNext;
   45736       assert( pLock->iTable!=1 || pLock==&p->lock );
   45737       if( pLock->iTable!=1 ){
   45738         sqlite3_free(pLock);
   45739       }
   45740     }else{
   45741       ppIter = &pLock->pNext;
   45742     }
   45743   }
   45744 
   45745   assert( pBt->isPending==0 || pBt->pWriter );
   45746   if( pBt->pWriter==p ){
   45747     pBt->pWriter = 0;
   45748     pBt->isExclusive = 0;
   45749     pBt->isPending = 0;
   45750   }else if( pBt->nTransaction==2 ){
   45751     /* This function is called when Btree p is concluding its
   45752     ** transaction. If there currently exists a writer, and p is not
   45753     ** that writer, then the number of locks held by connections other
   45754     ** than the writer must be about to drop to zero. In this case
   45755     ** set the isPending flag to 0.
   45756     **
   45757     ** If there is not currently a writer, then BtShared.isPending must
   45758     ** be zero already. So this next line is harmless in that case.
   45759     */
   45760     pBt->isPending = 0;
   45761   }
   45762 }
   45763 
   45764 /*
   45765 ** This function changes all write-locks held by Btree p into read-locks.
   45766 */
   45767 static void downgradeAllSharedCacheTableLocks(Btree *p){
   45768   BtShared *pBt = p->pBt;
   45769   if( pBt->pWriter==p ){
   45770     BtLock *pLock;
   45771     pBt->pWriter = 0;
   45772     pBt->isExclusive = 0;
   45773     pBt->isPending = 0;
   45774     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
   45775       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
   45776       pLock->eLock = READ_LOCK;
   45777     }
   45778   }
   45779 }
   45780 
   45781 #endif /* SQLITE_OMIT_SHARED_CACHE */
   45782 
   45783 static void releasePage(MemPage *pPage);  /* Forward reference */
   45784 
   45785 /*
   45786 ***** This routine is used inside of assert() only ****
   45787 **
   45788 ** Verify that the cursor holds the mutex on its BtShared
   45789 */
   45790 #ifdef SQLITE_DEBUG
   45791 static int cursorHoldsMutex(BtCursor *p){
   45792   return sqlite3_mutex_held(p->pBt->mutex);
   45793 }
   45794 #endif
   45795 
   45796 
   45797 #ifndef SQLITE_OMIT_INCRBLOB
   45798 /*
   45799 ** Invalidate the overflow page-list cache for cursor pCur, if any.
   45800 */
   45801 static void invalidateOverflowCache(BtCursor *pCur){
   45802   assert( cursorHoldsMutex(pCur) );
   45803   sqlite3_free(pCur->aOverflow);
   45804   pCur->aOverflow = 0;
   45805 }
   45806 
   45807 /*
   45808 ** Invalidate the overflow page-list cache for all cursors opened
   45809 ** on the shared btree structure pBt.
   45810 */
   45811 static void invalidateAllOverflowCache(BtShared *pBt){
   45812   BtCursor *p;
   45813   assert( sqlite3_mutex_held(pBt->mutex) );
   45814   for(p=pBt->pCursor; p; p=p->pNext){
   45815     invalidateOverflowCache(p);
   45816   }
   45817 }
   45818 
   45819 /*
   45820 ** This function is called before modifying the contents of a table
   45821 ** to invalidate any incrblob cursors that are open on the
   45822 ** row or one of the rows being modified.
   45823 **
   45824 ** If argument isClearTable is true, then the entire contents of the
   45825 ** table is about to be deleted. In this case invalidate all incrblob
   45826 ** cursors open on any row within the table with root-page pgnoRoot.
   45827 **
   45828 ** Otherwise, if argument isClearTable is false, then the row with
   45829 ** rowid iRow is being replaced or deleted. In this case invalidate
   45830 ** only those incrblob cursors open on that specific row.
   45831 */
   45832 static void invalidateIncrblobCursors(
   45833   Btree *pBtree,          /* The database file to check */
   45834   i64 iRow,               /* The rowid that might be changing */
   45835   int isClearTable        /* True if all rows are being deleted */
   45836 ){
   45837   BtCursor *p;
   45838   BtShared *pBt = pBtree->pBt;
   45839   assert( sqlite3BtreeHoldsMutex(pBtree) );
   45840   for(p=pBt->pCursor; p; p=p->pNext){
   45841     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
   45842       p->eState = CURSOR_INVALID;
   45843     }
   45844   }
   45845 }
   45846 
   45847 #else
   45848   /* Stub functions when INCRBLOB is omitted */
   45849   #define invalidateOverflowCache(x)
   45850   #define invalidateAllOverflowCache(x)
   45851   #define invalidateIncrblobCursors(x,y,z)
   45852 #endif /* SQLITE_OMIT_INCRBLOB */
   45853 
   45854 /*
   45855 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
   45856 ** when a page that previously contained data becomes a free-list leaf
   45857 ** page.
   45858 **
   45859 ** The BtShared.pHasContent bitvec exists to work around an obscure
   45860 ** bug caused by the interaction of two useful IO optimizations surrounding
   45861 ** free-list leaf pages:
   45862 **
   45863 **   1) When all data is deleted from a page and the page becomes
   45864 **      a free-list leaf page, the page is not written to the database
   45865 **      (as free-list leaf pages contain no meaningful data). Sometimes
   45866 **      such a page is not even journalled (as it will not be modified,
   45867 **      why bother journalling it?).
   45868 **
   45869 **   2) When a free-list leaf page is reused, its content is not read
   45870 **      from the database or written to the journal file (why should it
   45871 **      be, if it is not at all meaningful?).
   45872 **
   45873 ** By themselves, these optimizations work fine and provide a handy
   45874 ** performance boost to bulk delete or insert operations. However, if
   45875 ** a page is moved to the free-list and then reused within the same
   45876 ** transaction, a problem comes up. If the page is not journalled when
   45877 ** it is moved to the free-list and it is also not journalled when it
   45878 ** is extracted from the free-list and reused, then the original data
   45879 ** may be lost. In the event of a rollback, it may not be possible
   45880 ** to restore the database to its original configuration.
   45881 **
   45882 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
   45883 ** moved to become a free-list leaf page, the corresponding bit is
   45884 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
   45885 ** optimization 2 above is omitted if the corresponding bit is already
   45886 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
   45887 ** at the end of every transaction.
   45888 */
   45889 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
   45890   int rc = SQLITE_OK;
   45891   if( !pBt->pHasContent ){
   45892     assert( pgno<=pBt->nPage );
   45893     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
   45894     if( !pBt->pHasContent ){
   45895       rc = SQLITE_NOMEM;
   45896     }
   45897   }
   45898   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
   45899     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
   45900   }
   45901   return rc;
   45902 }
   45903 
   45904 /*
   45905 ** Query the BtShared.pHasContent vector.
   45906 **
   45907 ** This function is called when a free-list leaf page is removed from the
   45908 ** free-list for reuse. It returns false if it is safe to retrieve the
   45909 ** page from the pager layer with the 'no-content' flag set. True otherwise.
   45910 */
   45911 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   45912   Bitvec *p = pBt->pHasContent;
   45913   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
   45914 }
   45915 
   45916 /*
   45917 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
   45918 ** invoked at the conclusion of each write-transaction.
   45919 */
   45920 static void btreeClearHasContent(BtShared *pBt){
   45921   sqlite3BitvecDestroy(pBt->pHasContent);
   45922   pBt->pHasContent = 0;
   45923 }
   45924 
   45925 /*
   45926 ** Save the current cursor position in the variables BtCursor.nKey
   45927 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
   45928 **
   45929 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
   45930 ** prior to calling this routine.
   45931 */
   45932 static int saveCursorPosition(BtCursor *pCur){
   45933   int rc;
   45934 
   45935   assert( CURSOR_VALID==pCur->eState );
   45936   assert( 0==pCur->pKey );
   45937   assert( cursorHoldsMutex(pCur) );
   45938 
   45939   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
   45940   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
   45941 
   45942   /* If this is an intKey table, then the above call to BtreeKeySize()
   45943   ** stores the integer key in pCur->nKey. In this case this value is
   45944   ** all that is required. Otherwise, if pCur is not open on an intKey
   45945   ** table, then malloc space for and store the pCur->nKey bytes of key
   45946   ** data.
   45947   */
   45948   if( 0==pCur->apPage[0]->intKey ){
   45949     void *pKey = sqlite3Malloc( (int)pCur->nKey );
   45950     if( pKey ){
   45951       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
   45952       if( rc==SQLITE_OK ){
   45953         pCur->pKey = pKey;
   45954       }else{
   45955         sqlite3_free(pKey);
   45956       }
   45957     }else{
   45958       rc = SQLITE_NOMEM;
   45959     }
   45960   }
   45961   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
   45962 
   45963   if( rc==SQLITE_OK ){
   45964     int i;
   45965     for(i=0; i<=pCur->iPage; i++){
   45966       releasePage(pCur->apPage[i]);
   45967       pCur->apPage[i] = 0;
   45968     }
   45969     pCur->iPage = -1;
   45970     pCur->eState = CURSOR_REQUIRESEEK;
   45971   }
   45972 
   45973   invalidateOverflowCache(pCur);
   45974   return rc;
   45975 }
   45976 
   45977 /*
   45978 ** Save the positions of all cursors (except pExcept) that are open on
   45979 ** the table  with root-page iRoot. Usually, this is called just before cursor
   45980 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
   45981 */
   45982 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
   45983   BtCursor *p;
   45984   assert( sqlite3_mutex_held(pBt->mutex) );
   45985   assert( pExcept==0 || pExcept->pBt==pBt );
   45986   for(p=pBt->pCursor; p; p=p->pNext){
   45987     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
   45988         p->eState==CURSOR_VALID ){
   45989       int rc = saveCursorPosition(p);
   45990       if( SQLITE_OK!=rc ){
   45991         return rc;
   45992       }
   45993     }
   45994   }
   45995   return SQLITE_OK;
   45996 }
   45997 
   45998 /*
   45999 ** Clear the current cursor position.
   46000 */
   46001 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
   46002   assert( cursorHoldsMutex(pCur) );
   46003   sqlite3_free(pCur->pKey);
   46004   pCur->pKey = 0;
   46005   pCur->eState = CURSOR_INVALID;
   46006 }
   46007 
   46008 /*
   46009 ** In this version of BtreeMoveto, pKey is a packed index record
   46010 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
   46011 ** record and then call BtreeMovetoUnpacked() to do the work.
   46012 */
   46013 static int btreeMoveto(
   46014   BtCursor *pCur,     /* Cursor open on the btree to be searched */
   46015   const void *pKey,   /* Packed key if the btree is an index */
   46016   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
   46017   int bias,           /* Bias search to the high end */
   46018   int *pRes           /* Write search results here */
   46019 ){
   46020   int rc;                    /* Status code */
   46021   UnpackedRecord *pIdxKey;   /* Unpacked index key */
   46022   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
   46023 
   46024   if( pKey ){
   46025     assert( nKey==(i64)(int)nKey );
   46026     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
   46027                                       aSpace, sizeof(aSpace));
   46028     if( pIdxKey==0 ) return SQLITE_NOMEM;
   46029   }else{
   46030     pIdxKey = 0;
   46031   }
   46032   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
   46033   if( pKey ){
   46034     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
   46035   }
   46036   return rc;
   46037 }
   46038 
   46039 /*
   46040 ** Restore the cursor to the position it was in (or as close to as possible)
   46041 ** when saveCursorPosition() was called. Note that this call deletes the
   46042 ** saved position info stored by saveCursorPosition(), so there can be
   46043 ** at most one effective restoreCursorPosition() call after each
   46044 ** saveCursorPosition().
   46045 */
   46046 static int btreeRestoreCursorPosition(BtCursor *pCur){
   46047   int rc;
   46048   assert( cursorHoldsMutex(pCur) );
   46049   assert( pCur->eState>=CURSOR_REQUIRESEEK );
   46050   if( pCur->eState==CURSOR_FAULT ){
   46051     return pCur->skipNext;
   46052   }
   46053   pCur->eState = CURSOR_INVALID;
   46054   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
   46055   if( rc==SQLITE_OK ){
   46056     sqlite3_free(pCur->pKey);
   46057     pCur->pKey = 0;
   46058     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
   46059   }
   46060   return rc;
   46061 }
   46062 
   46063 #define restoreCursorPosition(p) \
   46064   (p->eState>=CURSOR_REQUIRESEEK ? \
   46065          btreeRestoreCursorPosition(p) : \
   46066          SQLITE_OK)
   46067 
   46068 /*
   46069 ** Determine whether or not a cursor has moved from the position it
   46070 ** was last placed at.  Cursors can move when the row they are pointing
   46071 ** at is deleted out from under them.
   46072 **
   46073 ** This routine returns an error code if something goes wrong.  The
   46074 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
   46075 */
   46076 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
   46077   int rc;
   46078 
   46079   rc = restoreCursorPosition(pCur);
   46080   if( rc ){
   46081     *pHasMoved = 1;
   46082     return rc;
   46083   }
   46084   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
   46085     *pHasMoved = 1;
   46086   }else{
   46087     *pHasMoved = 0;
   46088   }
   46089   return SQLITE_OK;
   46090 }
   46091 
   46092 #ifndef SQLITE_OMIT_AUTOVACUUM
   46093 /*
   46094 ** Given a page number of a regular database page, return the page
   46095 ** number for the pointer-map page that contains the entry for the
   46096 ** input page number.
   46097 **
   46098 ** Return 0 (not a valid page) for pgno==1 since there is
   46099 ** no pointer map associated with page 1.  The integrity_check logic
   46100 ** requires that ptrmapPageno(*,1)!=1.
   46101 */
   46102 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   46103   int nPagesPerMapPage;
   46104   Pgno iPtrMap, ret;
   46105   assert( sqlite3_mutex_held(pBt->mutex) );
   46106   if( pgno<2 ) return 0;
   46107   nPagesPerMapPage = (pBt->usableSize/5)+1;
   46108   iPtrMap = (pgno-2)/nPagesPerMapPage;
   46109   ret = (iPtrMap*nPagesPerMapPage) + 2;
   46110   if( ret==PENDING_BYTE_PAGE(pBt) ){
   46111     ret++;
   46112   }
   46113   return ret;
   46114 }
   46115 
   46116 /*
   46117 ** Write an entry into the pointer map.
   46118 **
   46119 ** This routine updates the pointer map entry for page number 'key'
   46120 ** so that it maps to type 'eType' and parent page number 'pgno'.
   46121 **
   46122 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
   46123 ** a no-op.  If an error occurs, the appropriate error code is written
   46124 ** into *pRC.
   46125 */
   46126 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   46127   DbPage *pDbPage;  /* The pointer map page */
   46128   u8 *pPtrmap;      /* The pointer map data */
   46129   Pgno iPtrmap;     /* The pointer map page number */
   46130   int offset;       /* Offset in pointer map page */
   46131   int rc;           /* Return code from subfunctions */
   46132 
   46133   if( *pRC ) return;
   46134 
   46135   assert( sqlite3_mutex_held(pBt->mutex) );
   46136   /* The master-journal page number must never be used as a pointer map page */
   46137   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
   46138 
   46139   assert( pBt->autoVacuum );
   46140   if( key==0 ){
   46141     *pRC = SQLITE_CORRUPT_BKPT;
   46142     return;
   46143   }
   46144   iPtrmap = PTRMAP_PAGENO(pBt, key);
   46145   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   46146   if( rc!=SQLITE_OK ){
   46147     *pRC = rc;
   46148     return;
   46149   }
   46150   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   46151   if( offset<0 ){
   46152     *pRC = SQLITE_CORRUPT_BKPT;
   46153     goto ptrmap_exit;
   46154   }
   46155   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   46156 
   46157   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
   46158     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
   46159     *pRC= rc = sqlite3PagerWrite(pDbPage);
   46160     if( rc==SQLITE_OK ){
   46161       pPtrmap[offset] = eType;
   46162       put4byte(&pPtrmap[offset+1], parent);
   46163     }
   46164   }
   46165 
   46166 ptrmap_exit:
   46167   sqlite3PagerUnref(pDbPage);
   46168 }
   46169 
   46170 /*
   46171 ** Read an entry from the pointer map.
   46172 **
   46173 ** This routine retrieves the pointer map entry for page 'key', writing
   46174 ** the type and parent page number to *pEType and *pPgno respectively.
   46175 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
   46176 */
   46177 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
   46178   DbPage *pDbPage;   /* The pointer map page */
   46179   int iPtrmap;       /* Pointer map page index */
   46180   u8 *pPtrmap;       /* Pointer map page data */
   46181   int offset;        /* Offset of entry in pointer map */
   46182   int rc;
   46183 
   46184   assert( sqlite3_mutex_held(pBt->mutex) );
   46185 
   46186   iPtrmap = PTRMAP_PAGENO(pBt, key);
   46187   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
   46188   if( rc!=0 ){
   46189     return rc;
   46190   }
   46191   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
   46192 
   46193   offset = PTRMAP_PTROFFSET(iPtrmap, key);
   46194   assert( pEType!=0 );
   46195   *pEType = pPtrmap[offset];
   46196   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
   46197 
   46198   sqlite3PagerUnref(pDbPage);
   46199   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
   46200   return SQLITE_OK;
   46201 }
   46202 
   46203 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
   46204   #define ptrmapPut(w,x,y,z,rc)
   46205   #define ptrmapGet(w,x,y,z) SQLITE_OK
   46206   #define ptrmapPutOvflPtr(x, y, rc)
   46207 #endif
   46208 
   46209 /*
   46210 ** Given a btree page and a cell index (0 means the first cell on
   46211 ** the page, 1 means the second cell, and so forth) return a pointer
   46212 ** to the cell content.
   46213 **
   46214 ** This routine works only for pages that do not contain overflow cells.
   46215 */
   46216 #define findCell(P,I) \
   46217   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
   46218 
   46219 /*
   46220 ** This a more complex version of findCell() that works for
   46221 ** pages that do contain overflow cells.
   46222 */
   46223 static u8 *findOverflowCell(MemPage *pPage, int iCell){
   46224   int i;
   46225   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46226   for(i=pPage->nOverflow-1; i>=0; i--){
   46227     int k;
   46228     struct _OvflCell *pOvfl;
   46229     pOvfl = &pPage->aOvfl[i];
   46230     k = pOvfl->idx;
   46231     if( k<=iCell ){
   46232       if( k==iCell ){
   46233         return pOvfl->pCell;
   46234       }
   46235       iCell--;
   46236     }
   46237   }
   46238   return findCell(pPage, iCell);
   46239 }
   46240 
   46241 /*
   46242 ** Parse a cell content block and fill in the CellInfo structure.  There
   46243 ** are two versions of this function.  btreeParseCell() takes a
   46244 ** cell index as the second argument and btreeParseCellPtr()
   46245 ** takes a pointer to the body of the cell as its second argument.
   46246 **
   46247 ** Within this file, the parseCell() macro can be called instead of
   46248 ** btreeParseCellPtr(). Using some compilers, this will be faster.
   46249 */
   46250 static void btreeParseCellPtr(
   46251   MemPage *pPage,         /* Page containing the cell */
   46252   u8 *pCell,              /* Pointer to the cell text. */
   46253   CellInfo *pInfo         /* Fill in this structure */
   46254 ){
   46255   u16 n;                  /* Number bytes in cell content header */
   46256   u32 nPayload;           /* Number of bytes of cell payload */
   46257 
   46258   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46259 
   46260   pInfo->pCell = pCell;
   46261   assert( pPage->leaf==0 || pPage->leaf==1 );
   46262   n = pPage->childPtrSize;
   46263   assert( n==4-4*pPage->leaf );
   46264   if( pPage->intKey ){
   46265     if( pPage->hasData ){
   46266       n += getVarint32(&pCell[n], nPayload);
   46267     }else{
   46268       nPayload = 0;
   46269     }
   46270     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   46271     pInfo->nData = nPayload;
   46272   }else{
   46273     pInfo->nData = 0;
   46274     n += getVarint32(&pCell[n], nPayload);
   46275     pInfo->nKey = nPayload;
   46276   }
   46277   pInfo->nPayload = nPayload;
   46278   pInfo->nHeader = n;
   46279   testcase( nPayload==pPage->maxLocal );
   46280   testcase( nPayload==pPage->maxLocal+1 );
   46281   if( likely(nPayload<=pPage->maxLocal) ){
   46282     /* This is the (easy) common case where the entire payload fits
   46283     ** on the local page.  No overflow is required.
   46284     */
   46285     int nSize;          /* Total size of cell content in bytes */
   46286     nSize = nPayload + n;
   46287     pInfo->nLocal = (u16)nPayload;
   46288     pInfo->iOverflow = 0;
   46289     if( (nSize & ~3)==0 ){
   46290       nSize = 4;        /* Minimum cell size is 4 */
   46291     }
   46292     pInfo->nSize = (u16)nSize;
   46293   }else{
   46294     /* If the payload will not fit completely on the local page, we have
   46295     ** to decide how much to store locally and how much to spill onto
   46296     ** overflow pages.  The strategy is to minimize the amount of unused
   46297     ** space on overflow pages while keeping the amount of local storage
   46298     ** in between minLocal and maxLocal.
   46299     **
   46300     ** Warning:  changing the way overflow payload is distributed in any
   46301     ** way will result in an incompatible file format.
   46302     */
   46303     int minLocal;  /* Minimum amount of payload held locally */
   46304     int maxLocal;  /* Maximum amount of payload held locally */
   46305     int surplus;   /* Overflow payload available for local storage */
   46306 
   46307     minLocal = pPage->minLocal;
   46308     maxLocal = pPage->maxLocal;
   46309     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
   46310     testcase( surplus==maxLocal );
   46311     testcase( surplus==maxLocal+1 );
   46312     if( surplus <= maxLocal ){
   46313       pInfo->nLocal = (u16)surplus;
   46314     }else{
   46315       pInfo->nLocal = (u16)minLocal;
   46316     }
   46317     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
   46318     pInfo->nSize = pInfo->iOverflow + 4;
   46319   }
   46320 }
   46321 #define parseCell(pPage, iCell, pInfo) \
   46322   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
   46323 static void btreeParseCell(
   46324   MemPage *pPage,         /* Page containing the cell */
   46325   int iCell,              /* The cell index.  First cell is 0 */
   46326   CellInfo *pInfo         /* Fill in this structure */
   46327 ){
   46328   parseCell(pPage, iCell, pInfo);
   46329 }
   46330 
   46331 /*
   46332 ** Compute the total number of bytes that a Cell needs in the cell
   46333 ** data area of the btree-page.  The return number includes the cell
   46334 ** data header and the local payload, but not any overflow page or
   46335 ** the space used by the cell pointer.
   46336 */
   46337 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   46338   u8 *pIter = &pCell[pPage->childPtrSize];
   46339   u32 nSize;
   46340 
   46341 #ifdef SQLITE_DEBUG
   46342   /* The value returned by this function should always be the same as
   46343   ** the (CellInfo.nSize) value found by doing a full parse of the
   46344   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
   46345   ** this function verifies that this invariant is not violated. */
   46346   CellInfo debuginfo;
   46347   btreeParseCellPtr(pPage, pCell, &debuginfo);
   46348 #endif
   46349 
   46350   if( pPage->intKey ){
   46351     u8 *pEnd;
   46352     if( pPage->hasData ){
   46353       pIter += getVarint32(pIter, nSize);
   46354     }else{
   46355       nSize = 0;
   46356     }
   46357 
   46358     /* pIter now points at the 64-bit integer key value, a variable length
   46359     ** integer. The following block moves pIter to point at the first byte
   46360     ** past the end of the key value. */
   46361     pEnd = &pIter[9];
   46362     while( (*pIter++)&0x80 && pIter<pEnd );
   46363   }else{
   46364     pIter += getVarint32(pIter, nSize);
   46365   }
   46366 
   46367   testcase( nSize==pPage->maxLocal );
   46368   testcase( nSize==pPage->maxLocal+1 );
   46369   if( nSize>pPage->maxLocal ){
   46370     int minLocal = pPage->minLocal;
   46371     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
   46372     testcase( nSize==pPage->maxLocal );
   46373     testcase( nSize==pPage->maxLocal+1 );
   46374     if( nSize>pPage->maxLocal ){
   46375       nSize = minLocal;
   46376     }
   46377     nSize += 4;
   46378   }
   46379   nSize += (u32)(pIter - pCell);
   46380 
   46381   /* The minimum size of any cell is 4 bytes. */
   46382   if( nSize<4 ){
   46383     nSize = 4;
   46384   }
   46385 
   46386   assert( nSize==debuginfo.nSize );
   46387   return (u16)nSize;
   46388 }
   46389 
   46390 #ifdef SQLITE_DEBUG
   46391 /* This variation on cellSizePtr() is used inside of assert() statements
   46392 ** only. */
   46393 static u16 cellSize(MemPage *pPage, int iCell){
   46394   return cellSizePtr(pPage, findCell(pPage, iCell));
   46395 }
   46396 #endif
   46397 
   46398 #ifndef SQLITE_OMIT_AUTOVACUUM
   46399 /*
   46400 ** If the cell pCell, part of page pPage contains a pointer
   46401 ** to an overflow page, insert an entry into the pointer-map
   46402 ** for the overflow page.
   46403 */
   46404 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
   46405   CellInfo info;
   46406   if( *pRC ) return;
   46407   assert( pCell!=0 );
   46408   btreeParseCellPtr(pPage, pCell, &info);
   46409   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
   46410   if( info.iOverflow ){
   46411     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
   46412     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
   46413   }
   46414 }
   46415 #endif
   46416 
   46417 
   46418 /*
   46419 ** Defragment the page given.  All Cells are moved to the
   46420 ** end of the page and all free space is collected into one
   46421 ** big FreeBlk that occurs in between the header and cell
   46422 ** pointer array and the cell content area.
   46423 */
   46424 static int defragmentPage(MemPage *pPage){
   46425   int i;                     /* Loop counter */
   46426   int pc;                    /* Address of a i-th cell */
   46427   int hdr;                   /* Offset to the page header */
   46428   int size;                  /* Size of a cell */
   46429   int usableSize;            /* Number of usable bytes on a page */
   46430   int cellOffset;            /* Offset to the cell pointer array */
   46431   int cbrk;                  /* Offset to the cell content area */
   46432   int nCell;                 /* Number of cells on the page */
   46433   unsigned char *data;       /* The page data */
   46434   unsigned char *temp;       /* Temp area for cell content */
   46435   int iCellFirst;            /* First allowable cell index */
   46436   int iCellLast;             /* Last possible cell index */
   46437 
   46438 
   46439   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46440   assert( pPage->pBt!=0 );
   46441   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
   46442   assert( pPage->nOverflow==0 );
   46443   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46444   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
   46445   data = pPage->aData;
   46446   hdr = pPage->hdrOffset;
   46447   cellOffset = pPage->cellOffset;
   46448   nCell = pPage->nCell;
   46449   assert( nCell==get2byte(&data[hdr+3]) );
   46450   usableSize = pPage->pBt->usableSize;
   46451   cbrk = get2byte(&data[hdr+5]);
   46452   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
   46453   cbrk = usableSize;
   46454   iCellFirst = cellOffset + 2*nCell;
   46455   iCellLast = usableSize - 4;
   46456   for(i=0; i<nCell; i++){
   46457     u8 *pAddr;     /* The i-th cell pointer */
   46458     pAddr = &data[cellOffset + i*2];
   46459     pc = get2byte(pAddr);
   46460     testcase( pc==iCellFirst );
   46461     testcase( pc==iCellLast );
   46462 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   46463     /* These conditions have already been verified in btreeInitPage()
   46464     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
   46465     */
   46466     if( pc<iCellFirst || pc>iCellLast ){
   46467       return SQLITE_CORRUPT_BKPT;
   46468     }
   46469 #endif
   46470     assert( pc>=iCellFirst && pc<=iCellLast );
   46471     size = cellSizePtr(pPage, &temp[pc]);
   46472     cbrk -= size;
   46473 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   46474     if( cbrk<iCellFirst ){
   46475       return SQLITE_CORRUPT_BKPT;
   46476     }
   46477 #else
   46478     if( cbrk<iCellFirst || pc+size>usableSize ){
   46479       return SQLITE_CORRUPT_BKPT;
   46480     }
   46481 #endif
   46482     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
   46483     testcase( cbrk+size==usableSize );
   46484     testcase( pc+size==usableSize );
   46485     memcpy(&data[cbrk], &temp[pc], size);
   46486     put2byte(pAddr, cbrk);
   46487   }
   46488   assert( cbrk>=iCellFirst );
   46489   put2byte(&data[hdr+5], cbrk);
   46490   data[hdr+1] = 0;
   46491   data[hdr+2] = 0;
   46492   data[hdr+7] = 0;
   46493   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
   46494   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46495   if( cbrk-iCellFirst!=pPage->nFree ){
   46496     return SQLITE_CORRUPT_BKPT;
   46497   }
   46498   return SQLITE_OK;
   46499 }
   46500 
   46501 /*
   46502 ** Allocate nByte bytes of space from within the B-Tree page passed
   46503 ** as the first argument. Write into *pIdx the index into pPage->aData[]
   46504 ** of the first byte of allocated space. Return either SQLITE_OK or
   46505 ** an error code (usually SQLITE_CORRUPT).
   46506 **
   46507 ** The caller guarantees that there is sufficient space to make the
   46508 ** allocation.  This routine might need to defragment in order to bring
   46509 ** all the space together, however.  This routine will avoid using
   46510 ** the first two bytes past the cell pointer area since presumably this
   46511 ** allocation is being made in order to insert a new cell, so we will
   46512 ** also end up needing a new cell pointer.
   46513 */
   46514 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   46515   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
   46516   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
   46517   int nFrag;                           /* Number of fragmented bytes on pPage */
   46518   int top;                             /* First byte of cell content area */
   46519   int gap;        /* First byte of gap between cell pointers and cell content */
   46520   int rc;         /* Integer return code */
   46521   int usableSize; /* Usable size of the page */
   46522 
   46523   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46524   assert( pPage->pBt );
   46525   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46526   assert( nByte>=0 );  /* Minimum cell size is 4 */
   46527   assert( pPage->nFree>=nByte );
   46528   assert( pPage->nOverflow==0 );
   46529   usableSize = pPage->pBt->usableSize;
   46530   assert( nByte < usableSize-8 );
   46531 
   46532   nFrag = data[hdr+7];
   46533   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
   46534   gap = pPage->cellOffset + 2*pPage->nCell;
   46535   top = get2byteNotZero(&data[hdr+5]);
   46536   if( gap>top ) return SQLITE_CORRUPT_BKPT;
   46537   testcase( gap+2==top );
   46538   testcase( gap+1==top );
   46539   testcase( gap==top );
   46540 
   46541   if( nFrag>=60 ){
   46542     /* Always defragment highly fragmented pages */
   46543     rc = defragmentPage(pPage);
   46544     if( rc ) return rc;
   46545     top = get2byteNotZero(&data[hdr+5]);
   46546   }else if( gap+2<=top ){
   46547     /* Search the freelist looking for a free slot big enough to satisfy
   46548     ** the request. The allocation is made from the first free slot in
   46549     ** the list that is large enough to accomadate it.
   46550     */
   46551     int pc, addr;
   46552     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
   46553       int size;            /* Size of the free slot */
   46554       if( pc>usableSize-4 || pc<addr+4 ){
   46555         return SQLITE_CORRUPT_BKPT;
   46556       }
   46557       size = get2byte(&data[pc+2]);
   46558       if( size>=nByte ){
   46559         int x = size - nByte;
   46560         testcase( x==4 );
   46561         testcase( x==3 );
   46562         if( x<4 ){
   46563           /* Remove the slot from the free-list. Update the number of
   46564           ** fragmented bytes within the page. */
   46565           memcpy(&data[addr], &data[pc], 2);
   46566           data[hdr+7] = (u8)(nFrag + x);
   46567         }else if( size+pc > usableSize ){
   46568           return SQLITE_CORRUPT_BKPT;
   46569         }else{
   46570           /* The slot remains on the free-list. Reduce its size to account
   46571           ** for the portion used by the new allocation. */
   46572           put2byte(&data[pc+2], x);
   46573         }
   46574         *pIdx = pc + x;
   46575         return SQLITE_OK;
   46576       }
   46577     }
   46578   }
   46579 
   46580   /* Check to make sure there is enough space in the gap to satisfy
   46581   ** the allocation.  If not, defragment.
   46582   */
   46583   testcase( gap+2+nByte==top );
   46584   if( gap+2+nByte>top ){
   46585     rc = defragmentPage(pPage);
   46586     if( rc ) return rc;
   46587     top = get2byteNotZero(&data[hdr+5]);
   46588     assert( gap+nByte<=top );
   46589   }
   46590 
   46591 
   46592   /* Allocate memory from the gap in between the cell pointer array
   46593   ** and the cell content area.  The btreeInitPage() call has already
   46594   ** validated the freelist.  Given that the freelist is valid, there
   46595   ** is no way that the allocation can extend off the end of the page.
   46596   ** The assert() below verifies the previous sentence.
   46597   */
   46598   top -= nByte;
   46599   put2byte(&data[hdr+5], top);
   46600   assert( top+nByte <= pPage->pBt->usableSize );
   46601   *pIdx = top;
   46602   return SQLITE_OK;
   46603 }
   46604 
   46605 /*
   46606 ** Return a section of the pPage->aData to the freelist.
   46607 ** The first byte of the new free block is pPage->aDisk[start]
   46608 ** and the size of the block is "size" bytes.
   46609 **
   46610 ** Most of the effort here is involved in coalesing adjacent
   46611 ** free blocks into a single big free block.
   46612 */
   46613 static int freeSpace(MemPage *pPage, int start, int size){
   46614   int addr, pbegin, hdr;
   46615   int iLast;                        /* Largest possible freeblock offset */
   46616   unsigned char *data = pPage->aData;
   46617 
   46618   assert( pPage->pBt!=0 );
   46619   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46620   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
   46621   assert( (start + size)<=pPage->pBt->usableSize );
   46622   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46623   assert( size>=0 );   /* Minimum cell size is 4 */
   46624 
   46625   if( pPage->pBt->secureDelete ){
   46626     /* Overwrite deleted information with zeros when the secure_delete
   46627     ** option is enabled */
   46628     memset(&data[start], 0, size);
   46629   }
   46630 
   46631   /* Add the space back into the linked list of freeblocks.  Note that
   46632   ** even though the freeblock list was checked by btreeInitPage(),
   46633   ** btreeInitPage() did not detect overlapping cells or
   46634   ** freeblocks that overlapped cells.   Nor does it detect when the
   46635   ** cell content area exceeds the value in the page header.  If these
   46636   ** situations arise, then subsequent insert operations might corrupt
   46637   ** the freelist.  So we do need to check for corruption while scanning
   46638   ** the freelist.
   46639   */
   46640   hdr = pPage->hdrOffset;
   46641   addr = hdr + 1;
   46642   iLast = pPage->pBt->usableSize - 4;
   46643   assert( start<=iLast );
   46644   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
   46645     if( pbegin<addr+4 ){
   46646       return SQLITE_CORRUPT_BKPT;
   46647     }
   46648     addr = pbegin;
   46649   }
   46650   if( pbegin>iLast ){
   46651     return SQLITE_CORRUPT_BKPT;
   46652   }
   46653   assert( pbegin>addr || pbegin==0 );
   46654   put2byte(&data[addr], start);
   46655   put2byte(&data[start], pbegin);
   46656   put2byte(&data[start+2], size);
   46657   pPage->nFree = pPage->nFree + (u16)size;
   46658 
   46659   /* Coalesce adjacent free blocks */
   46660   addr = hdr + 1;
   46661   while( (pbegin = get2byte(&data[addr]))>0 ){
   46662     int pnext, psize, x;
   46663     assert( pbegin>addr );
   46664     assert( pbegin<=pPage->pBt->usableSize-4 );
   46665     pnext = get2byte(&data[pbegin]);
   46666     psize = get2byte(&data[pbegin+2]);
   46667     if( pbegin + psize + 3 >= pnext && pnext>0 ){
   46668       int frag = pnext - (pbegin+psize);
   46669       if( (frag<0) || (frag>(int)data[hdr+7]) ){
   46670         return SQLITE_CORRUPT_BKPT;
   46671       }
   46672       data[hdr+7] -= (u8)frag;
   46673       x = get2byte(&data[pnext]);
   46674       put2byte(&data[pbegin], x);
   46675       x = pnext + get2byte(&data[pnext+2]) - pbegin;
   46676       put2byte(&data[pbegin+2], x);
   46677     }else{
   46678       addr = pbegin;
   46679     }
   46680   }
   46681 
   46682   /* If the cell content area begins with a freeblock, remove it. */
   46683   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
   46684     int top;
   46685     pbegin = get2byte(&data[hdr+1]);
   46686     memcpy(&data[hdr+1], &data[pbegin], 2);
   46687     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
   46688     put2byte(&data[hdr+5], top);
   46689   }
   46690   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46691   return SQLITE_OK;
   46692 }
   46693 
   46694 /*
   46695 ** Decode the flags byte (the first byte of the header) for a page
   46696 ** and initialize fields of the MemPage structure accordingly.
   46697 **
   46698 ** Only the following combinations are supported.  Anything different
   46699 ** indicates a corrupt database files:
   46700 **
   46701 **         PTF_ZERODATA
   46702 **         PTF_ZERODATA | PTF_LEAF
   46703 **         PTF_LEAFDATA | PTF_INTKEY
   46704 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
   46705 */
   46706 static int decodeFlags(MemPage *pPage, int flagByte){
   46707   BtShared *pBt;     /* A copy of pPage->pBt */
   46708 
   46709   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
   46710   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46711   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
   46712   flagByte &= ~PTF_LEAF;
   46713   pPage->childPtrSize = 4-4*pPage->leaf;
   46714   pBt = pPage->pBt;
   46715   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
   46716     pPage->intKey = 1;
   46717     pPage->hasData = pPage->leaf;
   46718     pPage->maxLocal = pBt->maxLeaf;
   46719     pPage->minLocal = pBt->minLeaf;
   46720   }else if( flagByte==PTF_ZERODATA ){
   46721     pPage->intKey = 0;
   46722     pPage->hasData = 0;
   46723     pPage->maxLocal = pBt->maxLocal;
   46724     pPage->minLocal = pBt->minLocal;
   46725   }else{
   46726     return SQLITE_CORRUPT_BKPT;
   46727   }
   46728   return SQLITE_OK;
   46729 }
   46730 
   46731 /*
   46732 ** Initialize the auxiliary information for a disk block.
   46733 **
   46734 ** Return SQLITE_OK on success.  If we see that the page does
   46735 ** not contain a well-formed database page, then return
   46736 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
   46737 ** guarantee that the page is well-formed.  It only shows that
   46738 ** we failed to detect any corruption.
   46739 */
   46740 static int btreeInitPage(MemPage *pPage){
   46741 
   46742   assert( pPage->pBt!=0 );
   46743   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46744   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
   46745   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
   46746   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
   46747 
   46748   if( !pPage->isInit ){
   46749     u16 pc;            /* Address of a freeblock within pPage->aData[] */
   46750     u8 hdr;            /* Offset to beginning of page header */
   46751     u8 *data;          /* Equal to pPage->aData */
   46752     BtShared *pBt;        /* The main btree structure */
   46753     int usableSize;    /* Amount of usable space on each page */
   46754     u16 cellOffset;    /* Offset from start of page to first cell pointer */
   46755     int nFree;         /* Number of unused bytes on the page */
   46756     int top;           /* First byte of the cell content area */
   46757     int iCellFirst;    /* First allowable cell or freeblock offset */
   46758     int iCellLast;     /* Last possible cell or freeblock offset */
   46759 
   46760     pBt = pPage->pBt;
   46761 
   46762     hdr = pPage->hdrOffset;
   46763     data = pPage->aData;
   46764     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
   46765     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   46766     pPage->maskPage = (u16)(pBt->pageSize - 1);
   46767     pPage->nOverflow = 0;
   46768     usableSize = pBt->usableSize;
   46769     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
   46770     top = get2byteNotZero(&data[hdr+5]);
   46771     pPage->nCell = get2byte(&data[hdr+3]);
   46772     if( pPage->nCell>MX_CELL(pBt) ){
   46773       /* To many cells for a single page.  The page must be corrupt */
   46774       return SQLITE_CORRUPT_BKPT;
   46775     }
   46776     testcase( pPage->nCell==MX_CELL(pBt) );
   46777 
   46778     /* A malformed database page might cause us to read past the end
   46779     ** of page when parsing a cell.
   46780     **
   46781     ** The following block of code checks early to see if a cell extends
   46782     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
   46783     ** returned if it does.
   46784     */
   46785     iCellFirst = cellOffset + 2*pPage->nCell;
   46786     iCellLast = usableSize - 4;
   46787 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
   46788     {
   46789       int i;            /* Index into the cell pointer array */
   46790       int sz;           /* Size of a cell */
   46791 
   46792       if( !pPage->leaf ) iCellLast--;
   46793       for(i=0; i<pPage->nCell; i++){
   46794         pc = get2byte(&data[cellOffset+i*2]);
   46795         testcase( pc==iCellFirst );
   46796         testcase( pc==iCellLast );
   46797         if( pc<iCellFirst || pc>iCellLast ){
   46798           return SQLITE_CORRUPT_BKPT;
   46799         }
   46800         sz = cellSizePtr(pPage, &data[pc]);
   46801         testcase( pc+sz==usableSize );
   46802         if( pc+sz>usableSize ){
   46803           return SQLITE_CORRUPT_BKPT;
   46804         }
   46805       }
   46806       if( !pPage->leaf ) iCellLast++;
   46807     }
   46808 #endif
   46809 
   46810     /* Compute the total free space on the page */
   46811     pc = get2byte(&data[hdr+1]);
   46812     nFree = data[hdr+7] + top;
   46813     while( pc>0 ){
   46814       u16 next, size;
   46815       if( pc<iCellFirst || pc>iCellLast ){
   46816         /* Start of free block is off the page */
   46817         return SQLITE_CORRUPT_BKPT;
   46818       }
   46819       next = get2byte(&data[pc]);
   46820       size = get2byte(&data[pc+2]);
   46821       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
   46822         /* Free blocks must be in ascending order. And the last byte of
   46823 	** the free-block must lie on the database page.  */
   46824         return SQLITE_CORRUPT_BKPT;
   46825       }
   46826       nFree = nFree + size;
   46827       pc = next;
   46828     }
   46829 
   46830     /* At this point, nFree contains the sum of the offset to the start
   46831     ** of the cell-content area plus the number of free bytes within
   46832     ** the cell-content area. If this is greater than the usable-size
   46833     ** of the page, then the page must be corrupted. This check also
   46834     ** serves to verify that the offset to the start of the cell-content
   46835     ** area, according to the page header, lies within the page.
   46836     */
   46837     if( nFree>usableSize ){
   46838       return SQLITE_CORRUPT_BKPT;
   46839     }
   46840     pPage->nFree = (u16)(nFree - iCellFirst);
   46841     pPage->isInit = 1;
   46842   }
   46843   return SQLITE_OK;
   46844 }
   46845 
   46846 /*
   46847 ** Set up a raw page so that it looks like a database page holding
   46848 ** no entries.
   46849 */
   46850 static void zeroPage(MemPage *pPage, int flags){
   46851   unsigned char *data = pPage->aData;
   46852   BtShared *pBt = pPage->pBt;
   46853   u8 hdr = pPage->hdrOffset;
   46854   u16 first;
   46855 
   46856   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
   46857   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   46858   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
   46859   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   46860   assert( sqlite3_mutex_held(pBt->mutex) );
   46861   if( pBt->secureDelete ){
   46862     memset(&data[hdr], 0, pBt->usableSize - hdr);
   46863   }
   46864   data[hdr] = (char)flags;
   46865   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
   46866   memset(&data[hdr+1], 0, 4);
   46867   data[hdr+7] = 0;
   46868   put2byte(&data[hdr+5], pBt->usableSize);
   46869   pPage->nFree = (u16)(pBt->usableSize - first);
   46870   decodeFlags(pPage, flags);
   46871   pPage->hdrOffset = hdr;
   46872   pPage->cellOffset = first;
   46873   pPage->nOverflow = 0;
   46874   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
   46875   pPage->maskPage = (u16)(pBt->pageSize - 1);
   46876   pPage->nCell = 0;
   46877   pPage->isInit = 1;
   46878 }
   46879 
   46880 
   46881 /*
   46882 ** Convert a DbPage obtained from the pager into a MemPage used by
   46883 ** the btree layer.
   46884 */
   46885 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
   46886   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
   46887   pPage->aData = sqlite3PagerGetData(pDbPage);
   46888   pPage->pDbPage = pDbPage;
   46889   pPage->pBt = pBt;
   46890   pPage->pgno = pgno;
   46891   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
   46892   return pPage;
   46893 }
   46894 
   46895 /*
   46896 ** Get a page from the pager.  Initialize the MemPage.pBt and
   46897 ** MemPage.aData elements if needed.
   46898 **
   46899 ** If the noContent flag is set, it means that we do not care about
   46900 ** the content of the page at this time.  So do not go to the disk
   46901 ** to fetch the content.  Just fill in the content with zeros for now.
   46902 ** If in the future we call sqlite3PagerWrite() on this page, that
   46903 ** means we have started to be concerned about content and the disk
   46904 ** read should occur at that point.
   46905 */
   46906 static int btreeGetPage(
   46907   BtShared *pBt,       /* The btree */
   46908   Pgno pgno,           /* Number of the page to fetch */
   46909   MemPage **ppPage,    /* Return the page in this parameter */
   46910   int noContent        /* Do not load page content if true */
   46911 ){
   46912   int rc;
   46913   DbPage *pDbPage;
   46914 
   46915   assert( sqlite3_mutex_held(pBt->mutex) );
   46916   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
   46917   if( rc ) return rc;
   46918   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
   46919   return SQLITE_OK;
   46920 }
   46921 
   46922 /*
   46923 ** Retrieve a page from the pager cache. If the requested page is not
   46924 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
   46925 ** MemPage.aData elements if needed.
   46926 */
   46927 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
   46928   DbPage *pDbPage;
   46929   assert( sqlite3_mutex_held(pBt->mutex) );
   46930   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
   46931   if( pDbPage ){
   46932     return btreePageFromDbPage(pDbPage, pgno, pBt);
   46933   }
   46934   return 0;
   46935 }
   46936 
   46937 /*
   46938 ** Return the size of the database file in pages. If there is any kind of
   46939 ** error, return ((unsigned int)-1).
   46940 */
   46941 static Pgno btreePagecount(BtShared *pBt){
   46942   return pBt->nPage;
   46943 }
   46944 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
   46945   assert( sqlite3BtreeHoldsMutex(p) );
   46946   assert( ((p->pBt->nPage)&0x8000000)==0 );
   46947   return (int)btreePagecount(p->pBt);
   46948 }
   46949 
   46950 /*
   46951 ** Get a page from the pager and initialize it.  This routine is just a
   46952 ** convenience wrapper around separate calls to btreeGetPage() and
   46953 ** btreeInitPage().
   46954 **
   46955 ** If an error occurs, then the value *ppPage is set to is undefined. It
   46956 ** may remain unchanged, or it may be set to an invalid value.
   46957 */
   46958 static int getAndInitPage(
   46959   BtShared *pBt,          /* The database file */
   46960   Pgno pgno,           /* Number of the page to get */
   46961   MemPage **ppPage     /* Write the page pointer here */
   46962 ){
   46963   int rc;
   46964   assert( sqlite3_mutex_held(pBt->mutex) );
   46965 
   46966   if( pgno>btreePagecount(pBt) ){
   46967     rc = SQLITE_CORRUPT_BKPT;
   46968   }else{
   46969     rc = btreeGetPage(pBt, pgno, ppPage, 0);
   46970     if( rc==SQLITE_OK ){
   46971       rc = btreeInitPage(*ppPage);
   46972       if( rc!=SQLITE_OK ){
   46973         releasePage(*ppPage);
   46974       }
   46975     }
   46976   }
   46977 
   46978   testcase( pgno==0 );
   46979   assert( pgno!=0 || rc==SQLITE_CORRUPT );
   46980   return rc;
   46981 }
   46982 
   46983 /*
   46984 ** Release a MemPage.  This should be called once for each prior
   46985 ** call to btreeGetPage.
   46986 */
   46987 static void releasePage(MemPage *pPage){
   46988   if( pPage ){
   46989     assert( pPage->aData );
   46990     assert( pPage->pBt );
   46991     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
   46992     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
   46993     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   46994     sqlite3PagerUnref(pPage->pDbPage);
   46995   }
   46996 }
   46997 
   46998 /*
   46999 ** During a rollback, when the pager reloads information into the cache
   47000 ** so that the cache is restored to its original state at the start of
   47001 ** the transaction, for each page restored this routine is called.
   47002 **
   47003 ** This routine needs to reset the extra data section at the end of the
   47004 ** page to agree with the restored data.
   47005 */
   47006 static void pageReinit(DbPage *pData){
   47007   MemPage *pPage;
   47008   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
   47009   assert( sqlite3PagerPageRefcount(pData)>0 );
   47010   if( pPage->isInit ){
   47011     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   47012     pPage->isInit = 0;
   47013     if( sqlite3PagerPageRefcount(pData)>1 ){
   47014       /* pPage might not be a btree page;  it might be an overflow page
   47015       ** or ptrmap page or a free page.  In those cases, the following
   47016       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
   47017       ** But no harm is done by this.  And it is very important that
   47018       ** btreeInitPage() be called on every btree page so we make
   47019       ** the call for every page that comes in for re-initing. */
   47020       btreeInitPage(pPage);
   47021     }
   47022   }
   47023 }
   47024 
   47025 /*
   47026 ** Invoke the busy handler for a btree.
   47027 */
   47028 static int btreeInvokeBusyHandler(void *pArg){
   47029   BtShared *pBt = (BtShared*)pArg;
   47030   assert( pBt->db );
   47031   assert( sqlite3_mutex_held(pBt->db->mutex) );
   47032   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
   47033 }
   47034 
   47035 /*
   47036 ** Open a database file.
   47037 **
   47038 ** zFilename is the name of the database file.  If zFilename is NULL
   47039 ** then an ephemeral database is created.  The ephemeral database might
   47040 ** be exclusively in memory, or it might use a disk-based memory cache.
   47041 ** Either way, the ephemeral database will be automatically deleted
   47042 ** when sqlite3BtreeClose() is called.
   47043 **
   47044 ** If zFilename is ":memory:" then an in-memory database is created
   47045 ** that is automatically destroyed when it is closed.
   47046 **
   47047 ** The "flags" parameter is a bitmask that might contain bits
   47048 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
   47049 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
   47050 ** These flags are passed through into sqlite3PagerOpen() and must
   47051 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
   47052 **
   47053 ** If the database is already opened in the same database connection
   47054 ** and we are in shared cache mode, then the open will fail with an
   47055 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
   47056 ** objects in the same database connection since doing so will lead
   47057 ** to problems with locking.
   47058 */
   47059 SQLITE_PRIVATE int sqlite3BtreeOpen(
   47060   const char *zFilename,  /* Name of the file containing the BTree database */
   47061   sqlite3 *db,            /* Associated database handle */
   47062   Btree **ppBtree,        /* Pointer to new Btree object written here */
   47063   int flags,              /* Options */
   47064   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
   47065 ){
   47066   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
   47067   BtShared *pBt = 0;             /* Shared part of btree structure */
   47068   Btree *p;                      /* Handle to return */
   47069   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
   47070   int rc = SQLITE_OK;            /* Result code from this function */
   47071   u8 nReserve;                   /* Byte of unused space on each page */
   47072   unsigned char zDbHeader[100];  /* Database header content */
   47073 
   47074   /* True if opening an ephemeral, temporary database */
   47075   const int isTempDb = zFilename==0 || zFilename[0]==0;
   47076 
   47077   /* Set the variable isMemdb to true for an in-memory database, or
   47078   ** false for a file-based database.
   47079   */
   47080 #ifdef SQLITE_OMIT_MEMORYDB
   47081   const int isMemdb = 0;
   47082 #else
   47083   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
   47084                        || (isTempDb && sqlite3TempInMemory(db));
   47085 #endif
   47086 
   47087   assert( db!=0 );
   47088   assert( sqlite3_mutex_held(db->mutex) );
   47089   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
   47090 
   47091   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
   47092   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
   47093 
   47094   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
   47095   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
   47096 
   47097   if( db->flags & SQLITE_NoReadlock ){
   47098     flags |= BTREE_NO_READLOCK;
   47099   }
   47100   if( isMemdb ){
   47101     flags |= BTREE_MEMORY;
   47102   }
   47103   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
   47104     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
   47105   }
   47106   pVfs = db->pVfs;
   47107   p = sqlite3MallocZero(sizeof(Btree));
   47108   if( !p ){
   47109     return SQLITE_NOMEM;
   47110   }
   47111   p->inTrans = TRANS_NONE;
   47112   p->db = db;
   47113 #ifndef SQLITE_OMIT_SHARED_CACHE
   47114   p->lock.pBtree = p;
   47115   p->lock.iTable = 1;
   47116 #endif
   47117 
   47118 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   47119   /*
   47120   ** If this Btree is a candidate for shared cache, try to find an
   47121   ** existing BtShared object that we can share with
   47122   */
   47123   if( isMemdb==0 && isTempDb==0 ){
   47124     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
   47125       int nFullPathname = pVfs->mxPathname+1;
   47126       char *zFullPathname = sqlite3Malloc(nFullPathname);
   47127       sqlite3_mutex *mutexShared;
   47128       p->sharable = 1;
   47129       if( !zFullPathname ){
   47130         sqlite3_free(p);
   47131         return SQLITE_NOMEM;
   47132       }
   47133       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
   47134       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
   47135       sqlite3_mutex_enter(mutexOpen);
   47136       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   47137       sqlite3_mutex_enter(mutexShared);
   47138       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
   47139         assert( pBt->nRef>0 );
   47140         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
   47141                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
   47142           int iDb;
   47143           for(iDb=db->nDb-1; iDb>=0; iDb--){
   47144             Btree *pExisting = db->aDb[iDb].pBt;
   47145             if( pExisting && pExisting->pBt==pBt ){
   47146               sqlite3_mutex_leave(mutexShared);
   47147               sqlite3_mutex_leave(mutexOpen);
   47148               sqlite3_free(zFullPathname);
   47149               sqlite3_free(p);
   47150               return SQLITE_CONSTRAINT;
   47151             }
   47152           }
   47153           p->pBt = pBt;
   47154           pBt->nRef++;
   47155           break;
   47156         }
   47157       }
   47158       sqlite3_mutex_leave(mutexShared);
   47159       sqlite3_free(zFullPathname);
   47160     }
   47161 #ifdef SQLITE_DEBUG
   47162     else{
   47163       /* In debug mode, we mark all persistent databases as sharable
   47164       ** even when they are not.  This exercises the locking code and
   47165       ** gives more opportunity for asserts(sqlite3_mutex_held())
   47166       ** statements to find locking problems.
   47167       */
   47168       p->sharable = 1;
   47169     }
   47170 #endif
   47171   }
   47172 #endif
   47173   if( pBt==0 ){
   47174     /*
   47175     ** The following asserts make sure that structures used by the btree are
   47176     ** the right size.  This is to guard against size changes that result
   47177     ** when compiling on a different architecture.
   47178     */
   47179     assert( sizeof(i64)==8 || sizeof(i64)==4 );
   47180     assert( sizeof(u64)==8 || sizeof(u64)==4 );
   47181     assert( sizeof(u32)==4 );
   47182     assert( sizeof(u16)==2 );
   47183     assert( sizeof(Pgno)==4 );
   47184 
   47185     pBt = sqlite3MallocZero( sizeof(*pBt) );
   47186     if( pBt==0 ){
   47187       rc = SQLITE_NOMEM;
   47188       goto btree_open_out;
   47189     }
   47190     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
   47191                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
   47192     if( rc==SQLITE_OK ){
   47193       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
   47194     }
   47195     if( rc!=SQLITE_OK ){
   47196       goto btree_open_out;
   47197     }
   47198     pBt->openFlags = (u8)flags;
   47199     pBt->db = db;
   47200     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
   47201     p->pBt = pBt;
   47202 
   47203     pBt->pCursor = 0;
   47204     pBt->pPage1 = 0;
   47205     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
   47206 #ifdef SQLITE_SECURE_DELETE
   47207     pBt->secureDelete = 1;
   47208 #endif
   47209     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
   47210     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
   47211          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
   47212       pBt->pageSize = 0;
   47213 #ifndef SQLITE_OMIT_AUTOVACUUM
   47214       /* If the magic name ":memory:" will create an in-memory database, then
   47215       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
   47216       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
   47217       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
   47218       ** regular file-name. In this case the auto-vacuum applies as per normal.
   47219       */
   47220       if( zFilename && !isMemdb ){
   47221         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
   47222         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
   47223       }
   47224 #endif
   47225       nReserve = 0;
   47226     }else{
   47227       nReserve = zDbHeader[20];
   47228       pBt->pageSizeFixed = 1;
   47229 #ifndef SQLITE_OMIT_AUTOVACUUM
   47230       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
   47231       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
   47232 #endif
   47233     }
   47234     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   47235     if( rc ) goto btree_open_out;
   47236     pBt->usableSize = pBt->pageSize - nReserve;
   47237     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
   47238 
   47239 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   47240     /* Add the new BtShared object to the linked list sharable BtShareds.
   47241     */
   47242     if( p->sharable ){
   47243       sqlite3_mutex *mutexShared;
   47244       pBt->nRef = 1;
   47245       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   47246       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
   47247         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
   47248         if( pBt->mutex==0 ){
   47249           rc = SQLITE_NOMEM;
   47250           db->mallocFailed = 0;
   47251           goto btree_open_out;
   47252         }
   47253       }
   47254       sqlite3_mutex_enter(mutexShared);
   47255       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
   47256       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
   47257       sqlite3_mutex_leave(mutexShared);
   47258     }
   47259 #endif
   47260   }
   47261 
   47262 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
   47263   /* If the new Btree uses a sharable pBtShared, then link the new
   47264   ** Btree into the list of all sharable Btrees for the same connection.
   47265   ** The list is kept in ascending order by pBt address.
   47266   */
   47267   if( p->sharable ){
   47268     int i;
   47269     Btree *pSib;
   47270     for(i=0; i<db->nDb; i++){
   47271       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
   47272         while( pSib->pPrev ){ pSib = pSib->pPrev; }
   47273         if( p->pBt<pSib->pBt ){
   47274           p->pNext = pSib;
   47275           p->pPrev = 0;
   47276           pSib->pPrev = p;
   47277         }else{
   47278           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
   47279             pSib = pSib->pNext;
   47280           }
   47281           p->pNext = pSib->pNext;
   47282           p->pPrev = pSib;
   47283           if( p->pNext ){
   47284             p->pNext->pPrev = p;
   47285           }
   47286           pSib->pNext = p;
   47287         }
   47288         break;
   47289       }
   47290     }
   47291   }
   47292 #endif
   47293   *ppBtree = p;
   47294 
   47295 btree_open_out:
   47296   if( rc!=SQLITE_OK ){
   47297     if( pBt && pBt->pPager ){
   47298       sqlite3PagerClose(pBt->pPager);
   47299     }
   47300     sqlite3_free(pBt);
   47301     sqlite3_free(p);
   47302     *ppBtree = 0;
   47303   }else{
   47304     /* If the B-Tree was successfully opened, set the pager-cache size to the
   47305     ** default value. Except, when opening on an existing shared pager-cache,
   47306     ** do not change the pager-cache size.
   47307     */
   47308     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
   47309       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
   47310     }
   47311   }
   47312   if( mutexOpen ){
   47313     assert( sqlite3_mutex_held(mutexOpen) );
   47314     sqlite3_mutex_leave(mutexOpen);
   47315   }
   47316   return rc;
   47317 }
   47318 
   47319 /*
   47320 ** Decrement the BtShared.nRef counter.  When it reaches zero,
   47321 ** remove the BtShared structure from the sharing list.  Return
   47322 ** true if the BtShared.nRef counter reaches zero and return
   47323 ** false if it is still positive.
   47324 */
   47325 static int removeFromSharingList(BtShared *pBt){
   47326 #ifndef SQLITE_OMIT_SHARED_CACHE
   47327   sqlite3_mutex *pMaster;
   47328   BtShared *pList;
   47329   int removed = 0;
   47330 
   47331   assert( sqlite3_mutex_notheld(pBt->mutex) );
   47332   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   47333   sqlite3_mutex_enter(pMaster);
   47334   pBt->nRef--;
   47335   if( pBt->nRef<=0 ){
   47336     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
   47337       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
   47338     }else{
   47339       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
   47340       while( ALWAYS(pList) && pList->pNext!=pBt ){
   47341         pList=pList->pNext;
   47342       }
   47343       if( ALWAYS(pList) ){
   47344         pList->pNext = pBt->pNext;
   47345       }
   47346     }
   47347     if( SQLITE_THREADSAFE ){
   47348       sqlite3_mutex_free(pBt->mutex);
   47349     }
   47350     removed = 1;
   47351   }
   47352   sqlite3_mutex_leave(pMaster);
   47353   return removed;
   47354 #else
   47355   return 1;
   47356 #endif
   47357 }
   47358 
   47359 /*
   47360 ** Make sure pBt->pTmpSpace points to an allocation of
   47361 ** MX_CELL_SIZE(pBt) bytes.
   47362 */
   47363 static void allocateTempSpace(BtShared *pBt){
   47364   if( !pBt->pTmpSpace ){
   47365     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
   47366   }
   47367 }
   47368 
   47369 /*
   47370 ** Free the pBt->pTmpSpace allocation
   47371 */
   47372 static void freeTempSpace(BtShared *pBt){
   47373   sqlite3PageFree( pBt->pTmpSpace);
   47374   pBt->pTmpSpace = 0;
   47375 }
   47376 
   47377 /*
   47378 ** Close an open database and invalidate all cursors.
   47379 */
   47380 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   47381   BtShared *pBt = p->pBt;
   47382   BtCursor *pCur;
   47383 
   47384   /* Close all cursors opened via this handle.  */
   47385   assert( sqlite3_mutex_held(p->db->mutex) );
   47386   sqlite3BtreeEnter(p);
   47387   pCur = pBt->pCursor;
   47388   while( pCur ){
   47389     BtCursor *pTmp = pCur;
   47390     pCur = pCur->pNext;
   47391     if( pTmp->pBtree==p ){
   47392       sqlite3BtreeCloseCursor(pTmp);
   47393     }
   47394   }
   47395 
   47396   /* Rollback any active transaction and free the handle structure.
   47397   ** The call to sqlite3BtreeRollback() drops any table-locks held by
   47398   ** this handle.
   47399   */
   47400   sqlite3BtreeRollback(p);
   47401   sqlite3BtreeLeave(p);
   47402 
   47403   /* If there are still other outstanding references to the shared-btree
   47404   ** structure, return now. The remainder of this procedure cleans
   47405   ** up the shared-btree.
   47406   */
   47407   assert( p->wantToLock==0 && p->locked==0 );
   47408   if( !p->sharable || removeFromSharingList(pBt) ){
   47409     /* The pBt is no longer on the sharing list, so we can access
   47410     ** it without having to hold the mutex.
   47411     **
   47412     ** Clean out and delete the BtShared object.
   47413     */
   47414     assert( !pBt->pCursor );
   47415     sqlite3PagerClose(pBt->pPager);
   47416     if( pBt->xFreeSchema && pBt->pSchema ){
   47417       pBt->xFreeSchema(pBt->pSchema);
   47418     }
   47419     sqlite3DbFree(0, pBt->pSchema);
   47420     freeTempSpace(pBt);
   47421     sqlite3_free(pBt);
   47422   }
   47423 
   47424 #ifndef SQLITE_OMIT_SHARED_CACHE
   47425   assert( p->wantToLock==0 );
   47426   assert( p->locked==0 );
   47427   if( p->pPrev ) p->pPrev->pNext = p->pNext;
   47428   if( p->pNext ) p->pNext->pPrev = p->pPrev;
   47429 #endif
   47430 
   47431   sqlite3_free(p);
   47432   return SQLITE_OK;
   47433 }
   47434 
   47435 /*
   47436 ** Change the limit on the number of pages allowed in the cache.
   47437 **
   47438 ** The maximum number of cache pages is set to the absolute
   47439 ** value of mxPage.  If mxPage is negative, the pager will
   47440 ** operate asynchronously - it will not stop to do fsync()s
   47441 ** to insure data is written to the disk surface before
   47442 ** continuing.  Transactions still work if synchronous is off,
   47443 ** and the database cannot be corrupted if this program
   47444 ** crashes.  But if the operating system crashes or there is
   47445 ** an abrupt power failure when synchronous is off, the database
   47446 ** could be left in an inconsistent and unrecoverable state.
   47447 ** Synchronous is on by default so database corruption is not
   47448 ** normally a worry.
   47449 */
   47450 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
   47451   BtShared *pBt = p->pBt;
   47452   assert( sqlite3_mutex_held(p->db->mutex) );
   47453   sqlite3BtreeEnter(p);
   47454   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
   47455   sqlite3BtreeLeave(p);
   47456   return SQLITE_OK;
   47457 }
   47458 
   47459 /*
   47460 ** Change the way data is synced to disk in order to increase or decrease
   47461 ** how well the database resists damage due to OS crashes and power
   47462 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
   47463 ** there is a high probability of damage)  Level 2 is the default.  There
   47464 ** is a very low but non-zero probability of damage.  Level 3 reduces the
   47465 ** probability of damage to near zero but with a write performance reduction.
   47466 */
   47467 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   47468 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
   47469   Btree *p,              /* The btree to set the safety level on */
   47470   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
   47471   int fullSync,          /* PRAGMA fullfsync. */
   47472   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
   47473 ){
   47474   BtShared *pBt = p->pBt;
   47475   assert( sqlite3_mutex_held(p->db->mutex) );
   47476   assert( level>=1 && level<=3 );
   47477   sqlite3BtreeEnter(p);
   47478   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
   47479   sqlite3BtreeLeave(p);
   47480   return SQLITE_OK;
   47481 }
   47482 #endif
   47483 
   47484 /*
   47485 ** Return TRUE if the given btree is set to safety level 1.  In other
   47486 ** words, return TRUE if no sync() occurs on the disk files.
   47487 */
   47488 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
   47489   BtShared *pBt = p->pBt;
   47490   int rc;
   47491   assert( sqlite3_mutex_held(p->db->mutex) );
   47492   sqlite3BtreeEnter(p);
   47493   assert( pBt && pBt->pPager );
   47494   rc = sqlite3PagerNosync(pBt->pPager);
   47495   sqlite3BtreeLeave(p);
   47496   return rc;
   47497 }
   47498 
   47499 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
   47500 /*
   47501 ** Change the default pages size and the number of reserved bytes per page.
   47502 ** Or, if the page size has already been fixed, return SQLITE_READONLY
   47503 ** without changing anything.
   47504 **
   47505 ** The page size must be a power of 2 between 512 and 65536.  If the page
   47506 ** size supplied does not meet this constraint then the page size is not
   47507 ** changed.
   47508 **
   47509 ** Page sizes are constrained to be a power of two so that the region
   47510 ** of the database file used for locking (beginning at PENDING_BYTE,
   47511 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
   47512 ** at the beginning of a page.
   47513 **
   47514 ** If parameter nReserve is less than zero, then the number of reserved
   47515 ** bytes per page is left unchanged.
   47516 **
   47517 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
   47518 ** and autovacuum mode can no longer be changed.
   47519 */
   47520 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   47521   int rc = SQLITE_OK;
   47522   BtShared *pBt = p->pBt;
   47523   assert( nReserve>=-1 && nReserve<=255 );
   47524   sqlite3BtreeEnter(p);
   47525   if( pBt->pageSizeFixed ){
   47526     sqlite3BtreeLeave(p);
   47527     return SQLITE_READONLY;
   47528   }
   47529   if( nReserve<0 ){
   47530     nReserve = pBt->pageSize - pBt->usableSize;
   47531   }
   47532   assert( nReserve>=0 && nReserve<=255 );
   47533   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
   47534         ((pageSize-1)&pageSize)==0 ){
   47535     assert( (pageSize & 7)==0 );
   47536     assert( !pBt->pPage1 && !pBt->pCursor );
   47537     pBt->pageSize = (u32)pageSize;
   47538     freeTempSpace(pBt);
   47539   }
   47540   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
   47541   pBt->usableSize = pBt->pageSize - (u16)nReserve;
   47542   if( iFix ) pBt->pageSizeFixed = 1;
   47543   sqlite3BtreeLeave(p);
   47544   return rc;
   47545 }
   47546 
   47547 /*
   47548 ** Return the currently defined page size
   47549 */
   47550 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
   47551   return p->pBt->pageSize;
   47552 }
   47553 
   47554 /*
   47555 ** Return the number of bytes of space at the end of every page that
   47556 ** are intentually left unused.  This is the "reserved" space that is
   47557 ** sometimes used by extensions.
   47558 */
   47559 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
   47560   int n;
   47561   sqlite3BtreeEnter(p);
   47562   n = p->pBt->pageSize - p->pBt->usableSize;
   47563   sqlite3BtreeLeave(p);
   47564   return n;
   47565 }
   47566 
   47567 /*
   47568 ** Set the maximum page count for a database if mxPage is positive.
   47569 ** No changes are made if mxPage is 0 or negative.
   47570 ** Regardless of the value of mxPage, return the maximum page count.
   47571 */
   47572 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
   47573   int n;
   47574   sqlite3BtreeEnter(p);
   47575   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   47576   sqlite3BtreeLeave(p);
   47577   return n;
   47578 }
   47579 
   47580 /*
   47581 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
   47582 ** then make no changes.  Always return the value of the secureDelete
   47583 ** setting after the change.
   47584 */
   47585 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
   47586   int b;
   47587   if( p==0 ) return 0;
   47588   sqlite3BtreeEnter(p);
   47589   if( newFlag>=0 ){
   47590     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
   47591   }
   47592   b = p->pBt->secureDelete;
   47593   sqlite3BtreeLeave(p);
   47594   return b;
   47595 }
   47596 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
   47597 
   47598 /*
   47599 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
   47600 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
   47601 ** is disabled. The default value for the auto-vacuum property is
   47602 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
   47603 */
   47604 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
   47605 #ifdef SQLITE_OMIT_AUTOVACUUM
   47606   return SQLITE_READONLY;
   47607 #else
   47608   BtShared *pBt = p->pBt;
   47609   int rc = SQLITE_OK;
   47610   u8 av = (u8)autoVacuum;
   47611 
   47612   sqlite3BtreeEnter(p);
   47613   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
   47614     rc = SQLITE_READONLY;
   47615   }else{
   47616     pBt->autoVacuum = av ?1:0;
   47617     pBt->incrVacuum = av==2 ?1:0;
   47618   }
   47619   sqlite3BtreeLeave(p);
   47620   return rc;
   47621 #endif
   47622 }
   47623 
   47624 /*
   47625 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
   47626 ** enabled 1 is returned. Otherwise 0.
   47627 */
   47628 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
   47629 #ifdef SQLITE_OMIT_AUTOVACUUM
   47630   return BTREE_AUTOVACUUM_NONE;
   47631 #else
   47632   int rc;
   47633   sqlite3BtreeEnter(p);
   47634   rc = (
   47635     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
   47636     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
   47637     BTREE_AUTOVACUUM_INCR
   47638   );
   47639   sqlite3BtreeLeave(p);
   47640   return rc;
   47641 #endif
   47642 }
   47643 
   47644 
   47645 /*
   47646 ** Get a reference to pPage1 of the database file.  This will
   47647 ** also acquire a readlock on that file.
   47648 **
   47649 ** SQLITE_OK is returned on success.  If the file is not a
   47650 ** well-formed database file, then SQLITE_CORRUPT is returned.
   47651 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
   47652 ** is returned if we run out of memory.
   47653 */
   47654 static int lockBtree(BtShared *pBt){
   47655   int rc;              /* Result code from subfunctions */
   47656   MemPage *pPage1;     /* Page 1 of the database file */
   47657   int nPage;           /* Number of pages in the database */
   47658   int nPageFile = 0;   /* Number of pages in the database file */
   47659   int nPageHeader;     /* Number of pages in the database according to hdr */
   47660 
   47661   assert( sqlite3_mutex_held(pBt->mutex) );
   47662   assert( pBt->pPage1==0 );
   47663   rc = sqlite3PagerSharedLock(pBt->pPager);
   47664   if( rc!=SQLITE_OK ) return rc;
   47665   rc = btreeGetPage(pBt, 1, &pPage1, 0);
   47666   if( rc!=SQLITE_OK ) return rc;
   47667 
   47668   /* Do some checking to help insure the file we opened really is
   47669   ** a valid database file.
   47670   */
   47671   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   47672   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
   47673   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
   47674     nPage = nPageFile;
   47675   }
   47676   if( nPage>0 ){
   47677     u32 pageSize;
   47678     u32 usableSize;
   47679     u8 *page1 = pPage1->aData;
   47680     rc = SQLITE_NOTADB;
   47681     if( memcmp(page1, zMagicHeader, 16)!=0 ){
   47682       goto page1_init_failed;
   47683     }
   47684 
   47685 #ifdef SQLITE_OMIT_WAL
   47686     if( page1[18]>1 ){
   47687       pBt->readOnly = 1;
   47688     }
   47689     if( page1[19]>1 ){
   47690       goto page1_init_failed;
   47691     }
   47692 #else
   47693     if( page1[18]>2 ){
   47694       pBt->readOnly = 1;
   47695     }
   47696     if( page1[19]>2 ){
   47697       goto page1_init_failed;
   47698     }
   47699 
   47700     /* If the write version is set to 2, this database should be accessed
   47701     ** in WAL mode. If the log is not already open, open it now. Then
   47702     ** return SQLITE_OK and return without populating BtShared.pPage1.
   47703     ** The caller detects this and calls this function again. This is
   47704     ** required as the version of page 1 currently in the page1 buffer
   47705     ** may not be the latest version - there may be a newer one in the log
   47706     ** file.
   47707     */
   47708     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
   47709       int isOpen = 0;
   47710       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
   47711       if( rc!=SQLITE_OK ){
   47712         goto page1_init_failed;
   47713       }else if( isOpen==0 ){
   47714         releasePage(pPage1);
   47715         return SQLITE_OK;
   47716       }
   47717       rc = SQLITE_NOTADB;
   47718     }
   47719 #endif
   47720 
   47721     /* The maximum embedded fraction must be exactly 25%.  And the minimum
   47722     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
   47723     ** The original design allowed these amounts to vary, but as of
   47724     ** version 3.6.0, we require them to be fixed.
   47725     */
   47726     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
   47727       goto page1_init_failed;
   47728     }
   47729     pageSize = (page1[16]<<8) | (page1[17]<<16);
   47730     if( ((pageSize-1)&pageSize)!=0
   47731      || pageSize>SQLITE_MAX_PAGE_SIZE
   47732      || pageSize<=256
   47733     ){
   47734       goto page1_init_failed;
   47735     }
   47736     assert( (pageSize & 7)==0 );
   47737     usableSize = pageSize - page1[20];
   47738     if( (u32)pageSize!=pBt->pageSize ){
   47739       /* After reading the first page of the database assuming a page size
   47740       ** of BtShared.pageSize, we have discovered that the page-size is
   47741       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
   47742       ** zero and return SQLITE_OK. The caller will call this function
   47743       ** again with the correct page-size.
   47744       */
   47745       releasePage(pPage1);
   47746       pBt->usableSize = usableSize;
   47747       pBt->pageSize = pageSize;
   47748       freeTempSpace(pBt);
   47749       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
   47750                                    pageSize-usableSize);
   47751       return rc;
   47752     }
   47753     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
   47754       rc = SQLITE_CORRUPT_BKPT;
   47755       goto page1_init_failed;
   47756     }
   47757     if( usableSize<480 ){
   47758       goto page1_init_failed;
   47759     }
   47760     pBt->pageSize = pageSize;
   47761     pBt->usableSize = usableSize;
   47762 #ifndef SQLITE_OMIT_AUTOVACUUM
   47763     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
   47764     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
   47765 #endif
   47766   }
   47767 
   47768   /* maxLocal is the maximum amount of payload to store locally for
   47769   ** a cell.  Make sure it is small enough so that at least minFanout
   47770   ** cells can will fit on one page.  We assume a 10-byte page header.
   47771   ** Besides the payload, the cell must store:
   47772   **     2-byte pointer to the cell
   47773   **     4-byte child pointer
   47774   **     9-byte nKey value
   47775   **     4-byte nData value
   47776   **     4-byte overflow page pointer
   47777   ** So a cell consists of a 2-byte pointer, a header which is as much as
   47778   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
   47779   ** page pointer.
   47780   */
   47781   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
   47782   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
   47783   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
   47784   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
   47785   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
   47786   pBt->pPage1 = pPage1;
   47787   pBt->nPage = nPage;
   47788   return SQLITE_OK;
   47789 
   47790 page1_init_failed:
   47791   releasePage(pPage1);
   47792   pBt->pPage1 = 0;
   47793   return rc;
   47794 }
   47795 
   47796 /*
   47797 ** If there are no outstanding cursors and we are not in the middle
   47798 ** of a transaction but there is a read lock on the database, then
   47799 ** this routine unrefs the first page of the database file which
   47800 ** has the effect of releasing the read lock.
   47801 **
   47802 ** If there is a transaction in progress, this routine is a no-op.
   47803 */
   47804 static void unlockBtreeIfUnused(BtShared *pBt){
   47805   assert( sqlite3_mutex_held(pBt->mutex) );
   47806   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
   47807   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
   47808     assert( pBt->pPage1->aData );
   47809     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
   47810     assert( pBt->pPage1->aData );
   47811     releasePage(pBt->pPage1);
   47812     pBt->pPage1 = 0;
   47813   }
   47814 }
   47815 
   47816 /*
   47817 ** If pBt points to an empty file then convert that empty file
   47818 ** into a new empty database by initializing the first page of
   47819 ** the database.
   47820 */
   47821 static int newDatabase(BtShared *pBt){
   47822   MemPage *pP1;
   47823   unsigned char *data;
   47824   int rc;
   47825 
   47826   assert( sqlite3_mutex_held(pBt->mutex) );
   47827   if( pBt->nPage>0 ){
   47828     return SQLITE_OK;
   47829   }
   47830   pP1 = pBt->pPage1;
   47831   assert( pP1!=0 );
   47832   data = pP1->aData;
   47833   rc = sqlite3PagerWrite(pP1->pDbPage);
   47834   if( rc ) return rc;
   47835   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
   47836   assert( sizeof(zMagicHeader)==16 );
   47837   data[16] = (u8)((pBt->pageSize>>8)&0xff);
   47838   data[17] = (u8)((pBt->pageSize>>16)&0xff);
   47839   data[18] = 1;
   47840   data[19] = 1;
   47841   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
   47842   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
   47843   data[21] = 64;
   47844   data[22] = 32;
   47845   data[23] = 32;
   47846   memset(&data[24], 0, 100-24);
   47847   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
   47848   pBt->pageSizeFixed = 1;
   47849 #ifndef SQLITE_OMIT_AUTOVACUUM
   47850   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
   47851   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
   47852   put4byte(&data[36 + 4*4], pBt->autoVacuum);
   47853   put4byte(&data[36 + 7*4], pBt->incrVacuum);
   47854 #endif
   47855   pBt->nPage = 1;
   47856   data[31] = 1;
   47857   return SQLITE_OK;
   47858 }
   47859 
   47860 /*
   47861 ** Attempt to start a new transaction. A write-transaction
   47862 ** is started if the second argument is nonzero, otherwise a read-
   47863 ** transaction.  If the second argument is 2 or more and exclusive
   47864 ** transaction is started, meaning that no other process is allowed
   47865 ** to access the database.  A preexisting transaction may not be
   47866 ** upgraded to exclusive by calling this routine a second time - the
   47867 ** exclusivity flag only works for a new transaction.
   47868 **
   47869 ** A write-transaction must be started before attempting any
   47870 ** changes to the database.  None of the following routines
   47871 ** will work unless a transaction is started first:
   47872 **
   47873 **      sqlite3BtreeCreateTable()
   47874 **      sqlite3BtreeCreateIndex()
   47875 **      sqlite3BtreeClearTable()
   47876 **      sqlite3BtreeDropTable()
   47877 **      sqlite3BtreeInsert()
   47878 **      sqlite3BtreeDelete()
   47879 **      sqlite3BtreeUpdateMeta()
   47880 **
   47881 ** If an initial attempt to acquire the lock fails because of lock contention
   47882 ** and the database was previously unlocked, then invoke the busy handler
   47883 ** if there is one.  But if there was previously a read-lock, do not
   47884 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
   47885 ** returned when there is already a read-lock in order to avoid a deadlock.
   47886 **
   47887 ** Suppose there are two processes A and B.  A has a read lock and B has
   47888 ** a reserved lock.  B tries to promote to exclusive but is blocked because
   47889 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
   47890 ** One or the other of the two processes must give way or there can be
   47891 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
   47892 ** when A already has a read lock, we encourage A to give up and let B
   47893 ** proceed.
   47894 */
   47895 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
   47896   sqlite3 *pBlock = 0;
   47897   BtShared *pBt = p->pBt;
   47898   int rc = SQLITE_OK;
   47899 
   47900   sqlite3BtreeEnter(p);
   47901   btreeIntegrity(p);
   47902 
   47903   /* If the btree is already in a write-transaction, or it
   47904   ** is already in a read-transaction and a read-transaction
   47905   ** is requested, this is a no-op.
   47906   */
   47907   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
   47908     goto trans_begun;
   47909   }
   47910 
   47911   /* Write transactions are not possible on a read-only database */
   47912   if( pBt->readOnly && wrflag ){
   47913     rc = SQLITE_READONLY;
   47914     goto trans_begun;
   47915   }
   47916 
   47917 #ifndef SQLITE_OMIT_SHARED_CACHE
   47918   /* If another database handle has already opened a write transaction
   47919   ** on this shared-btree structure and a second write transaction is
   47920   ** requested, return SQLITE_LOCKED.
   47921   */
   47922   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
   47923     pBlock = pBt->pWriter->db;
   47924   }else if( wrflag>1 ){
   47925     BtLock *pIter;
   47926     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
   47927       if( pIter->pBtree!=p ){
   47928         pBlock = pIter->pBtree->db;
   47929         break;
   47930       }
   47931     }
   47932   }
   47933   if( pBlock ){
   47934     sqlite3ConnectionBlocked(p->db, pBlock);
   47935     rc = SQLITE_LOCKED_SHAREDCACHE;
   47936     goto trans_begun;
   47937   }
   47938 #endif
   47939 
   47940   /* Any read-only or read-write transaction implies a read-lock on
   47941   ** page 1. So if some other shared-cache client already has a write-lock
   47942   ** on page 1, the transaction cannot be opened. */
   47943   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   47944   if( SQLITE_OK!=rc ) goto trans_begun;
   47945 
   47946   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
   47947   do {
   47948     /* Call lockBtree() until either pBt->pPage1 is populated or
   47949     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
   47950     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
   47951     ** reading page 1 it discovers that the page-size of the database
   47952     ** file is not pBt->pageSize. In this case lockBtree() will update
   47953     ** pBt->pageSize to the page-size of the file on disk.
   47954     */
   47955     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
   47956 
   47957     if( rc==SQLITE_OK && wrflag ){
   47958       if( pBt->readOnly ){
   47959         rc = SQLITE_READONLY;
   47960       }else{
   47961         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
   47962         if( rc==SQLITE_OK ){
   47963           rc = newDatabase(pBt);
   47964         }
   47965       }
   47966     }
   47967 
   47968     if( rc!=SQLITE_OK ){
   47969       unlockBtreeIfUnused(pBt);
   47970     }
   47971   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
   47972           btreeInvokeBusyHandler(pBt) );
   47973 
   47974   if( rc==SQLITE_OK ){
   47975     if( p->inTrans==TRANS_NONE ){
   47976       pBt->nTransaction++;
   47977 #ifndef SQLITE_OMIT_SHARED_CACHE
   47978       if( p->sharable ){
   47979 	assert( p->lock.pBtree==p && p->lock.iTable==1 );
   47980         p->lock.eLock = READ_LOCK;
   47981         p->lock.pNext = pBt->pLock;
   47982         pBt->pLock = &p->lock;
   47983       }
   47984 #endif
   47985     }
   47986     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
   47987     if( p->inTrans>pBt->inTransaction ){
   47988       pBt->inTransaction = p->inTrans;
   47989     }
   47990     if( wrflag ){
   47991       MemPage *pPage1 = pBt->pPage1;
   47992 #ifndef SQLITE_OMIT_SHARED_CACHE
   47993       assert( !pBt->pWriter );
   47994       pBt->pWriter = p;
   47995       pBt->isExclusive = (u8)(wrflag>1);
   47996 #endif
   47997 
   47998       /* If the db-size header field is incorrect (as it may be if an old
   47999       ** client has been writing the database file), update it now. Doing
   48000       ** this sooner rather than later means the database size can safely
   48001       ** re-read the database size from page 1 if a savepoint or transaction
   48002       ** rollback occurs within the transaction.
   48003       */
   48004       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
   48005         rc = sqlite3PagerWrite(pPage1->pDbPage);
   48006         if( rc==SQLITE_OK ){
   48007           put4byte(&pPage1->aData[28], pBt->nPage);
   48008         }
   48009       }
   48010     }
   48011   }
   48012 
   48013 
   48014 trans_begun:
   48015   if( rc==SQLITE_OK && wrflag ){
   48016     /* This call makes sure that the pager has the correct number of
   48017     ** open savepoints. If the second parameter is greater than 0 and
   48018     ** the sub-journal is not already open, then it will be opened here.
   48019     */
   48020     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
   48021   }
   48022 
   48023   btreeIntegrity(p);
   48024   sqlite3BtreeLeave(p);
   48025   return rc;
   48026 }
   48027 
   48028 #ifndef SQLITE_OMIT_AUTOVACUUM
   48029 
   48030 /*
   48031 ** Set the pointer-map entries for all children of page pPage. Also, if
   48032 ** pPage contains cells that point to overflow pages, set the pointer
   48033 ** map entries for the overflow pages as well.
   48034 */
   48035 static int setChildPtrmaps(MemPage *pPage){
   48036   int i;                             /* Counter variable */
   48037   int nCell;                         /* Number of cells in page pPage */
   48038   int rc;                            /* Return code */
   48039   BtShared *pBt = pPage->pBt;
   48040   u8 isInitOrig = pPage->isInit;
   48041   Pgno pgno = pPage->pgno;
   48042 
   48043   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   48044   rc = btreeInitPage(pPage);
   48045   if( rc!=SQLITE_OK ){
   48046     goto set_child_ptrmaps_out;
   48047   }
   48048   nCell = pPage->nCell;
   48049 
   48050   for(i=0; i<nCell; i++){
   48051     u8 *pCell = findCell(pPage, i);
   48052 
   48053     ptrmapPutOvflPtr(pPage, pCell, &rc);
   48054 
   48055     if( !pPage->leaf ){
   48056       Pgno childPgno = get4byte(pCell);
   48057       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   48058     }
   48059   }
   48060 
   48061   if( !pPage->leaf ){
   48062     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   48063     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
   48064   }
   48065 
   48066 set_child_ptrmaps_out:
   48067   pPage->isInit = isInitOrig;
   48068   return rc;
   48069 }
   48070 
   48071 /*
   48072 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
   48073 ** that it points to iTo. Parameter eType describes the type of pointer to
   48074 ** be modified, as  follows:
   48075 **
   48076 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
   48077 **                   page of pPage.
   48078 **
   48079 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
   48080 **                   page pointed to by one of the cells on pPage.
   48081 **
   48082 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
   48083 **                   overflow page in the list.
   48084 */
   48085 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
   48086   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   48087   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   48088   if( eType==PTRMAP_OVERFLOW2 ){
   48089     /* The pointer is always the first 4 bytes of the page in this case.  */
   48090     if( get4byte(pPage->aData)!=iFrom ){
   48091       return SQLITE_CORRUPT_BKPT;
   48092     }
   48093     put4byte(pPage->aData, iTo);
   48094   }else{
   48095     u8 isInitOrig = pPage->isInit;
   48096     int i;
   48097     int nCell;
   48098 
   48099     btreeInitPage(pPage);
   48100     nCell = pPage->nCell;
   48101 
   48102     for(i=0; i<nCell; i++){
   48103       u8 *pCell = findCell(pPage, i);
   48104       if( eType==PTRMAP_OVERFLOW1 ){
   48105         CellInfo info;
   48106         btreeParseCellPtr(pPage, pCell, &info);
   48107         if( info.iOverflow ){
   48108           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
   48109             put4byte(&pCell[info.iOverflow], iTo);
   48110             break;
   48111           }
   48112         }
   48113       }else{
   48114         if( get4byte(pCell)==iFrom ){
   48115           put4byte(pCell, iTo);
   48116           break;
   48117         }
   48118       }
   48119     }
   48120 
   48121     if( i==nCell ){
   48122       if( eType!=PTRMAP_BTREE ||
   48123           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
   48124         return SQLITE_CORRUPT_BKPT;
   48125       }
   48126       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
   48127     }
   48128 
   48129     pPage->isInit = isInitOrig;
   48130   }
   48131   return SQLITE_OK;
   48132 }
   48133 
   48134 
   48135 /*
   48136 ** Move the open database page pDbPage to location iFreePage in the
   48137 ** database. The pDbPage reference remains valid.
   48138 **
   48139 ** The isCommit flag indicates that there is no need to remember that
   48140 ** the journal needs to be sync()ed before database page pDbPage->pgno
   48141 ** can be written to. The caller has already promised not to write to that
   48142 ** page.
   48143 */
   48144 static int relocatePage(
   48145   BtShared *pBt,           /* Btree */
   48146   MemPage *pDbPage,        /* Open page to move */
   48147   u8 eType,                /* Pointer map 'type' entry for pDbPage */
   48148   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
   48149   Pgno iFreePage,          /* The location to move pDbPage to */
   48150   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
   48151 ){
   48152   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
   48153   Pgno iDbPage = pDbPage->pgno;
   48154   Pager *pPager = pBt->pPager;
   48155   int rc;
   48156 
   48157   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
   48158       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   48159   assert( sqlite3_mutex_held(pBt->mutex) );
   48160   assert( pDbPage->pBt==pBt );
   48161 
   48162   /* Move page iDbPage from its current location to page number iFreePage */
   48163   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
   48164       iDbPage, iFreePage, iPtrPage, eType));
   48165   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   48166   if( rc!=SQLITE_OK ){
   48167     return rc;
   48168   }
   48169   pDbPage->pgno = iFreePage;
   48170 
   48171   /* If pDbPage was a btree-page, then it may have child pages and/or cells
   48172   ** that point to overflow pages. The pointer map entries for all these
   48173   ** pages need to be changed.
   48174   **
   48175   ** If pDbPage is an overflow page, then the first 4 bytes may store a
   48176   ** pointer to a subsequent overflow page. If this is the case, then
   48177   ** the pointer map needs to be updated for the subsequent overflow page.
   48178   */
   48179   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
   48180     rc = setChildPtrmaps(pDbPage);
   48181     if( rc!=SQLITE_OK ){
   48182       return rc;
   48183     }
   48184   }else{
   48185     Pgno nextOvfl = get4byte(pDbPage->aData);
   48186     if( nextOvfl!=0 ){
   48187       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
   48188       if( rc!=SQLITE_OK ){
   48189         return rc;
   48190       }
   48191     }
   48192   }
   48193 
   48194   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
   48195   ** that it points at iFreePage. Also fix the pointer map entry for
   48196   ** iPtrPage.
   48197   */
   48198   if( eType!=PTRMAP_ROOTPAGE ){
   48199     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
   48200     if( rc!=SQLITE_OK ){
   48201       return rc;
   48202     }
   48203     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
   48204     if( rc!=SQLITE_OK ){
   48205       releasePage(pPtrPage);
   48206       return rc;
   48207     }
   48208     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
   48209     releasePage(pPtrPage);
   48210     if( rc==SQLITE_OK ){
   48211       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
   48212     }
   48213   }
   48214   return rc;
   48215 }
   48216 
   48217 /* Forward declaration required by incrVacuumStep(). */
   48218 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
   48219 
   48220 /*
   48221 ** Perform a single step of an incremental-vacuum. If successful,
   48222 ** return SQLITE_OK. If there is no work to do (and therefore no
   48223 ** point in calling this function again), return SQLITE_DONE.
   48224 **
   48225 ** More specificly, this function attempts to re-organize the
   48226 ** database so that the last page of the file currently in use
   48227 ** is no longer in use.
   48228 **
   48229 ** If the nFin parameter is non-zero, this function assumes
   48230 ** that the caller will keep calling incrVacuumStep() until
   48231 ** it returns SQLITE_DONE or an error, and that nFin is the
   48232 ** number of pages the database file will contain after this
   48233 ** process is complete.  If nFin is zero, it is assumed that
   48234 ** incrVacuumStep() will be called a finite amount of times
   48235 ** which may or may not empty the freelist.  A full autovacuum
   48236 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
   48237 */
   48238 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
   48239   Pgno nFreeList;           /* Number of pages still on the free-list */
   48240   int rc;
   48241 
   48242   assert( sqlite3_mutex_held(pBt->mutex) );
   48243   assert( iLastPg>nFin );
   48244 
   48245   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
   48246     u8 eType;
   48247     Pgno iPtrPage;
   48248 
   48249     nFreeList = get4byte(&pBt->pPage1->aData[36]);
   48250     if( nFreeList==0 ){
   48251       return SQLITE_DONE;
   48252     }
   48253 
   48254     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
   48255     if( rc!=SQLITE_OK ){
   48256       return rc;
   48257     }
   48258     if( eType==PTRMAP_ROOTPAGE ){
   48259       return SQLITE_CORRUPT_BKPT;
   48260     }
   48261 
   48262     if( eType==PTRMAP_FREEPAGE ){
   48263       if( nFin==0 ){
   48264         /* Remove the page from the files free-list. This is not required
   48265         ** if nFin is non-zero. In that case, the free-list will be
   48266         ** truncated to zero after this function returns, so it doesn't
   48267         ** matter if it still contains some garbage entries.
   48268         */
   48269         Pgno iFreePg;
   48270         MemPage *pFreePg;
   48271         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
   48272         if( rc!=SQLITE_OK ){
   48273           return rc;
   48274         }
   48275         assert( iFreePg==iLastPg );
   48276         releasePage(pFreePg);
   48277       }
   48278     } else {
   48279       Pgno iFreePg;             /* Index of free page to move pLastPg to */
   48280       MemPage *pLastPg;
   48281 
   48282       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
   48283       if( rc!=SQLITE_OK ){
   48284         return rc;
   48285       }
   48286 
   48287       /* If nFin is zero, this loop runs exactly once and page pLastPg
   48288       ** is swapped with the first free page pulled off the free list.
   48289       **
   48290       ** On the other hand, if nFin is greater than zero, then keep
   48291       ** looping until a free-page located within the first nFin pages
   48292       ** of the file is found.
   48293       */
   48294       do {
   48295         MemPage *pFreePg;
   48296         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
   48297         if( rc!=SQLITE_OK ){
   48298           releasePage(pLastPg);
   48299           return rc;
   48300         }
   48301         releasePage(pFreePg);
   48302       }while( nFin!=0 && iFreePg>nFin );
   48303       assert( iFreePg<iLastPg );
   48304 
   48305       rc = sqlite3PagerWrite(pLastPg->pDbPage);
   48306       if( rc==SQLITE_OK ){
   48307         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
   48308       }
   48309       releasePage(pLastPg);
   48310       if( rc!=SQLITE_OK ){
   48311         return rc;
   48312       }
   48313     }
   48314   }
   48315 
   48316   if( nFin==0 ){
   48317     iLastPg--;
   48318     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
   48319       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
   48320         MemPage *pPg;
   48321         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
   48322         if( rc!=SQLITE_OK ){
   48323           return rc;
   48324         }
   48325         rc = sqlite3PagerWrite(pPg->pDbPage);
   48326         releasePage(pPg);
   48327         if( rc!=SQLITE_OK ){
   48328           return rc;
   48329         }
   48330       }
   48331       iLastPg--;
   48332     }
   48333     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
   48334     pBt->nPage = iLastPg;
   48335   }
   48336   return SQLITE_OK;
   48337 }
   48338 
   48339 /*
   48340 ** A write-transaction must be opened before calling this function.
   48341 ** It performs a single unit of work towards an incremental vacuum.
   48342 **
   48343 ** If the incremental vacuum is finished after this function has run,
   48344 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
   48345 ** SQLITE_OK is returned. Otherwise an SQLite error code.
   48346 */
   48347 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   48348   int rc;
   48349   BtShared *pBt = p->pBt;
   48350 
   48351   sqlite3BtreeEnter(p);
   48352   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
   48353   if( !pBt->autoVacuum ){
   48354     rc = SQLITE_DONE;
   48355   }else{
   48356     invalidateAllOverflowCache(pBt);
   48357     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
   48358     if( rc==SQLITE_OK ){
   48359       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   48360       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
   48361     }
   48362   }
   48363   sqlite3BtreeLeave(p);
   48364   return rc;
   48365 }
   48366 
   48367 /*
   48368 ** This routine is called prior to sqlite3PagerCommit when a transaction
   48369 ** is commited for an auto-vacuum database.
   48370 **
   48371 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
   48372 ** the database file should be truncated to during the commit process.
   48373 ** i.e. the database has been reorganized so that only the first *pnTrunc
   48374 ** pages are in use.
   48375 */
   48376 static int autoVacuumCommit(BtShared *pBt){
   48377   int rc = SQLITE_OK;
   48378   Pager *pPager = pBt->pPager;
   48379   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
   48380 
   48381   assert( sqlite3_mutex_held(pBt->mutex) );
   48382   invalidateAllOverflowCache(pBt);
   48383   assert(pBt->autoVacuum);
   48384   if( !pBt->incrVacuum ){
   48385     Pgno nFin;         /* Number of pages in database after autovacuuming */
   48386     Pgno nFree;        /* Number of pages on the freelist initially */
   48387     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
   48388     Pgno iFree;        /* The next page to be freed */
   48389     int nEntry;        /* Number of entries on one ptrmap page */
   48390     Pgno nOrig;        /* Database size before freeing */
   48391 
   48392     nOrig = btreePagecount(pBt);
   48393     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
   48394       /* It is not possible to create a database for which the final page
   48395       ** is either a pointer-map page or the pending-byte page. If one
   48396       ** is encountered, this indicates corruption.
   48397       */
   48398       return SQLITE_CORRUPT_BKPT;
   48399     }
   48400 
   48401     nFree = get4byte(&pBt->pPage1->aData[36]);
   48402     nEntry = pBt->usableSize/5;
   48403     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
   48404     nFin = nOrig - nFree - nPtrmap;
   48405     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
   48406       nFin--;
   48407     }
   48408     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
   48409       nFin--;
   48410     }
   48411     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
   48412 
   48413     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
   48414       rc = incrVacuumStep(pBt, nFin, iFree);
   48415     }
   48416     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
   48417       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   48418       put4byte(&pBt->pPage1->aData[32], 0);
   48419       put4byte(&pBt->pPage1->aData[36], 0);
   48420       put4byte(&pBt->pPage1->aData[28], nFin);
   48421       sqlite3PagerTruncateImage(pBt->pPager, nFin);
   48422       pBt->nPage = nFin;
   48423     }
   48424     if( rc!=SQLITE_OK ){
   48425       sqlite3PagerRollback(pPager);
   48426     }
   48427   }
   48428 
   48429   assert( nRef==sqlite3PagerRefcount(pPager) );
   48430   return rc;
   48431 }
   48432 
   48433 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
   48434 # define setChildPtrmaps(x) SQLITE_OK
   48435 #endif
   48436 
   48437 /*
   48438 ** This routine does the first phase of a two-phase commit.  This routine
   48439 ** causes a rollback journal to be created (if it does not already exist)
   48440 ** and populated with enough information so that if a power loss occurs
   48441 ** the database can be restored to its original state by playing back
   48442 ** the journal.  Then the contents of the journal are flushed out to
   48443 ** the disk.  After the journal is safely on oxide, the changes to the
   48444 ** database are written into the database file and flushed to oxide.
   48445 ** At the end of this call, the rollback journal still exists on the
   48446 ** disk and we are still holding all locks, so the transaction has not
   48447 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
   48448 ** commit process.
   48449 **
   48450 ** This call is a no-op if no write-transaction is currently active on pBt.
   48451 **
   48452 ** Otherwise, sync the database file for the btree pBt. zMaster points to
   48453 ** the name of a master journal file that should be written into the
   48454 ** individual journal file, or is NULL, indicating no master journal file
   48455 ** (single database transaction).
   48456 **
   48457 ** When this is called, the master journal should already have been
   48458 ** created, populated with this journal pointer and synced to disk.
   48459 **
   48460 ** Once this is routine has returned, the only thing required to commit
   48461 ** the write-transaction for this database file is to delete the journal.
   48462 */
   48463 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
   48464   int rc = SQLITE_OK;
   48465   if( p->inTrans==TRANS_WRITE ){
   48466     BtShared *pBt = p->pBt;
   48467     sqlite3BtreeEnter(p);
   48468 #ifndef SQLITE_OMIT_AUTOVACUUM
   48469     if( pBt->autoVacuum ){
   48470       rc = autoVacuumCommit(pBt);
   48471       if( rc!=SQLITE_OK ){
   48472         sqlite3BtreeLeave(p);
   48473         return rc;
   48474       }
   48475     }
   48476 #endif
   48477     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
   48478     sqlite3BtreeLeave(p);
   48479   }
   48480   return rc;
   48481 }
   48482 
   48483 /*
   48484 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
   48485 ** at the conclusion of a transaction.
   48486 */
   48487 static void btreeEndTransaction(Btree *p){
   48488   BtShared *pBt = p->pBt;
   48489   assert( sqlite3BtreeHoldsMutex(p) );
   48490 
   48491   btreeClearHasContent(pBt);
   48492   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
   48493     /* If there are other active statements that belong to this database
   48494     ** handle, downgrade to a read-only transaction. The other statements
   48495     ** may still be reading from the database.  */
   48496     downgradeAllSharedCacheTableLocks(p);
   48497     p->inTrans = TRANS_READ;
   48498   }else{
   48499     /* If the handle had any kind of transaction open, decrement the
   48500     ** transaction count of the shared btree. If the transaction count
   48501     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
   48502     ** call below will unlock the pager.  */
   48503     if( p->inTrans!=TRANS_NONE ){
   48504       clearAllSharedCacheTableLocks(p);
   48505       pBt->nTransaction--;
   48506       if( 0==pBt->nTransaction ){
   48507         pBt->inTransaction = TRANS_NONE;
   48508       }
   48509     }
   48510 
   48511     /* Set the current transaction state to TRANS_NONE and unlock the
   48512     ** pager if this call closed the only read or write transaction.  */
   48513     p->inTrans = TRANS_NONE;
   48514     unlockBtreeIfUnused(pBt);
   48515   }
   48516 
   48517   btreeIntegrity(p);
   48518 }
   48519 
   48520 /*
   48521 ** Commit the transaction currently in progress.
   48522 **
   48523 ** This routine implements the second phase of a 2-phase commit.  The
   48524 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
   48525 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
   48526 ** routine did all the work of writing information out to disk and flushing the
   48527 ** contents so that they are written onto the disk platter.  All this
   48528 ** routine has to do is delete or truncate or zero the header in the
   48529 ** the rollback journal (which causes the transaction to commit) and
   48530 ** drop locks.
   48531 **
   48532 ** This will release the write lock on the database file.  If there
   48533 ** are no active cursors, it also releases the read lock.
   48534 */
   48535 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
   48536 
   48537   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
   48538   sqlite3BtreeEnter(p);
   48539   btreeIntegrity(p);
   48540 
   48541   /* If the handle has a write-transaction open, commit the shared-btrees
   48542   ** transaction and set the shared state to TRANS_READ.
   48543   */
   48544   if( p->inTrans==TRANS_WRITE ){
   48545     int rc;
   48546     BtShared *pBt = p->pBt;
   48547     assert( pBt->inTransaction==TRANS_WRITE );
   48548     assert( pBt->nTransaction>0 );
   48549     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
   48550     if( rc!=SQLITE_OK ){
   48551       sqlite3BtreeLeave(p);
   48552       return rc;
   48553     }
   48554     pBt->inTransaction = TRANS_READ;
   48555   }
   48556 
   48557   btreeEndTransaction(p);
   48558   sqlite3BtreeLeave(p);
   48559   return SQLITE_OK;
   48560 }
   48561 
   48562 /*
   48563 ** Do both phases of a commit.
   48564 */
   48565 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
   48566   int rc;
   48567   sqlite3BtreeEnter(p);
   48568   rc = sqlite3BtreeCommitPhaseOne(p, 0);
   48569   if( rc==SQLITE_OK ){
   48570     rc = sqlite3BtreeCommitPhaseTwo(p);
   48571   }
   48572   sqlite3BtreeLeave(p);
   48573   return rc;
   48574 }
   48575 
   48576 #ifndef NDEBUG
   48577 /*
   48578 ** Return the number of write-cursors open on this handle. This is for use
   48579 ** in assert() expressions, so it is only compiled if NDEBUG is not
   48580 ** defined.
   48581 **
   48582 ** For the purposes of this routine, a write-cursor is any cursor that
   48583 ** is capable of writing to the databse.  That means the cursor was
   48584 ** originally opened for writing and the cursor has not be disabled
   48585 ** by having its state changed to CURSOR_FAULT.
   48586 */
   48587 static int countWriteCursors(BtShared *pBt){
   48588   BtCursor *pCur;
   48589   int r = 0;
   48590   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
   48591     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
   48592   }
   48593   return r;
   48594 }
   48595 #endif
   48596 
   48597 /*
   48598 ** This routine sets the state to CURSOR_FAULT and the error
   48599 ** code to errCode for every cursor on BtShared that pBtree
   48600 ** references.
   48601 **
   48602 ** Every cursor is tripped, including cursors that belong
   48603 ** to other database connections that happen to be sharing
   48604 ** the cache with pBtree.
   48605 **
   48606 ** This routine gets called when a rollback occurs.
   48607 ** All cursors using the same cache must be tripped
   48608 ** to prevent them from trying to use the btree after
   48609 ** the rollback.  The rollback may have deleted tables
   48610 ** or moved root pages, so it is not sufficient to
   48611 ** save the state of the cursor.  The cursor must be
   48612 ** invalidated.
   48613 */
   48614 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
   48615   BtCursor *p;
   48616   sqlite3BtreeEnter(pBtree);
   48617   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
   48618     int i;
   48619     sqlite3BtreeClearCursor(p);
   48620     p->eState = CURSOR_FAULT;
   48621     p->skipNext = errCode;
   48622     for(i=0; i<=p->iPage; i++){
   48623       releasePage(p->apPage[i]);
   48624       p->apPage[i] = 0;
   48625     }
   48626   }
   48627   sqlite3BtreeLeave(pBtree);
   48628 }
   48629 
   48630 /*
   48631 ** Rollback the transaction in progress.  All cursors will be
   48632 ** invalided by this operation.  Any attempt to use a cursor
   48633 ** that was open at the beginning of this operation will result
   48634 ** in an error.
   48635 **
   48636 ** This will release the write lock on the database file.  If there
   48637 ** are no active cursors, it also releases the read lock.
   48638 */
   48639 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
   48640   int rc;
   48641   BtShared *pBt = p->pBt;
   48642   MemPage *pPage1;
   48643 
   48644   sqlite3BtreeEnter(p);
   48645   rc = saveAllCursors(pBt, 0, 0);
   48646 #ifndef SQLITE_OMIT_SHARED_CACHE
   48647   if( rc!=SQLITE_OK ){
   48648     /* This is a horrible situation. An IO or malloc() error occurred whilst
   48649     ** trying to save cursor positions. If this is an automatic rollback (as
   48650     ** the result of a constraint, malloc() failure or IO error) then
   48651     ** the cache may be internally inconsistent (not contain valid trees) so
   48652     ** we cannot simply return the error to the caller. Instead, abort
   48653     ** all queries that may be using any of the cursors that failed to save.
   48654     */
   48655     sqlite3BtreeTripAllCursors(p, rc);
   48656   }
   48657 #endif
   48658   btreeIntegrity(p);
   48659 
   48660   if( p->inTrans==TRANS_WRITE ){
   48661     int rc2;
   48662 
   48663     assert( TRANS_WRITE==pBt->inTransaction );
   48664     rc2 = sqlite3PagerRollback(pBt->pPager);
   48665     if( rc2!=SQLITE_OK ){
   48666       rc = rc2;
   48667     }
   48668 
   48669     /* The rollback may have destroyed the pPage1->aData value.  So
   48670     ** call btreeGetPage() on page 1 again to make
   48671     ** sure pPage1->aData is set correctly. */
   48672     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
   48673       int nPage = get4byte(28+(u8*)pPage1->aData);
   48674       testcase( nPage==0 );
   48675       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
   48676       testcase( pBt->nPage!=nPage );
   48677       pBt->nPage = nPage;
   48678       releasePage(pPage1);
   48679     }
   48680     assert( countWriteCursors(pBt)==0 );
   48681     pBt->inTransaction = TRANS_READ;
   48682   }
   48683 
   48684   btreeEndTransaction(p);
   48685   sqlite3BtreeLeave(p);
   48686   return rc;
   48687 }
   48688 
   48689 /*
   48690 ** Start a statement subtransaction. The subtransaction can can be rolled
   48691 ** back independently of the main transaction. You must start a transaction
   48692 ** before starting a subtransaction. The subtransaction is ended automatically
   48693 ** if the main transaction commits or rolls back.
   48694 **
   48695 ** Statement subtransactions are used around individual SQL statements
   48696 ** that are contained within a BEGIN...COMMIT block.  If a constraint
   48697 ** error occurs within the statement, the effect of that one statement
   48698 ** can be rolled back without having to rollback the entire transaction.
   48699 **
   48700 ** A statement sub-transaction is implemented as an anonymous savepoint. The
   48701 ** value passed as the second parameter is the total number of savepoints,
   48702 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
   48703 ** are no active savepoints and no other statement-transactions open,
   48704 ** iStatement is 1. This anonymous savepoint can be released or rolled back
   48705 ** using the sqlite3BtreeSavepoint() function.
   48706 */
   48707 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
   48708   int rc;
   48709   BtShared *pBt = p->pBt;
   48710   sqlite3BtreeEnter(p);
   48711   assert( p->inTrans==TRANS_WRITE );
   48712   assert( pBt->readOnly==0 );
   48713   assert( iStatement>0 );
   48714   assert( iStatement>p->db->nSavepoint );
   48715   assert( pBt->inTransaction==TRANS_WRITE );
   48716   /* At the pager level, a statement transaction is a savepoint with
   48717   ** an index greater than all savepoints created explicitly using
   48718   ** SQL statements. It is illegal to open, release or rollback any
   48719   ** such savepoints while the statement transaction savepoint is active.
   48720   */
   48721   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
   48722   sqlite3BtreeLeave(p);
   48723   return rc;
   48724 }
   48725 
   48726 /*
   48727 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
   48728 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
   48729 ** savepoint identified by parameter iSavepoint, depending on the value
   48730 ** of op.
   48731 **
   48732 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
   48733 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
   48734 ** contents of the entire transaction are rolled back. This is different
   48735 ** from a normal transaction rollback, as no locks are released and the
   48736 ** transaction remains open.
   48737 */
   48738 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
   48739   int rc = SQLITE_OK;
   48740   if( p && p->inTrans==TRANS_WRITE ){
   48741     BtShared *pBt = p->pBt;
   48742     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
   48743     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
   48744     sqlite3BtreeEnter(p);
   48745     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
   48746     if( rc==SQLITE_OK ){
   48747       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
   48748       rc = newDatabase(pBt);
   48749       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
   48750 
   48751       /* The database size was written into the offset 28 of the header
   48752       ** when the transaction started, so we know that the value at offset
   48753       ** 28 is nonzero. */
   48754       assert( pBt->nPage>0 );
   48755     }
   48756     sqlite3BtreeLeave(p);
   48757   }
   48758   return rc;
   48759 }
   48760 
   48761 /*
   48762 ** Create a new cursor for the BTree whose root is on the page
   48763 ** iTable. If a read-only cursor is requested, it is assumed that
   48764 ** the caller already has at least a read-only transaction open
   48765 ** on the database already. If a write-cursor is requested, then
   48766 ** the caller is assumed to have an open write transaction.
   48767 **
   48768 ** If wrFlag==0, then the cursor can only be used for reading.
   48769 ** If wrFlag==1, then the cursor can be used for reading or for
   48770 ** writing if other conditions for writing are also met.  These
   48771 ** are the conditions that must be met in order for writing to
   48772 ** be allowed:
   48773 **
   48774 ** 1:  The cursor must have been opened with wrFlag==1
   48775 **
   48776 ** 2:  Other database connections that share the same pager cache
   48777 **     but which are not in the READ_UNCOMMITTED state may not have
   48778 **     cursors open with wrFlag==0 on the same table.  Otherwise
   48779 **     the changes made by this write cursor would be visible to
   48780 **     the read cursors in the other database connection.
   48781 **
   48782 ** 3:  The database must be writable (not on read-only media)
   48783 **
   48784 ** 4:  There must be an active transaction.
   48785 **
   48786 ** No checking is done to make sure that page iTable really is the
   48787 ** root page of a b-tree.  If it is not, then the cursor acquired
   48788 ** will not work correctly.
   48789 **
   48790 ** It is assumed that the sqlite3BtreeCursorZero() has been called
   48791 ** on pCur to initialize the memory space prior to invoking this routine.
   48792 */
   48793 static int btreeCursor(
   48794   Btree *p,                              /* The btree */
   48795   int iTable,                            /* Root page of table to open */
   48796   int wrFlag,                            /* 1 to write. 0 read-only */
   48797   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   48798   BtCursor *pCur                         /* Space for new cursor */
   48799 ){
   48800   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
   48801 
   48802   assert( sqlite3BtreeHoldsMutex(p) );
   48803   assert( wrFlag==0 || wrFlag==1 );
   48804 
   48805   /* The following assert statements verify that if this is a sharable
   48806   ** b-tree database, the connection is holding the required table locks,
   48807   ** and that no other connection has any open cursor that conflicts with
   48808   ** this lock.  */
   48809   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
   48810   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
   48811 
   48812   /* Assert that the caller has opened the required transaction. */
   48813   assert( p->inTrans>TRANS_NONE );
   48814   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
   48815   assert( pBt->pPage1 && pBt->pPage1->aData );
   48816 
   48817   if( NEVER(wrFlag && pBt->readOnly) ){
   48818     return SQLITE_READONLY;
   48819   }
   48820   if( iTable==1 && btreePagecount(pBt)==0 ){
   48821     return SQLITE_EMPTY;
   48822   }
   48823 
   48824   /* Now that no other errors can occur, finish filling in the BtCursor
   48825   ** variables and link the cursor into the BtShared list.  */
   48826   pCur->pgnoRoot = (Pgno)iTable;
   48827   pCur->iPage = -1;
   48828   pCur->pKeyInfo = pKeyInfo;
   48829   pCur->pBtree = p;
   48830   pCur->pBt = pBt;
   48831   pCur->wrFlag = (u8)wrFlag;
   48832   pCur->pNext = pBt->pCursor;
   48833   if( pCur->pNext ){
   48834     pCur->pNext->pPrev = pCur;
   48835   }
   48836   pBt->pCursor = pCur;
   48837   pCur->eState = CURSOR_INVALID;
   48838   pCur->cachedRowid = 0;
   48839   return SQLITE_OK;
   48840 }
   48841 SQLITE_PRIVATE int sqlite3BtreeCursor(
   48842   Btree *p,                                   /* The btree */
   48843   int iTable,                                 /* Root page of table to open */
   48844   int wrFlag,                                 /* 1 to write. 0 read-only */
   48845   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   48846   BtCursor *pCur                              /* Write new cursor here */
   48847 ){
   48848   int rc;
   48849   sqlite3BtreeEnter(p);
   48850   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   48851   sqlite3BtreeLeave(p);
   48852   return rc;
   48853 }
   48854 
   48855 /*
   48856 ** Return the size of a BtCursor object in bytes.
   48857 **
   48858 ** This interfaces is needed so that users of cursors can preallocate
   48859 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
   48860 ** to users so they cannot do the sizeof() themselves - they must call
   48861 ** this routine.
   48862 */
   48863 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
   48864   return ROUND8(sizeof(BtCursor));
   48865 }
   48866 
   48867 /*
   48868 ** Initialize memory that will be converted into a BtCursor object.
   48869 **
   48870 ** The simple approach here would be to memset() the entire object
   48871 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
   48872 ** do not need to be zeroed and they are large, so we can save a lot
   48873 ** of run-time by skipping the initialization of those elements.
   48874 */
   48875 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
   48876   memset(p, 0, offsetof(BtCursor, iPage));
   48877 }
   48878 
   48879 /*
   48880 ** Set the cached rowid value of every cursor in the same database file
   48881 ** as pCur and having the same root page number as pCur.  The value is
   48882 ** set to iRowid.
   48883 **
   48884 ** Only positive rowid values are considered valid for this cache.
   48885 ** The cache is initialized to zero, indicating an invalid cache.
   48886 ** A btree will work fine with zero or negative rowids.  We just cannot
   48887 ** cache zero or negative rowids, which means tables that use zero or
   48888 ** negative rowids might run a little slower.  But in practice, zero
   48889 ** or negative rowids are very uncommon so this should not be a problem.
   48890 */
   48891 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
   48892   BtCursor *p;
   48893   for(p=pCur->pBt->pCursor; p; p=p->pNext){
   48894     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
   48895   }
   48896   assert( pCur->cachedRowid==iRowid );
   48897 }
   48898 
   48899 /*
   48900 ** Return the cached rowid for the given cursor.  A negative or zero
   48901 ** return value indicates that the rowid cache is invalid and should be
   48902 ** ignored.  If the rowid cache has never before been set, then a
   48903 ** zero is returned.
   48904 */
   48905 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
   48906   return pCur->cachedRowid;
   48907 }
   48908 
   48909 /*
   48910 ** Close a cursor.  The read lock on the database file is released
   48911 ** when the last cursor is closed.
   48912 */
   48913 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
   48914   Btree *pBtree = pCur->pBtree;
   48915   if( pBtree ){
   48916     int i;
   48917     BtShared *pBt = pCur->pBt;
   48918     sqlite3BtreeEnter(pBtree);
   48919     sqlite3BtreeClearCursor(pCur);
   48920     if( pCur->pPrev ){
   48921       pCur->pPrev->pNext = pCur->pNext;
   48922     }else{
   48923       pBt->pCursor = pCur->pNext;
   48924     }
   48925     if( pCur->pNext ){
   48926       pCur->pNext->pPrev = pCur->pPrev;
   48927     }
   48928     for(i=0; i<=pCur->iPage; i++){
   48929       releasePage(pCur->apPage[i]);
   48930     }
   48931     unlockBtreeIfUnused(pBt);
   48932     invalidateOverflowCache(pCur);
   48933     /* sqlite3_free(pCur); */
   48934     sqlite3BtreeLeave(pBtree);
   48935   }
   48936   return SQLITE_OK;
   48937 }
   48938 
   48939 /*
   48940 ** Make sure the BtCursor* given in the argument has a valid
   48941 ** BtCursor.info structure.  If it is not already valid, call
   48942 ** btreeParseCell() to fill it in.
   48943 **
   48944 ** BtCursor.info is a cache of the information in the current cell.
   48945 ** Using this cache reduces the number of calls to btreeParseCell().
   48946 **
   48947 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
   48948 ** compiler to crash when getCellInfo() is implemented as a macro.
   48949 ** But there is a measureable speed advantage to using the macro on gcc
   48950 ** (when less compiler optimizations like -Os or -O0 are used and the
   48951 ** compiler is not doing agressive inlining.)  So we use a real function
   48952 ** for MSVC and a macro for everything else.  Ticket #2457.
   48953 */
   48954 #ifndef NDEBUG
   48955   static void assertCellInfo(BtCursor *pCur){
   48956     CellInfo info;
   48957     int iPage = pCur->iPage;
   48958     memset(&info, 0, sizeof(info));
   48959     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
   48960     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
   48961   }
   48962 #else
   48963   #define assertCellInfo(x)
   48964 #endif
   48965 #ifdef _MSC_VER
   48966   /* Use a real function in MSVC to work around bugs in that compiler. */
   48967   static void getCellInfo(BtCursor *pCur){
   48968     if( pCur->info.nSize==0 ){
   48969       int iPage = pCur->iPage;
   48970       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
   48971       pCur->validNKey = 1;
   48972     }else{
   48973       assertCellInfo(pCur);
   48974     }
   48975   }
   48976 #else /* if not _MSC_VER */
   48977   /* Use a macro in all other compilers so that the function is inlined */
   48978 #define getCellInfo(pCur)                                                      \
   48979   if( pCur->info.nSize==0 ){                                                   \
   48980     int iPage = pCur->iPage;                                                   \
   48981     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
   48982     pCur->validNKey = 1;                                                       \
   48983   }else{                                                                       \
   48984     assertCellInfo(pCur);                                                      \
   48985   }
   48986 #endif /* _MSC_VER */
   48987 
   48988 #ifndef NDEBUG  /* The next routine used only within assert() statements */
   48989 /*
   48990 ** Return true if the given BtCursor is valid.  A valid cursor is one
   48991 ** that is currently pointing to a row in a (non-empty) table.
   48992 ** This is a verification routine is used only within assert() statements.
   48993 */
   48994 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
   48995   return pCur && pCur->eState==CURSOR_VALID;
   48996 }
   48997 #endif /* NDEBUG */
   48998 
   48999 /*
   49000 ** Set *pSize to the size of the buffer needed to hold the value of
   49001 ** the key for the current entry.  If the cursor is not pointing
   49002 ** to a valid entry, *pSize is set to 0.
   49003 **
   49004 ** For a table with the INTKEY flag set, this routine returns the key
   49005 ** itself, not the number of bytes in the key.
   49006 **
   49007 ** The caller must position the cursor prior to invoking this routine.
   49008 **
   49009 ** This routine cannot fail.  It always returns SQLITE_OK.
   49010 */
   49011 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
   49012   assert( cursorHoldsMutex(pCur) );
   49013   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
   49014   if( pCur->eState!=CURSOR_VALID ){
   49015     *pSize = 0;
   49016   }else{
   49017     getCellInfo(pCur);
   49018     *pSize = pCur->info.nKey;
   49019   }
   49020   return SQLITE_OK;
   49021 }
   49022 
   49023 /*
   49024 ** Set *pSize to the number of bytes of data in the entry the
   49025 ** cursor currently points to.
   49026 **
   49027 ** The caller must guarantee that the cursor is pointing to a non-NULL
   49028 ** valid entry.  In other words, the calling procedure must guarantee
   49029 ** that the cursor has Cursor.eState==CURSOR_VALID.
   49030 **
   49031 ** Failure is not possible.  This function always returns SQLITE_OK.
   49032 ** It might just as well be a procedure (returning void) but we continue
   49033 ** to return an integer result code for historical reasons.
   49034 */
   49035 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
   49036   assert( cursorHoldsMutex(pCur) );
   49037   assert( pCur->eState==CURSOR_VALID );
   49038   getCellInfo(pCur);
   49039   *pSize = pCur->info.nData;
   49040   return SQLITE_OK;
   49041 }
   49042 
   49043 /*
   49044 ** Given the page number of an overflow page in the database (parameter
   49045 ** ovfl), this function finds the page number of the next page in the
   49046 ** linked list of overflow pages. If possible, it uses the auto-vacuum
   49047 ** pointer-map data instead of reading the content of page ovfl to do so.
   49048 **
   49049 ** If an error occurs an SQLite error code is returned. Otherwise:
   49050 **
   49051 ** The page number of the next overflow page in the linked list is
   49052 ** written to *pPgnoNext. If page ovfl is the last page in its linked
   49053 ** list, *pPgnoNext is set to zero.
   49054 **
   49055 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
   49056 ** to page number pOvfl was obtained, then *ppPage is set to point to that
   49057 ** reference. It is the responsibility of the caller to call releasePage()
   49058 ** on *ppPage to free the reference. In no reference was obtained (because
   49059 ** the pointer-map was used to obtain the value for *pPgnoNext), then
   49060 ** *ppPage is set to zero.
   49061 */
   49062 static int getOverflowPage(
   49063   BtShared *pBt,               /* The database file */
   49064   Pgno ovfl,                   /* Current overflow page number */
   49065   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
   49066   Pgno *pPgnoNext              /* OUT: Next overflow page number */
   49067 ){
   49068   Pgno next = 0;
   49069   MemPage *pPage = 0;
   49070   int rc = SQLITE_OK;
   49071 
   49072   assert( sqlite3_mutex_held(pBt->mutex) );
   49073   assert(pPgnoNext);
   49074 
   49075 #ifndef SQLITE_OMIT_AUTOVACUUM
   49076   /* Try to find the next page in the overflow list using the
   49077   ** autovacuum pointer-map pages. Guess that the next page in
   49078   ** the overflow list is page number (ovfl+1). If that guess turns
   49079   ** out to be wrong, fall back to loading the data of page
   49080   ** number ovfl to determine the next page number.
   49081   */
   49082   if( pBt->autoVacuum ){
   49083     Pgno pgno;
   49084     Pgno iGuess = ovfl+1;
   49085     u8 eType;
   49086 
   49087     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
   49088       iGuess++;
   49089     }
   49090 
   49091     if( iGuess<=btreePagecount(pBt) ){
   49092       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
   49093       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
   49094         next = iGuess;
   49095         rc = SQLITE_DONE;
   49096       }
   49097     }
   49098   }
   49099 #endif
   49100 
   49101   assert( next==0 || rc==SQLITE_DONE );
   49102   if( rc==SQLITE_OK ){
   49103     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
   49104     assert( rc==SQLITE_OK || pPage==0 );
   49105     if( rc==SQLITE_OK ){
   49106       next = get4byte(pPage->aData);
   49107     }
   49108   }
   49109 
   49110   *pPgnoNext = next;
   49111   if( ppPage ){
   49112     *ppPage = pPage;
   49113   }else{
   49114     releasePage(pPage);
   49115   }
   49116   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   49117 }
   49118 
   49119 /*
   49120 ** Copy data from a buffer to a page, or from a page to a buffer.
   49121 **
   49122 ** pPayload is a pointer to data stored on database page pDbPage.
   49123 ** If argument eOp is false, then nByte bytes of data are copied
   49124 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
   49125 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
   49126 ** of data are copied from the buffer pBuf to pPayload.
   49127 **
   49128 ** SQLITE_OK is returned on success, otherwise an error code.
   49129 */
   49130 static int copyPayload(
   49131   void *pPayload,           /* Pointer to page data */
   49132   void *pBuf,               /* Pointer to buffer */
   49133   int nByte,                /* Number of bytes to copy */
   49134   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
   49135   DbPage *pDbPage           /* Page containing pPayload */
   49136 ){
   49137   if( eOp ){
   49138     /* Copy data from buffer to page (a write operation) */
   49139     int rc = sqlite3PagerWrite(pDbPage);
   49140     if( rc!=SQLITE_OK ){
   49141       return rc;
   49142     }
   49143     memcpy(pPayload, pBuf, nByte);
   49144   }else{
   49145     /* Copy data from page to buffer (a read operation) */
   49146     memcpy(pBuf, pPayload, nByte);
   49147   }
   49148   return SQLITE_OK;
   49149 }
   49150 
   49151 /*
   49152 ** This function is used to read or overwrite payload information
   49153 ** for the entry that the pCur cursor is pointing to. If the eOp
   49154 ** parameter is 0, this is a read operation (data copied into
   49155 ** buffer pBuf). If it is non-zero, a write (data copied from
   49156 ** buffer pBuf).
   49157 **
   49158 ** A total of "amt" bytes are read or written beginning at "offset".
   49159 ** Data is read to or from the buffer pBuf.
   49160 **
   49161 ** The content being read or written might appear on the main page
   49162 ** or be scattered out on multiple overflow pages.
   49163 **
   49164 ** If the BtCursor.isIncrblobHandle flag is set, and the current
   49165 ** cursor entry uses one or more overflow pages, this function
   49166 ** allocates space for and lazily popluates the overflow page-list
   49167 ** cache array (BtCursor.aOverflow). Subsequent calls use this
   49168 ** cache to make seeking to the supplied offset more efficient.
   49169 **
   49170 ** Once an overflow page-list cache has been allocated, it may be
   49171 ** invalidated if some other cursor writes to the same table, or if
   49172 ** the cursor is moved to a different row. Additionally, in auto-vacuum
   49173 ** mode, the following events may invalidate an overflow page-list cache.
   49174 **
   49175 **   * An incremental vacuum,
   49176 **   * A commit in auto_vacuum="full" mode,
   49177 **   * Creating a table (may require moving an overflow page).
   49178 */
   49179 static int accessPayload(
   49180   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   49181   u32 offset,          /* Begin reading this far into payload */
   49182   u32 amt,             /* Read this many bytes */
   49183   unsigned char *pBuf, /* Write the bytes into this buffer */
   49184   int eOp              /* zero to read. non-zero to write. */
   49185 ){
   49186   unsigned char *aPayload;
   49187   int rc = SQLITE_OK;
   49188   u32 nKey;
   49189   int iIdx = 0;
   49190   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
   49191   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
   49192 
   49193   assert( pPage );
   49194   assert( pCur->eState==CURSOR_VALID );
   49195   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   49196   assert( cursorHoldsMutex(pCur) );
   49197 
   49198   getCellInfo(pCur);
   49199   aPayload = pCur->info.pCell + pCur->info.nHeader;
   49200   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
   49201 
   49202   if( NEVER(offset+amt > nKey+pCur->info.nData)
   49203    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
   49204   ){
   49205     /* Trying to read or write past the end of the data is an error */
   49206     return SQLITE_CORRUPT_BKPT;
   49207   }
   49208 
   49209   /* Check if data must be read/written to/from the btree page itself. */
   49210   if( offset<pCur->info.nLocal ){
   49211     int a = amt;
   49212     if( a+offset>pCur->info.nLocal ){
   49213       a = pCur->info.nLocal - offset;
   49214     }
   49215     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
   49216     offset = 0;
   49217     pBuf += a;
   49218     amt -= a;
   49219   }else{
   49220     offset -= pCur->info.nLocal;
   49221   }
   49222 
   49223   if( rc==SQLITE_OK && amt>0 ){
   49224     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
   49225     Pgno nextPage;
   49226 
   49227     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
   49228 
   49229 #ifndef SQLITE_OMIT_INCRBLOB
   49230     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
   49231     ** has not been allocated, allocate it now. The array is sized at
   49232     ** one entry for each overflow page in the overflow chain. The
   49233     ** page number of the first overflow page is stored in aOverflow[0],
   49234     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
   49235     ** (the cache is lazily populated).
   49236     */
   49237     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
   49238       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
   49239       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
   49240       /* nOvfl is always positive.  If it were zero, fetchPayload would have
   49241       ** been used instead of this routine. */
   49242       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
   49243         rc = SQLITE_NOMEM;
   49244       }
   49245     }
   49246 
   49247     /* If the overflow page-list cache has been allocated and the
   49248     ** entry for the first required overflow page is valid, skip
   49249     ** directly to it.
   49250     */
   49251     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
   49252       iIdx = (offset/ovflSize);
   49253       nextPage = pCur->aOverflow[iIdx];
   49254       offset = (offset%ovflSize);
   49255     }
   49256 #endif
   49257 
   49258     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
   49259 
   49260 #ifndef SQLITE_OMIT_INCRBLOB
   49261       /* If required, populate the overflow page-list cache. */
   49262       if( pCur->aOverflow ){
   49263         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
   49264         pCur->aOverflow[iIdx] = nextPage;
   49265       }
   49266 #endif
   49267 
   49268       if( offset>=ovflSize ){
   49269         /* The only reason to read this page is to obtain the page
   49270         ** number for the next page in the overflow chain. The page
   49271         ** data is not required. So first try to lookup the overflow
   49272         ** page-list cache, if any, then fall back to the getOverflowPage()
   49273         ** function.
   49274         */
   49275 #ifndef SQLITE_OMIT_INCRBLOB
   49276         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
   49277           nextPage = pCur->aOverflow[iIdx+1];
   49278         } else
   49279 #endif
   49280           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
   49281         offset -= ovflSize;
   49282       }else{
   49283         /* Need to read this page properly. It contains some of the
   49284         ** range of data that is being read (eOp==0) or written (eOp!=0).
   49285         */
   49286         DbPage *pDbPage;
   49287         int a = amt;
   49288         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
   49289         if( rc==SQLITE_OK ){
   49290           aPayload = sqlite3PagerGetData(pDbPage);
   49291           nextPage = get4byte(aPayload);
   49292           if( a + offset > ovflSize ){
   49293             a = ovflSize - offset;
   49294           }
   49295           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
   49296           sqlite3PagerUnref(pDbPage);
   49297           offset = 0;
   49298           amt -= a;
   49299           pBuf += a;
   49300         }
   49301       }
   49302     }
   49303   }
   49304 
   49305   if( rc==SQLITE_OK && amt>0 ){
   49306     return SQLITE_CORRUPT_BKPT;
   49307   }
   49308   return rc;
   49309 }
   49310 
   49311 /*
   49312 ** Read part of the key associated with cursor pCur.  Exactly
   49313 ** "amt" bytes will be transfered into pBuf[].  The transfer
   49314 ** begins at "offset".
   49315 **
   49316 ** The caller must ensure that pCur is pointing to a valid row
   49317 ** in the table.
   49318 **
   49319 ** Return SQLITE_OK on success or an error code if anything goes
   49320 ** wrong.  An error is returned if "offset+amt" is larger than
   49321 ** the available payload.
   49322 */
   49323 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   49324   assert( cursorHoldsMutex(pCur) );
   49325   assert( pCur->eState==CURSOR_VALID );
   49326   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   49327   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   49328   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
   49329 }
   49330 
   49331 /*
   49332 ** Read part of the data associated with cursor pCur.  Exactly
   49333 ** "amt" bytes will be transfered into pBuf[].  The transfer
   49334 ** begins at "offset".
   49335 **
   49336 ** Return SQLITE_OK on success or an error code if anything goes
   49337 ** wrong.  An error is returned if "offset+amt" is larger than
   49338 ** the available payload.
   49339 */
   49340 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
   49341   int rc;
   49342 
   49343 #ifndef SQLITE_OMIT_INCRBLOB
   49344   if ( pCur->eState==CURSOR_INVALID ){
   49345     return SQLITE_ABORT;
   49346   }
   49347 #endif
   49348 
   49349   assert( cursorHoldsMutex(pCur) );
   49350   rc = restoreCursorPosition(pCur);
   49351   if( rc==SQLITE_OK ){
   49352     assert( pCur->eState==CURSOR_VALID );
   49353     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
   49354     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   49355     rc = accessPayload(pCur, offset, amt, pBuf, 0);
   49356   }
   49357   return rc;
   49358 }
   49359 
   49360 /*
   49361 ** Return a pointer to payload information from the entry that the
   49362 ** pCur cursor is pointing to.  The pointer is to the beginning of
   49363 ** the key if skipKey==0 and it points to the beginning of data if
   49364 ** skipKey==1.  The number of bytes of available key/data is written
   49365 ** into *pAmt.  If *pAmt==0, then the value returned will not be
   49366 ** a valid pointer.
   49367 **
   49368 ** This routine is an optimization.  It is common for the entire key
   49369 ** and data to fit on the local page and for there to be no overflow
   49370 ** pages.  When that is so, this routine can be used to access the
   49371 ** key and data without making a copy.  If the key and/or data spills
   49372 ** onto overflow pages, then accessPayload() must be used to reassemble
   49373 ** the key/data and copy it into a preallocated buffer.
   49374 **
   49375 ** The pointer returned by this routine looks directly into the cached
   49376 ** page of the database.  The data might change or move the next time
   49377 ** any btree routine is called.
   49378 */
   49379 static const unsigned char *fetchPayload(
   49380   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   49381   int *pAmt,           /* Write the number of available bytes here */
   49382   int skipKey          /* read beginning at data if this is true */
   49383 ){
   49384   unsigned char *aPayload;
   49385   MemPage *pPage;
   49386   u32 nKey;
   49387   u32 nLocal;
   49388 
   49389   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
   49390   assert( pCur->eState==CURSOR_VALID );
   49391   assert( cursorHoldsMutex(pCur) );
   49392   pPage = pCur->apPage[pCur->iPage];
   49393   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   49394   if( NEVER(pCur->info.nSize==0) ){
   49395     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
   49396                    &pCur->info);
   49397   }
   49398   aPayload = pCur->info.pCell;
   49399   aPayload += pCur->info.nHeader;
   49400   if( pPage->intKey ){
   49401     nKey = 0;
   49402   }else{
   49403     nKey = (int)pCur->info.nKey;
   49404   }
   49405   if( skipKey ){
   49406     aPayload += nKey;
   49407     nLocal = pCur->info.nLocal - nKey;
   49408   }else{
   49409     nLocal = pCur->info.nLocal;
   49410     assert( nLocal<=nKey );
   49411   }
   49412   *pAmt = nLocal;
   49413   return aPayload;
   49414 }
   49415 
   49416 
   49417 /*
   49418 ** For the entry that cursor pCur is point to, return as
   49419 ** many bytes of the key or data as are available on the local
   49420 ** b-tree page.  Write the number of available bytes into *pAmt.
   49421 **
   49422 ** The pointer returned is ephemeral.  The key/data may move
   49423 ** or be destroyed on the next call to any Btree routine,
   49424 ** including calls from other threads against the same cache.
   49425 ** Hence, a mutex on the BtShared should be held prior to calling
   49426 ** this routine.
   49427 **
   49428 ** These routines is used to get quick access to key and data
   49429 ** in the common case where no overflow pages are used.
   49430 */
   49431 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
   49432   const void *p = 0;
   49433   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   49434   assert( cursorHoldsMutex(pCur) );
   49435   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   49436     p = (const void*)fetchPayload(pCur, pAmt, 0);
   49437   }
   49438   return p;
   49439 }
   49440 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
   49441   const void *p = 0;
   49442   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   49443   assert( cursorHoldsMutex(pCur) );
   49444   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
   49445     p = (const void*)fetchPayload(pCur, pAmt, 1);
   49446   }
   49447   return p;
   49448 }
   49449 
   49450 
   49451 /*
   49452 ** Move the cursor down to a new child page.  The newPgno argument is the
   49453 ** page number of the child page to move to.
   49454 **
   49455 ** This function returns SQLITE_CORRUPT if the page-header flags field of
   49456 ** the new child page does not match the flags field of the parent (i.e.
   49457 ** if an intkey page appears to be the parent of a non-intkey page, or
   49458 ** vice-versa).
   49459 */
   49460 static int moveToChild(BtCursor *pCur, u32 newPgno){
   49461   int rc;
   49462   int i = pCur->iPage;
   49463   MemPage *pNewPage;
   49464   BtShared *pBt = pCur->pBt;
   49465 
   49466   assert( cursorHoldsMutex(pCur) );
   49467   assert( pCur->eState==CURSOR_VALID );
   49468   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
   49469   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
   49470     return SQLITE_CORRUPT_BKPT;
   49471   }
   49472   rc = getAndInitPage(pBt, newPgno, &pNewPage);
   49473   if( rc ) return rc;
   49474   pCur->apPage[i+1] = pNewPage;
   49475   pCur->aiIdx[i+1] = 0;
   49476   pCur->iPage++;
   49477 
   49478   pCur->info.nSize = 0;
   49479   pCur->validNKey = 0;
   49480   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
   49481     return SQLITE_CORRUPT_BKPT;
   49482   }
   49483   return SQLITE_OK;
   49484 }
   49485 
   49486 #ifndef NDEBUG
   49487 /*
   49488 ** Page pParent is an internal (non-leaf) tree page. This function
   49489 ** asserts that page number iChild is the left-child if the iIdx'th
   49490 ** cell in page pParent. Or, if iIdx is equal to the total number of
   49491 ** cells in pParent, that page number iChild is the right-child of
   49492 ** the page.
   49493 */
   49494 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   49495   assert( iIdx<=pParent->nCell );
   49496   if( iIdx==pParent->nCell ){
   49497     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
   49498   }else{
   49499     assert( get4byte(findCell(pParent, iIdx))==iChild );
   49500   }
   49501 }
   49502 #else
   49503 #  define assertParentIndex(x,y,z)
   49504 #endif
   49505 
   49506 /*
   49507 ** Move the cursor up to the parent page.
   49508 **
   49509 ** pCur->idx is set to the cell index that contains the pointer
   49510 ** to the page we are coming from.  If we are coming from the
   49511 ** right-most child page then pCur->idx is set to one more than
   49512 ** the largest cell index.
   49513 */
   49514 static void moveToParent(BtCursor *pCur){
   49515   assert( cursorHoldsMutex(pCur) );
   49516   assert( pCur->eState==CURSOR_VALID );
   49517   assert( pCur->iPage>0 );
   49518   assert( pCur->apPage[pCur->iPage] );
   49519   assertParentIndex(
   49520     pCur->apPage[pCur->iPage-1],
   49521     pCur->aiIdx[pCur->iPage-1],
   49522     pCur->apPage[pCur->iPage]->pgno
   49523   );
   49524   releasePage(pCur->apPage[pCur->iPage]);
   49525   pCur->iPage--;
   49526   pCur->info.nSize = 0;
   49527   pCur->validNKey = 0;
   49528 }
   49529 
   49530 /*
   49531 ** Move the cursor to point to the root page of its b-tree structure.
   49532 **
   49533 ** If the table has a virtual root page, then the cursor is moved to point
   49534 ** to the virtual root page instead of the actual root page. A table has a
   49535 ** virtual root page when the actual root page contains no cells and a
   49536 ** single child page. This can only happen with the table rooted at page 1.
   49537 **
   49538 ** If the b-tree structure is empty, the cursor state is set to
   49539 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
   49540 ** cell located on the root (or virtual root) page and the cursor state
   49541 ** is set to CURSOR_VALID.
   49542 **
   49543 ** If this function returns successfully, it may be assumed that the
   49544 ** page-header flags indicate that the [virtual] root-page is the expected
   49545 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
   49546 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
   49547 ** indicating a table b-tree, or if the caller did specify a KeyInfo
   49548 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
   49549 ** b-tree).
   49550 */
   49551 static int moveToRoot(BtCursor *pCur){
   49552   MemPage *pRoot;
   49553   int rc = SQLITE_OK;
   49554   Btree *p = pCur->pBtree;
   49555   BtShared *pBt = p->pBt;
   49556 
   49557   assert( cursorHoldsMutex(pCur) );
   49558   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
   49559   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
   49560   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
   49561   if( pCur->eState>=CURSOR_REQUIRESEEK ){
   49562     if( pCur->eState==CURSOR_FAULT ){
   49563       assert( pCur->skipNext!=SQLITE_OK );
   49564       return pCur->skipNext;
   49565     }
   49566     sqlite3BtreeClearCursor(pCur);
   49567   }
   49568 
   49569   if( pCur->iPage>=0 ){
   49570     int i;
   49571     for(i=1; i<=pCur->iPage; i++){
   49572       releasePage(pCur->apPage[i]);
   49573     }
   49574     pCur->iPage = 0;
   49575   }else{
   49576     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
   49577     if( rc!=SQLITE_OK ){
   49578       pCur->eState = CURSOR_INVALID;
   49579       return rc;
   49580     }
   49581     pCur->iPage = 0;
   49582 
   49583     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   49584     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   49585     ** NULL, the caller expects a table b-tree. If this is not the case,
   49586     ** return an SQLITE_CORRUPT error.  */
   49587     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
   49588     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
   49589       return SQLITE_CORRUPT_BKPT;
   49590     }
   49591   }
   49592 
   49593   /* Assert that the root page is of the correct type. This must be the
   49594   ** case as the call to this function that loaded the root-page (either
   49595   ** this call or a previous invocation) would have detected corruption
   49596   ** if the assumption were not true, and it is not possible for the flags
   49597   ** byte to have been modified while this cursor is holding a reference
   49598   ** to the page.  */
   49599   pRoot = pCur->apPage[0];
   49600   assert( pRoot->pgno==pCur->pgnoRoot );
   49601   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
   49602 
   49603   pCur->aiIdx[0] = 0;
   49604   pCur->info.nSize = 0;
   49605   pCur->atLast = 0;
   49606   pCur->validNKey = 0;
   49607 
   49608   if( pRoot->nCell==0 && !pRoot->leaf ){
   49609     Pgno subpage;
   49610     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
   49611     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
   49612     pCur->eState = CURSOR_VALID;
   49613     rc = moveToChild(pCur, subpage);
   49614   }else{
   49615     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
   49616   }
   49617   return rc;
   49618 }
   49619 
   49620 /*
   49621 ** Move the cursor down to the left-most leaf entry beneath the
   49622 ** entry to which it is currently pointing.
   49623 **
   49624 ** The left-most leaf is the one with the smallest key - the first
   49625 ** in ascending order.
   49626 */
   49627 static int moveToLeftmost(BtCursor *pCur){
   49628   Pgno pgno;
   49629   int rc = SQLITE_OK;
   49630   MemPage *pPage;
   49631 
   49632   assert( cursorHoldsMutex(pCur) );
   49633   assert( pCur->eState==CURSOR_VALID );
   49634   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   49635     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
   49636     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
   49637     rc = moveToChild(pCur, pgno);
   49638   }
   49639   return rc;
   49640 }
   49641 
   49642 /*
   49643 ** Move the cursor down to the right-most leaf entry beneath the
   49644 ** page to which it is currently pointing.  Notice the difference
   49645 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
   49646 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
   49647 ** finds the right-most entry beneath the *page*.
   49648 **
   49649 ** The right-most entry is the one with the largest key - the last
   49650 ** key in ascending order.
   49651 */
   49652 static int moveToRightmost(BtCursor *pCur){
   49653   Pgno pgno;
   49654   int rc = SQLITE_OK;
   49655   MemPage *pPage = 0;
   49656 
   49657   assert( cursorHoldsMutex(pCur) );
   49658   assert( pCur->eState==CURSOR_VALID );
   49659   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
   49660     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   49661     pCur->aiIdx[pCur->iPage] = pPage->nCell;
   49662     rc = moveToChild(pCur, pgno);
   49663   }
   49664   if( rc==SQLITE_OK ){
   49665     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
   49666     pCur->info.nSize = 0;
   49667     pCur->validNKey = 0;
   49668   }
   49669   return rc;
   49670 }
   49671 
   49672 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
   49673 ** on success.  Set *pRes to 0 if the cursor actually points to something
   49674 ** or set *pRes to 1 if the table is empty.
   49675 */
   49676 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
   49677   int rc;
   49678 
   49679   assert( cursorHoldsMutex(pCur) );
   49680   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   49681   rc = moveToRoot(pCur);
   49682   if( rc==SQLITE_OK ){
   49683     if( pCur->eState==CURSOR_INVALID ){
   49684       assert( pCur->apPage[pCur->iPage]->nCell==0 );
   49685       *pRes = 1;
   49686     }else{
   49687       assert( pCur->apPage[pCur->iPage]->nCell>0 );
   49688       *pRes = 0;
   49689       rc = moveToLeftmost(pCur);
   49690     }
   49691   }
   49692   return rc;
   49693 }
   49694 
   49695 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
   49696 ** on success.  Set *pRes to 0 if the cursor actually points to something
   49697 ** or set *pRes to 1 if the table is empty.
   49698 */
   49699 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   49700   int rc;
   49701 
   49702   assert( cursorHoldsMutex(pCur) );
   49703   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   49704 
   49705   /* If the cursor already points to the last entry, this is a no-op. */
   49706   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
   49707 #ifdef SQLITE_DEBUG
   49708     /* This block serves to assert() that the cursor really does point
   49709     ** to the last entry in the b-tree. */
   49710     int ii;
   49711     for(ii=0; ii<pCur->iPage; ii++){
   49712       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
   49713     }
   49714     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
   49715     assert( pCur->apPage[pCur->iPage]->leaf );
   49716 #endif
   49717     return SQLITE_OK;
   49718   }
   49719 
   49720   rc = moveToRoot(pCur);
   49721   if( rc==SQLITE_OK ){
   49722     if( CURSOR_INVALID==pCur->eState ){
   49723       assert( pCur->apPage[pCur->iPage]->nCell==0 );
   49724       *pRes = 1;
   49725     }else{
   49726       assert( pCur->eState==CURSOR_VALID );
   49727       *pRes = 0;
   49728       rc = moveToRightmost(pCur);
   49729       pCur->atLast = rc==SQLITE_OK ?1:0;
   49730     }
   49731   }
   49732   return rc;
   49733 }
   49734 
   49735 /* Move the cursor so that it points to an entry near the key
   49736 ** specified by pIdxKey or intKey.   Return a success code.
   49737 **
   49738 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
   49739 ** must be NULL.  For index tables, pIdxKey is used and intKey
   49740 ** is ignored.
   49741 **
   49742 ** If an exact match is not found, then the cursor is always
   49743 ** left pointing at a leaf page which would hold the entry if it
   49744 ** were present.  The cursor might point to an entry that comes
   49745 ** before or after the key.
   49746 **
   49747 ** An integer is written into *pRes which is the result of
   49748 ** comparing the key with the entry to which the cursor is
   49749 ** pointing.  The meaning of the integer written into
   49750 ** *pRes is as follows:
   49751 **
   49752 **     *pRes<0      The cursor is left pointing at an entry that
   49753 **                  is smaller than intKey/pIdxKey or if the table is empty
   49754 **                  and the cursor is therefore left point to nothing.
   49755 **
   49756 **     *pRes==0     The cursor is left pointing at an entry that
   49757 **                  exactly matches intKey/pIdxKey.
   49758 **
   49759 **     *pRes>0      The cursor is left pointing at an entry that
   49760 **                  is larger than intKey/pIdxKey.
   49761 **
   49762 */
   49763 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   49764   BtCursor *pCur,          /* The cursor to be moved */
   49765   UnpackedRecord *pIdxKey, /* Unpacked index key */
   49766   i64 intKey,              /* The table key */
   49767   int biasRight,           /* If true, bias the search to the high end */
   49768   int *pRes                /* Write search results here */
   49769 ){
   49770   int rc;
   49771 
   49772   assert( cursorHoldsMutex(pCur) );
   49773   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   49774   assert( pRes );
   49775   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
   49776 
   49777   /* If the cursor is already positioned at the point we are trying
   49778   ** to move to, then just return without doing any work */
   49779   if( pCur->eState==CURSOR_VALID && pCur->validNKey
   49780    && pCur->apPage[0]->intKey
   49781   ){
   49782     if( pCur->info.nKey==intKey ){
   49783       *pRes = 0;
   49784       return SQLITE_OK;
   49785     }
   49786     if( pCur->atLast && pCur->info.nKey<intKey ){
   49787       *pRes = -1;
   49788       return SQLITE_OK;
   49789     }
   49790   }
   49791 
   49792   rc = moveToRoot(pCur);
   49793   if( rc ){
   49794     return rc;
   49795   }
   49796   assert( pCur->apPage[pCur->iPage] );
   49797   assert( pCur->apPage[pCur->iPage]->isInit );
   49798   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
   49799   if( pCur->eState==CURSOR_INVALID ){
   49800     *pRes = -1;
   49801     assert( pCur->apPage[pCur->iPage]->nCell==0 );
   49802     return SQLITE_OK;
   49803   }
   49804   assert( pCur->apPage[0]->intKey || pIdxKey );
   49805   for(;;){
   49806     int lwr, upr;
   49807     Pgno chldPg;
   49808     MemPage *pPage = pCur->apPage[pCur->iPage];
   49809     int c;
   49810 
   49811     /* pPage->nCell must be greater than zero. If this is the root-page
   49812     ** the cursor would have been INVALID above and this for(;;) loop
   49813     ** not run. If this is not the root-page, then the moveToChild() routine
   49814     ** would have already detected db corruption. Similarly, pPage must
   49815     ** be the right kind (index or table) of b-tree page. Otherwise
   49816     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
   49817     assert( pPage->nCell>0 );
   49818     assert( pPage->intKey==(pIdxKey==0) );
   49819     lwr = 0;
   49820     upr = pPage->nCell-1;
   49821     if( biasRight ){
   49822       pCur->aiIdx[pCur->iPage] = (u16)upr;
   49823     }else{
   49824       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
   49825     }
   49826     for(;;){
   49827       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
   49828       u8 *pCell;                          /* Pointer to current cell in pPage */
   49829 
   49830       pCur->info.nSize = 0;
   49831       pCell = findCell(pPage, idx) + pPage->childPtrSize;
   49832       if( pPage->intKey ){
   49833         i64 nCellKey;
   49834         if( pPage->hasData ){
   49835           u32 dummy;
   49836           pCell += getVarint32(pCell, dummy);
   49837         }
   49838         getVarint(pCell, (u64*)&nCellKey);
   49839         if( nCellKey==intKey ){
   49840           c = 0;
   49841         }else if( nCellKey<intKey ){
   49842           c = -1;
   49843         }else{
   49844           assert( nCellKey>intKey );
   49845           c = +1;
   49846         }
   49847         pCur->validNKey = 1;
   49848         pCur->info.nKey = nCellKey;
   49849       }else{
   49850         /* The maximum supported page-size is 65536 bytes. This means that
   49851         ** the maximum number of record bytes stored on an index B-Tree
   49852         ** page is less than 16384 bytes and may be stored as a 2-byte
   49853         ** varint. This information is used to attempt to avoid parsing
   49854         ** the entire cell by checking for the cases where the record is
   49855         ** stored entirely within the b-tree page by inspecting the first
   49856         ** 2 bytes of the cell.
   49857         */
   49858         int nCell = pCell[0];
   49859         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
   49860           /* This branch runs if the record-size field of the cell is a
   49861           ** single byte varint and the record fits entirely on the main
   49862           ** b-tree page.  */
   49863           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
   49864         }else if( !(pCell[1] & 0x80)
   49865           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
   49866         ){
   49867           /* The record-size field is a 2 byte varint and the record
   49868           ** fits entirely on the main b-tree page.  */
   49869           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
   49870         }else{
   49871           /* The record flows over onto one or more overflow pages. In
   49872           ** this case the whole cell needs to be parsed, a buffer allocated
   49873           ** and accessPayload() used to retrieve the record into the
   49874           ** buffer before VdbeRecordCompare() can be called. */
   49875           void *pCellKey;
   49876           u8 * const pCellBody = pCell - pPage->childPtrSize;
   49877           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
   49878           nCell = (int)pCur->info.nKey;
   49879           pCellKey = sqlite3Malloc( nCell );
   49880           if( pCellKey==0 ){
   49881             rc = SQLITE_NOMEM;
   49882             goto moveto_finish;
   49883           }
   49884           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
   49885           if( rc ){
   49886             sqlite3_free(pCellKey);
   49887             goto moveto_finish;
   49888           }
   49889           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
   49890           sqlite3_free(pCellKey);
   49891         }
   49892       }
   49893       if( c==0 ){
   49894         if( pPage->intKey && !pPage->leaf ){
   49895           lwr = idx;
   49896           upr = lwr - 1;
   49897           break;
   49898         }else{
   49899           *pRes = 0;
   49900           rc = SQLITE_OK;
   49901           goto moveto_finish;
   49902         }
   49903       }
   49904       if( c<0 ){
   49905         lwr = idx+1;
   49906       }else{
   49907         upr = idx-1;
   49908       }
   49909       if( lwr>upr ){
   49910         break;
   49911       }
   49912       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
   49913     }
   49914     assert( lwr==upr+1 );
   49915     assert( pPage->isInit );
   49916     if( pPage->leaf ){
   49917       chldPg = 0;
   49918     }else if( lwr>=pPage->nCell ){
   49919       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   49920     }else{
   49921       chldPg = get4byte(findCell(pPage, lwr));
   49922     }
   49923     if( chldPg==0 ){
   49924       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
   49925       *pRes = c;
   49926       rc = SQLITE_OK;
   49927       goto moveto_finish;
   49928     }
   49929     pCur->aiIdx[pCur->iPage] = (u16)lwr;
   49930     pCur->info.nSize = 0;
   49931     pCur->validNKey = 0;
   49932     rc = moveToChild(pCur, chldPg);
   49933     if( rc ) goto moveto_finish;
   49934   }
   49935 moveto_finish:
   49936   return rc;
   49937 }
   49938 
   49939 
   49940 /*
   49941 ** Return TRUE if the cursor is not pointing at an entry of the table.
   49942 **
   49943 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
   49944 ** past the last entry in the table or sqlite3BtreePrev() moves past
   49945 ** the first entry.  TRUE is also returned if the table is empty.
   49946 */
   49947 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
   49948   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
   49949   ** have been deleted? This API will need to change to return an error code
   49950   ** as well as the boolean result value.
   49951   */
   49952   return (CURSOR_VALID!=pCur->eState);
   49953 }
   49954 
   49955 /*
   49956 ** Advance the cursor to the next entry in the database.  If
   49957 ** successful then set *pRes=0.  If the cursor
   49958 ** was already pointing to the last entry in the database before
   49959 ** this routine was called, then set *pRes=1.
   49960 */
   49961 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
   49962   int rc;
   49963   int idx;
   49964   MemPage *pPage;
   49965 
   49966   assert( cursorHoldsMutex(pCur) );
   49967   rc = restoreCursorPosition(pCur);
   49968   if( rc!=SQLITE_OK ){
   49969     return rc;
   49970   }
   49971   assert( pRes!=0 );
   49972   if( CURSOR_INVALID==pCur->eState ){
   49973     *pRes = 1;
   49974     return SQLITE_OK;
   49975   }
   49976   if( pCur->skipNext>0 ){
   49977     pCur->skipNext = 0;
   49978     *pRes = 0;
   49979     return SQLITE_OK;
   49980   }
   49981   pCur->skipNext = 0;
   49982 
   49983   pPage = pCur->apPage[pCur->iPage];
   49984   idx = ++pCur->aiIdx[pCur->iPage];
   49985   assert( pPage->isInit );
   49986   assert( idx<=pPage->nCell );
   49987 
   49988   pCur->info.nSize = 0;
   49989   pCur->validNKey = 0;
   49990   if( idx>=pPage->nCell ){
   49991     if( !pPage->leaf ){
   49992       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   49993       if( rc ) return rc;
   49994       rc = moveToLeftmost(pCur);
   49995       *pRes = 0;
   49996       return rc;
   49997     }
   49998     do{
   49999       if( pCur->iPage==0 ){
   50000         *pRes = 1;
   50001         pCur->eState = CURSOR_INVALID;
   50002         return SQLITE_OK;
   50003       }
   50004       moveToParent(pCur);
   50005       pPage = pCur->apPage[pCur->iPage];
   50006     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
   50007     *pRes = 0;
   50008     if( pPage->intKey ){
   50009       rc = sqlite3BtreeNext(pCur, pRes);
   50010     }else{
   50011       rc = SQLITE_OK;
   50012     }
   50013     return rc;
   50014   }
   50015   *pRes = 0;
   50016   if( pPage->leaf ){
   50017     return SQLITE_OK;
   50018   }
   50019   rc = moveToLeftmost(pCur);
   50020   return rc;
   50021 }
   50022 
   50023 
   50024 /*
   50025 ** Step the cursor to the back to the previous entry in the database.  If
   50026 ** successful then set *pRes=0.  If the cursor
   50027 ** was already pointing to the first entry in the database before
   50028 ** this routine was called, then set *pRes=1.
   50029 */
   50030 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
   50031   int rc;
   50032   MemPage *pPage;
   50033 
   50034   assert( cursorHoldsMutex(pCur) );
   50035   rc = restoreCursorPosition(pCur);
   50036   if( rc!=SQLITE_OK ){
   50037     return rc;
   50038   }
   50039   pCur->atLast = 0;
   50040   if( CURSOR_INVALID==pCur->eState ){
   50041     *pRes = 1;
   50042     return SQLITE_OK;
   50043   }
   50044   if( pCur->skipNext<0 ){
   50045     pCur->skipNext = 0;
   50046     *pRes = 0;
   50047     return SQLITE_OK;
   50048   }
   50049   pCur->skipNext = 0;
   50050 
   50051   pPage = pCur->apPage[pCur->iPage];
   50052   assert( pPage->isInit );
   50053   if( !pPage->leaf ){
   50054     int idx = pCur->aiIdx[pCur->iPage];
   50055     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
   50056     if( rc ){
   50057       return rc;
   50058     }
   50059     rc = moveToRightmost(pCur);
   50060   }else{
   50061     while( pCur->aiIdx[pCur->iPage]==0 ){
   50062       if( pCur->iPage==0 ){
   50063         pCur->eState = CURSOR_INVALID;
   50064         *pRes = 1;
   50065         return SQLITE_OK;
   50066       }
   50067       moveToParent(pCur);
   50068     }
   50069     pCur->info.nSize = 0;
   50070     pCur->validNKey = 0;
   50071 
   50072     pCur->aiIdx[pCur->iPage]--;
   50073     pPage = pCur->apPage[pCur->iPage];
   50074     if( pPage->intKey && !pPage->leaf ){
   50075       rc = sqlite3BtreePrevious(pCur, pRes);
   50076     }else{
   50077       rc = SQLITE_OK;
   50078     }
   50079   }
   50080   *pRes = 0;
   50081   return rc;
   50082 }
   50083 
   50084 /*
   50085 ** Allocate a new page from the database file.
   50086 **
   50087 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
   50088 ** has already been called on the new page.)  The new page has also
   50089 ** been referenced and the calling routine is responsible for calling
   50090 ** sqlite3PagerUnref() on the new page when it is done.
   50091 **
   50092 ** SQLITE_OK is returned on success.  Any other return value indicates
   50093 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
   50094 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
   50095 **
   50096 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
   50097 ** locate a page close to the page number "nearby".  This can be used in an
   50098 ** attempt to keep related pages close to each other in the database file,
   50099 ** which in turn can make database access faster.
   50100 **
   50101 ** If the "exact" parameter is not 0, and the page-number nearby exists
   50102 ** anywhere on the free-list, then it is guarenteed to be returned. This
   50103 ** is only used by auto-vacuum databases when allocating a new table.
   50104 */
   50105 static int allocateBtreePage(
   50106   BtShared *pBt,
   50107   MemPage **ppPage,
   50108   Pgno *pPgno,
   50109   Pgno nearby,
   50110   u8 exact
   50111 ){
   50112   MemPage *pPage1;
   50113   int rc;
   50114   u32 n;     /* Number of pages on the freelist */
   50115   u32 k;     /* Number of leaves on the trunk of the freelist */
   50116   MemPage *pTrunk = 0;
   50117   MemPage *pPrevTrunk = 0;
   50118   Pgno mxPage;     /* Total size of the database file */
   50119 
   50120   assert( sqlite3_mutex_held(pBt->mutex) );
   50121   pPage1 = pBt->pPage1;
   50122   mxPage = btreePagecount(pBt);
   50123   n = get4byte(&pPage1->aData[36]);
   50124   testcase( n==mxPage-1 );
   50125   if( n>=mxPage ){
   50126     return SQLITE_CORRUPT_BKPT;
   50127   }
   50128   if( n>0 ){
   50129     /* There are pages on the freelist.  Reuse one of those pages. */
   50130     Pgno iTrunk;
   50131     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
   50132 
   50133     /* If the 'exact' parameter was true and a query of the pointer-map
   50134     ** shows that the page 'nearby' is somewhere on the free-list, then
   50135     ** the entire-list will be searched for that page.
   50136     */
   50137 #ifndef SQLITE_OMIT_AUTOVACUUM
   50138     if( exact && nearby<=mxPage ){
   50139       u8 eType;
   50140       assert( nearby>0 );
   50141       assert( pBt->autoVacuum );
   50142       rc = ptrmapGet(pBt, nearby, &eType, 0);
   50143       if( rc ) return rc;
   50144       if( eType==PTRMAP_FREEPAGE ){
   50145         searchList = 1;
   50146       }
   50147       *pPgno = nearby;
   50148     }
   50149 #endif
   50150 
   50151     /* Decrement the free-list count by 1. Set iTrunk to the index of the
   50152     ** first free-list trunk page. iPrevTrunk is initially 1.
   50153     */
   50154     rc = sqlite3PagerWrite(pPage1->pDbPage);
   50155     if( rc ) return rc;
   50156     put4byte(&pPage1->aData[36], n-1);
   50157 
   50158     /* The code within this loop is run only once if the 'searchList' variable
   50159     ** is not true. Otherwise, it runs once for each trunk-page on the
   50160     ** free-list until the page 'nearby' is located.
   50161     */
   50162     do {
   50163       pPrevTrunk = pTrunk;
   50164       if( pPrevTrunk ){
   50165         iTrunk = get4byte(&pPrevTrunk->aData[0]);
   50166       }else{
   50167         iTrunk = get4byte(&pPage1->aData[32]);
   50168       }
   50169       testcase( iTrunk==mxPage );
   50170       if( iTrunk>mxPage ){
   50171         rc = SQLITE_CORRUPT_BKPT;
   50172       }else{
   50173         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   50174       }
   50175       if( rc ){
   50176         pTrunk = 0;
   50177         goto end_allocate_page;
   50178       }
   50179 
   50180       k = get4byte(&pTrunk->aData[4]);
   50181       if( k==0 && !searchList ){
   50182         /* The trunk has no leaves and the list is not being searched.
   50183         ** So extract the trunk page itself and use it as the newly
   50184         ** allocated page */
   50185         assert( pPrevTrunk==0 );
   50186         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   50187         if( rc ){
   50188           goto end_allocate_page;
   50189         }
   50190         *pPgno = iTrunk;
   50191         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   50192         *ppPage = pTrunk;
   50193         pTrunk = 0;
   50194         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   50195       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
   50196         /* Value of k is out of range.  Database corruption */
   50197         rc = SQLITE_CORRUPT_BKPT;
   50198         goto end_allocate_page;
   50199 #ifndef SQLITE_OMIT_AUTOVACUUM
   50200       }else if( searchList && nearby==iTrunk ){
   50201         /* The list is being searched and this trunk page is the page
   50202         ** to allocate, regardless of whether it has leaves.
   50203         */
   50204         assert( *pPgno==iTrunk );
   50205         *ppPage = pTrunk;
   50206         searchList = 0;
   50207         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   50208         if( rc ){
   50209           goto end_allocate_page;
   50210         }
   50211         if( k==0 ){
   50212           if( !pPrevTrunk ){
   50213             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
   50214           }else{
   50215             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   50216             if( rc!=SQLITE_OK ){
   50217               goto end_allocate_page;
   50218             }
   50219             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
   50220           }
   50221         }else{
   50222           /* The trunk page is required by the caller but it contains
   50223           ** pointers to free-list leaves. The first leaf becomes a trunk
   50224           ** page in this case.
   50225           */
   50226           MemPage *pNewTrunk;
   50227           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
   50228           if( iNewTrunk>mxPage ){
   50229             rc = SQLITE_CORRUPT_BKPT;
   50230             goto end_allocate_page;
   50231           }
   50232           testcase( iNewTrunk==mxPage );
   50233           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
   50234           if( rc!=SQLITE_OK ){
   50235             goto end_allocate_page;
   50236           }
   50237           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
   50238           if( rc!=SQLITE_OK ){
   50239             releasePage(pNewTrunk);
   50240             goto end_allocate_page;
   50241           }
   50242           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
   50243           put4byte(&pNewTrunk->aData[4], k-1);
   50244           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
   50245           releasePage(pNewTrunk);
   50246           if( !pPrevTrunk ){
   50247             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
   50248             put4byte(&pPage1->aData[32], iNewTrunk);
   50249           }else{
   50250             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
   50251             if( rc ){
   50252               goto end_allocate_page;
   50253             }
   50254             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
   50255           }
   50256         }
   50257         pTrunk = 0;
   50258         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
   50259 #endif
   50260       }else if( k>0 ){
   50261         /* Extract a leaf from the trunk */
   50262         u32 closest;
   50263         Pgno iPage;
   50264         unsigned char *aData = pTrunk->aData;
   50265         rc = sqlite3PagerWrite(pTrunk->pDbPage);
   50266         if( rc ){
   50267           goto end_allocate_page;
   50268         }
   50269         if( nearby>0 ){
   50270           u32 i;
   50271           int dist;
   50272           closest = 0;
   50273           dist = get4byte(&aData[8]) - nearby;
   50274           if( dist<0 ) dist = -dist;
   50275           for(i=1; i<k; i++){
   50276             int d2 = get4byte(&aData[8+i*4]) - nearby;
   50277             if( d2<0 ) d2 = -d2;
   50278             if( d2<dist ){
   50279               closest = i;
   50280               dist = d2;
   50281             }
   50282           }
   50283         }else{
   50284           closest = 0;
   50285         }
   50286 
   50287         iPage = get4byte(&aData[8+closest*4]);
   50288         testcase( iPage==mxPage );
   50289         if( iPage>mxPage ){
   50290           rc = SQLITE_CORRUPT_BKPT;
   50291           goto end_allocate_page;
   50292         }
   50293         testcase( iPage==mxPage );
   50294         if( !searchList || iPage==nearby ){
   50295           int noContent;
   50296           *pPgno = iPage;
   50297           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
   50298                  ": %d more free pages\n",
   50299                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
   50300           if( closest<k-1 ){
   50301             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
   50302           }
   50303           put4byte(&aData[4], k-1);
   50304           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
   50305           noContent = !btreeGetHasContent(pBt, *pPgno);
   50306           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
   50307           if( rc==SQLITE_OK ){
   50308             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   50309             if( rc!=SQLITE_OK ){
   50310               releasePage(*ppPage);
   50311             }
   50312           }
   50313           searchList = 0;
   50314         }
   50315       }
   50316       releasePage(pPrevTrunk);
   50317       pPrevTrunk = 0;
   50318     }while( searchList );
   50319   }else{
   50320     /* There are no pages on the freelist, so create a new page at the
   50321     ** end of the file */
   50322     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   50323     if( rc ) return rc;
   50324     pBt->nPage++;
   50325     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
   50326 
   50327 #ifndef SQLITE_OMIT_AUTOVACUUM
   50328     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
   50329       /* If *pPgno refers to a pointer-map page, allocate two new pages
   50330       ** at the end of the file instead of one. The first allocated page
   50331       ** becomes a new pointer-map page, the second is used by the caller.
   50332       */
   50333       MemPage *pPg = 0;
   50334       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
   50335       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
   50336       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
   50337       if( rc==SQLITE_OK ){
   50338         rc = sqlite3PagerWrite(pPg->pDbPage);
   50339         releasePage(pPg);
   50340       }
   50341       if( rc ) return rc;
   50342       pBt->nPage++;
   50343       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
   50344     }
   50345 #endif
   50346     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
   50347     *pPgno = pBt->nPage;
   50348 
   50349     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   50350     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
   50351     if( rc ) return rc;
   50352     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
   50353     if( rc!=SQLITE_OK ){
   50354       releasePage(*ppPage);
   50355     }
   50356     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
   50357   }
   50358 
   50359   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
   50360 
   50361 end_allocate_page:
   50362   releasePage(pTrunk);
   50363   releasePage(pPrevTrunk);
   50364   if( rc==SQLITE_OK ){
   50365     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
   50366       releasePage(*ppPage);
   50367       return SQLITE_CORRUPT_BKPT;
   50368     }
   50369     (*ppPage)->isInit = 0;
   50370   }else{
   50371     *ppPage = 0;
   50372   }
   50373   return rc;
   50374 }
   50375 
   50376 /*
   50377 ** This function is used to add page iPage to the database file free-list.
   50378 ** It is assumed that the page is not already a part of the free-list.
   50379 **
   50380 ** The value passed as the second argument to this function is optional.
   50381 ** If the caller happens to have a pointer to the MemPage object
   50382 ** corresponding to page iPage handy, it may pass it as the second value.
   50383 ** Otherwise, it may pass NULL.
   50384 **
   50385 ** If a pointer to a MemPage object is passed as the second argument,
   50386 ** its reference count is not altered by this function.
   50387 */
   50388 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   50389   MemPage *pTrunk = 0;                /* Free-list trunk page */
   50390   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   50391   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   50392   MemPage *pPage;                     /* Page being freed. May be NULL. */
   50393   int rc;                             /* Return Code */
   50394   int nFree;                          /* Initial number of pages on free-list */
   50395 
   50396   assert( sqlite3_mutex_held(pBt->mutex) );
   50397   assert( iPage>1 );
   50398   assert( !pMemPage || pMemPage->pgno==iPage );
   50399 
   50400   if( pMemPage ){
   50401     pPage = pMemPage;
   50402     sqlite3PagerRef(pPage->pDbPage);
   50403   }else{
   50404     pPage = btreePageLookup(pBt, iPage);
   50405   }
   50406 
   50407   /* Increment the free page count on pPage1 */
   50408   rc = sqlite3PagerWrite(pPage1->pDbPage);
   50409   if( rc ) goto freepage_out;
   50410   nFree = get4byte(&pPage1->aData[36]);
   50411   put4byte(&pPage1->aData[36], nFree+1);
   50412 
   50413   if( pBt->secureDelete ){
   50414     /* If the secure_delete option is enabled, then
   50415     ** always fully overwrite deleted information with zeros.
   50416     */
   50417     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
   50418      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
   50419     ){
   50420       goto freepage_out;
   50421     }
   50422     memset(pPage->aData, 0, pPage->pBt->pageSize);
   50423   }
   50424 
   50425   /* If the database supports auto-vacuum, write an entry in the pointer-map
   50426   ** to indicate that the page is free.
   50427   */
   50428   if( ISAUTOVACUUM ){
   50429     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
   50430     if( rc ) goto freepage_out;
   50431   }
   50432 
   50433   /* Now manipulate the actual database free-list structure. There are two
   50434   ** possibilities. If the free-list is currently empty, or if the first
   50435   ** trunk page in the free-list is full, then this page will become a
   50436   ** new free-list trunk page. Otherwise, it will become a leaf of the
   50437   ** first trunk page in the current free-list. This block tests if it
   50438   ** is possible to add the page as a new free-list leaf.
   50439   */
   50440   if( nFree!=0 ){
   50441     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
   50442 
   50443     iTrunk = get4byte(&pPage1->aData[32]);
   50444     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
   50445     if( rc!=SQLITE_OK ){
   50446       goto freepage_out;
   50447     }
   50448 
   50449     nLeaf = get4byte(&pTrunk->aData[4]);
   50450     assert( pBt->usableSize>32 );
   50451     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
   50452       rc = SQLITE_CORRUPT_BKPT;
   50453       goto freepage_out;
   50454     }
   50455     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
   50456       /* In this case there is room on the trunk page to insert the page
   50457       ** being freed as a new leaf.
   50458       **
   50459       ** Note that the trunk page is not really full until it contains
   50460       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
   50461       ** coded.  But due to a coding error in versions of SQLite prior to
   50462       ** 3.6.0, databases with freelist trunk pages holding more than
   50463       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
   50464       ** to maintain backwards compatibility with older versions of SQLite,
   50465       ** we will continue to restrict the number of entries to usableSize/4 - 8
   50466       ** for now.  At some point in the future (once everyone has upgraded
   50467       ** to 3.6.0 or later) we should consider fixing the conditional above
   50468       ** to read "usableSize/4-2" instead of "usableSize/4-8".
   50469       */
   50470       rc = sqlite3PagerWrite(pTrunk->pDbPage);
   50471       if( rc==SQLITE_OK ){
   50472         put4byte(&pTrunk->aData[4], nLeaf+1);
   50473         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
   50474         if( pPage && !pBt->secureDelete ){
   50475           sqlite3PagerDontWrite(pPage->pDbPage);
   50476         }
   50477         rc = btreeSetHasContent(pBt, iPage);
   50478       }
   50479       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
   50480       goto freepage_out;
   50481     }
   50482   }
   50483 
   50484   /* If control flows to this point, then it was not possible to add the
   50485   ** the page being freed as a leaf page of the first trunk in the free-list.
   50486   ** Possibly because the free-list is empty, or possibly because the
   50487   ** first trunk in the free-list is full. Either way, the page being freed
   50488   ** will become the new first trunk page in the free-list.
   50489   */
   50490   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
   50491     goto freepage_out;
   50492   }
   50493   rc = sqlite3PagerWrite(pPage->pDbPage);
   50494   if( rc!=SQLITE_OK ){
   50495     goto freepage_out;
   50496   }
   50497   put4byte(pPage->aData, iTrunk);
   50498   put4byte(&pPage->aData[4], 0);
   50499   put4byte(&pPage1->aData[32], iPage);
   50500   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
   50501 
   50502 freepage_out:
   50503   if( pPage ){
   50504     pPage->isInit = 0;
   50505   }
   50506   releasePage(pPage);
   50507   releasePage(pTrunk);
   50508   return rc;
   50509 }
   50510 static void freePage(MemPage *pPage, int *pRC){
   50511   if( (*pRC)==SQLITE_OK ){
   50512     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
   50513   }
   50514 }
   50515 
   50516 /*
   50517 ** Free any overflow pages associated with the given Cell.
   50518 */
   50519 static int clearCell(MemPage *pPage, unsigned char *pCell){
   50520   BtShared *pBt = pPage->pBt;
   50521   CellInfo info;
   50522   Pgno ovflPgno;
   50523   int rc;
   50524   int nOvfl;
   50525   u32 ovflPageSize;
   50526 
   50527   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50528   btreeParseCellPtr(pPage, pCell, &info);
   50529   if( info.iOverflow==0 ){
   50530     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
   50531   }
   50532   ovflPgno = get4byte(&pCell[info.iOverflow]);
   50533   assert( pBt->usableSize > 4 );
   50534   ovflPageSize = pBt->usableSize - 4;
   50535   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
   50536   assert( ovflPgno==0 || nOvfl>0 );
   50537   while( nOvfl-- ){
   50538     Pgno iNext = 0;
   50539     MemPage *pOvfl = 0;
   50540     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
   50541       /* 0 is not a legal page number and page 1 cannot be an
   50542       ** overflow page. Therefore if ovflPgno<2 or past the end of the
   50543       ** file the database must be corrupt. */
   50544       return SQLITE_CORRUPT_BKPT;
   50545     }
   50546     if( nOvfl ){
   50547       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
   50548       if( rc ) return rc;
   50549     }
   50550 
   50551     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
   50552      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
   50553     ){
   50554       /* There is no reason any cursor should have an outstanding reference
   50555       ** to an overflow page belonging to a cell that is being deleted/updated.
   50556       ** So if there exists more than one reference to this page, then it
   50557       ** must not really be an overflow page and the database must be corrupt.
   50558       ** It is helpful to detect this before calling freePage2(), as
   50559       ** freePage2() may zero the page contents if secure-delete mode is
   50560       ** enabled. If this 'overflow' page happens to be a page that the
   50561       ** caller is iterating through or using in some other way, this
   50562       ** can be problematic.
   50563       */
   50564       rc = SQLITE_CORRUPT_BKPT;
   50565     }else{
   50566       rc = freePage2(pBt, pOvfl, ovflPgno);
   50567     }
   50568 
   50569     if( pOvfl ){
   50570       sqlite3PagerUnref(pOvfl->pDbPage);
   50571     }
   50572     if( rc ) return rc;
   50573     ovflPgno = iNext;
   50574   }
   50575   return SQLITE_OK;
   50576 }
   50577 
   50578 /*
   50579 ** Create the byte sequence used to represent a cell on page pPage
   50580 ** and write that byte sequence into pCell[].  Overflow pages are
   50581 ** allocated and filled in as necessary.  The calling procedure
   50582 ** is responsible for making sure sufficient space has been allocated
   50583 ** for pCell[].
   50584 **
   50585 ** Note that pCell does not necessary need to point to the pPage->aData
   50586 ** area.  pCell might point to some temporary storage.  The cell will
   50587 ** be constructed in this temporary area then copied into pPage->aData
   50588 ** later.
   50589 */
   50590 static int fillInCell(
   50591   MemPage *pPage,                /* The page that contains the cell */
   50592   unsigned char *pCell,          /* Complete text of the cell */
   50593   const void *pKey, i64 nKey,    /* The key */
   50594   const void *pData,int nData,   /* The data */
   50595   int nZero,                     /* Extra zero bytes to append to pData */
   50596   int *pnSize                    /* Write cell size here */
   50597 ){
   50598   int nPayload;
   50599   const u8 *pSrc;
   50600   int nSrc, n, rc;
   50601   int spaceLeft;
   50602   MemPage *pOvfl = 0;
   50603   MemPage *pToRelease = 0;
   50604   unsigned char *pPrior;
   50605   unsigned char *pPayload;
   50606   BtShared *pBt = pPage->pBt;
   50607   Pgno pgnoOvfl = 0;
   50608   int nHeader;
   50609   CellInfo info;
   50610 
   50611   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50612 
   50613   /* pPage is not necessarily writeable since pCell might be auxiliary
   50614   ** buffer space that is separate from the pPage buffer area */
   50615   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
   50616             || sqlite3PagerIswriteable(pPage->pDbPage) );
   50617 
   50618   /* Fill in the header. */
   50619   nHeader = 0;
   50620   if( !pPage->leaf ){
   50621     nHeader += 4;
   50622   }
   50623   if( pPage->hasData ){
   50624     nHeader += putVarint(&pCell[nHeader], nData+nZero);
   50625   }else{
   50626     nData = nZero = 0;
   50627   }
   50628   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
   50629   btreeParseCellPtr(pPage, pCell, &info);
   50630   assert( info.nHeader==nHeader );
   50631   assert( info.nKey==nKey );
   50632   assert( info.nData==(u32)(nData+nZero) );
   50633 
   50634   /* Fill in the payload */
   50635   nPayload = nData + nZero;
   50636   if( pPage->intKey ){
   50637     pSrc = pData;
   50638     nSrc = nData;
   50639     nData = 0;
   50640   }else{
   50641     if( NEVER(nKey>0x7fffffff || pKey==0) ){
   50642       return SQLITE_CORRUPT_BKPT;
   50643     }
   50644     nPayload += (int)nKey;
   50645     pSrc = pKey;
   50646     nSrc = (int)nKey;
   50647   }
   50648   *pnSize = info.nSize;
   50649   spaceLeft = info.nLocal;
   50650   pPayload = &pCell[nHeader];
   50651   pPrior = &pCell[info.iOverflow];
   50652 
   50653   while( nPayload>0 ){
   50654     if( spaceLeft==0 ){
   50655 #ifndef SQLITE_OMIT_AUTOVACUUM
   50656       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
   50657       if( pBt->autoVacuum ){
   50658         do{
   50659           pgnoOvfl++;
   50660         } while(
   50661           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
   50662         );
   50663       }
   50664 #endif
   50665       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
   50666 #ifndef SQLITE_OMIT_AUTOVACUUM
   50667       /* If the database supports auto-vacuum, and the second or subsequent
   50668       ** overflow page is being allocated, add an entry to the pointer-map
   50669       ** for that page now.
   50670       **
   50671       ** If this is the first overflow page, then write a partial entry
   50672       ** to the pointer-map. If we write nothing to this pointer-map slot,
   50673       ** then the optimistic overflow chain processing in clearCell()
   50674       ** may misinterpret the uninitialised values and delete the
   50675       ** wrong pages from the database.
   50676       */
   50677       if( pBt->autoVacuum && rc==SQLITE_OK ){
   50678         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
   50679         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
   50680         if( rc ){
   50681           releasePage(pOvfl);
   50682         }
   50683       }
   50684 #endif
   50685       if( rc ){
   50686         releasePage(pToRelease);
   50687         return rc;
   50688       }
   50689 
   50690       /* If pToRelease is not zero than pPrior points into the data area
   50691       ** of pToRelease.  Make sure pToRelease is still writeable. */
   50692       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   50693 
   50694       /* If pPrior is part of the data area of pPage, then make sure pPage
   50695       ** is still writeable */
   50696       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
   50697             || sqlite3PagerIswriteable(pPage->pDbPage) );
   50698 
   50699       put4byte(pPrior, pgnoOvfl);
   50700       releasePage(pToRelease);
   50701       pToRelease = pOvfl;
   50702       pPrior = pOvfl->aData;
   50703       put4byte(pPrior, 0);
   50704       pPayload = &pOvfl->aData[4];
   50705       spaceLeft = pBt->usableSize - 4;
   50706     }
   50707     n = nPayload;
   50708     if( n>spaceLeft ) n = spaceLeft;
   50709 
   50710     /* If pToRelease is not zero than pPayload points into the data area
   50711     ** of pToRelease.  Make sure pToRelease is still writeable. */
   50712     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
   50713 
   50714     /* If pPayload is part of the data area of pPage, then make sure pPage
   50715     ** is still writeable */
   50716     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
   50717             || sqlite3PagerIswriteable(pPage->pDbPage) );
   50718 
   50719     if( nSrc>0 ){
   50720       if( n>nSrc ) n = nSrc;
   50721       assert( pSrc );
   50722       memcpy(pPayload, pSrc, n);
   50723     }else{
   50724       memset(pPayload, 0, n);
   50725     }
   50726     nPayload -= n;
   50727     pPayload += n;
   50728     pSrc += n;
   50729     nSrc -= n;
   50730     spaceLeft -= n;
   50731     if( nSrc==0 ){
   50732       nSrc = nData;
   50733       pSrc = pData;
   50734     }
   50735   }
   50736   releasePage(pToRelease);
   50737   return SQLITE_OK;
   50738 }
   50739 
   50740 /*
   50741 ** Remove the i-th cell from pPage.  This routine effects pPage only.
   50742 ** The cell content is not freed or deallocated.  It is assumed that
   50743 ** the cell content has been copied someplace else.  This routine just
   50744 ** removes the reference to the cell from pPage.
   50745 **
   50746 ** "sz" must be the number of bytes in the cell.
   50747 */
   50748 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
   50749   int i;          /* Loop counter */
   50750   u32 pc;         /* Offset to cell content of cell being deleted */
   50751   u8 *data;       /* pPage->aData */
   50752   u8 *ptr;        /* Used to move bytes around within data[] */
   50753   int rc;         /* The return code */
   50754   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
   50755 
   50756   if( *pRC ) return;
   50757 
   50758   assert( idx>=0 && idx<pPage->nCell );
   50759   assert( sz==cellSize(pPage, idx) );
   50760   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50761   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50762   data = pPage->aData;
   50763   ptr = &data[pPage->cellOffset + 2*idx];
   50764   pc = get2byte(ptr);
   50765   hdr = pPage->hdrOffset;
   50766   testcase( pc==get2byte(&data[hdr+5]) );
   50767   testcase( pc+sz==pPage->pBt->usableSize );
   50768   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
   50769     *pRC = SQLITE_CORRUPT_BKPT;
   50770     return;
   50771   }
   50772   rc = freeSpace(pPage, pc, sz);
   50773   if( rc ){
   50774     *pRC = rc;
   50775     return;
   50776   }
   50777   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
   50778     ptr[0] = ptr[2];
   50779     ptr[1] = ptr[3];
   50780   }
   50781   pPage->nCell--;
   50782   put2byte(&data[hdr+3], pPage->nCell);
   50783   pPage->nFree += 2;
   50784 }
   50785 
   50786 /*
   50787 ** Insert a new cell on pPage at cell index "i".  pCell points to the
   50788 ** content of the cell.
   50789 **
   50790 ** If the cell content will fit on the page, then put it there.  If it
   50791 ** will not fit, then make a copy of the cell content into pTemp if
   50792 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
   50793 ** in pPage->aOvfl[] and make it point to the cell content (either
   50794 ** in pTemp or the original pCell) and also record its index.
   50795 ** Allocating a new entry in pPage->aCell[] implies that
   50796 ** pPage->nOverflow is incremented.
   50797 **
   50798 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
   50799 ** cell. The caller will overwrite them after this function returns. If
   50800 ** nSkip is non-zero, then pCell may not point to an invalid memory location
   50801 ** (but pCell+nSkip is always valid).
   50802 */
   50803 static void insertCell(
   50804   MemPage *pPage,   /* Page into which we are copying */
   50805   int i,            /* New cell becomes the i-th cell of the page */
   50806   u8 *pCell,        /* Content of the new cell */
   50807   int sz,           /* Bytes of content in pCell */
   50808   u8 *pTemp,        /* Temp storage space for pCell, if needed */
   50809   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
   50810   int *pRC          /* Read and write return code from here */
   50811 ){
   50812   int idx = 0;      /* Where to write new cell content in data[] */
   50813   int j;            /* Loop counter */
   50814   int end;          /* First byte past the last cell pointer in data[] */
   50815   int ins;          /* Index in data[] where new cell pointer is inserted */
   50816   int cellOffset;   /* Address of first cell pointer in data[] */
   50817   u8 *data;         /* The content of the whole page */
   50818   u8 *ptr;          /* Used for moving information around in data[] */
   50819 
   50820   int nSkip = (iChild ? 4 : 0);
   50821 
   50822   if( *pRC ) return;
   50823 
   50824   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
   50825   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
   50826   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
   50827   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50828   /* The cell should normally be sized correctly.  However, when moving a
   50829   ** malformed cell from a leaf page to an interior page, if the cell size
   50830   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
   50831   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
   50832   ** the term after the || in the following assert(). */
   50833   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
   50834   if( pPage->nOverflow || sz+2>pPage->nFree ){
   50835     if( pTemp ){
   50836       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
   50837       pCell = pTemp;
   50838     }
   50839     if( iChild ){
   50840       put4byte(pCell, iChild);
   50841     }
   50842     j = pPage->nOverflow++;
   50843     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
   50844     pPage->aOvfl[j].pCell = pCell;
   50845     pPage->aOvfl[j].idx = (u16)i;
   50846   }else{
   50847     int rc = sqlite3PagerWrite(pPage->pDbPage);
   50848     if( rc!=SQLITE_OK ){
   50849       *pRC = rc;
   50850       return;
   50851     }
   50852     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50853     data = pPage->aData;
   50854     cellOffset = pPage->cellOffset;
   50855     end = cellOffset + 2*pPage->nCell;
   50856     ins = cellOffset + 2*i;
   50857     rc = allocateSpace(pPage, sz, &idx);
   50858     if( rc ){ *pRC = rc; return; }
   50859     /* The allocateSpace() routine guarantees the following two properties
   50860     ** if it returns success */
   50861     assert( idx >= end+2 );
   50862     assert( idx+sz <= pPage->pBt->usableSize );
   50863     pPage->nCell++;
   50864     pPage->nFree -= (u16)(2 + sz);
   50865     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
   50866     if( iChild ){
   50867       put4byte(&data[idx], iChild);
   50868     }
   50869     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
   50870       ptr[0] = ptr[-2];
   50871       ptr[1] = ptr[-1];
   50872     }
   50873     put2byte(&data[ins], idx);
   50874     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
   50875 #ifndef SQLITE_OMIT_AUTOVACUUM
   50876     if( pPage->pBt->autoVacuum ){
   50877       /* The cell may contain a pointer to an overflow page. If so, write
   50878       ** the entry for the overflow page into the pointer map.
   50879       */
   50880       ptrmapPutOvflPtr(pPage, pCell, pRC);
   50881     }
   50882 #endif
   50883   }
   50884 }
   50885 
   50886 /*
   50887 ** Add a list of cells to a page.  The page should be initially empty.
   50888 ** The cells are guaranteed to fit on the page.
   50889 */
   50890 static void assemblePage(
   50891   MemPage *pPage,   /* The page to be assemblied */
   50892   int nCell,        /* The number of cells to add to this page */
   50893   u8 **apCell,      /* Pointers to cell bodies */
   50894   u16 *aSize        /* Sizes of the cells */
   50895 ){
   50896   int i;            /* Loop counter */
   50897   u8 *pCellptr;     /* Address of next cell pointer */
   50898   int cellbody;     /* Address of next cell body */
   50899   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
   50900   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
   50901   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
   50902 
   50903   assert( pPage->nOverflow==0 );
   50904   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50905   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
   50906   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   50907 
   50908   /* Check that the page has just been zeroed by zeroPage() */
   50909   assert( pPage->nCell==0 );
   50910   assert( get2byteNotZero(&data[hdr+5])==nUsable );
   50911 
   50912   pCellptr = &data[pPage->cellOffset + nCell*2];
   50913   cellbody = nUsable;
   50914   for(i=nCell-1; i>=0; i--){
   50915     pCellptr -= 2;
   50916     cellbody -= aSize[i];
   50917     put2byte(pCellptr, cellbody);
   50918     memcpy(&data[cellbody], apCell[i], aSize[i]);
   50919   }
   50920   put2byte(&data[hdr+3], nCell);
   50921   put2byte(&data[hdr+5], cellbody);
   50922   pPage->nFree -= (nCell*2 + nUsable - cellbody);
   50923   pPage->nCell = (u16)nCell;
   50924 }
   50925 
   50926 /*
   50927 ** The following parameters determine how many adjacent pages get involved
   50928 ** in a balancing operation.  NN is the number of neighbors on either side
   50929 ** of the page that participate in the balancing operation.  NB is the
   50930 ** total number of pages that participate, including the target page and
   50931 ** NN neighbors on either side.
   50932 **
   50933 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
   50934 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
   50935 ** in exchange for a larger degradation in INSERT and UPDATE performance.
   50936 ** The value of NN appears to give the best results overall.
   50937 */
   50938 #define NN 1             /* Number of neighbors on either side of pPage */
   50939 #define NB (NN*2+1)      /* Total pages involved in the balance */
   50940 
   50941 
   50942 #ifndef SQLITE_OMIT_QUICKBALANCE
   50943 /*
   50944 ** This version of balance() handles the common special case where
   50945 ** a new entry is being inserted on the extreme right-end of the
   50946 ** tree, in other words, when the new entry will become the largest
   50947 ** entry in the tree.
   50948 **
   50949 ** Instead of trying to balance the 3 right-most leaf pages, just add
   50950 ** a new page to the right-hand side and put the one new entry in
   50951 ** that page.  This leaves the right side of the tree somewhat
   50952 ** unbalanced.  But odds are that we will be inserting new entries
   50953 ** at the end soon afterwards so the nearly empty page will quickly
   50954 ** fill up.  On average.
   50955 **
   50956 ** pPage is the leaf page which is the right-most page in the tree.
   50957 ** pParent is its parent.  pPage must have a single overflow entry
   50958 ** which is also the right-most entry on the page.
   50959 **
   50960 ** The pSpace buffer is used to store a temporary copy of the divider
   50961 ** cell that will be inserted into pParent. Such a cell consists of a 4
   50962 ** byte page number followed by a variable length integer. In other
   50963 ** words, at most 13 bytes. Hence the pSpace buffer must be at
   50964 ** least 13 bytes in size.
   50965 */
   50966 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   50967   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
   50968   MemPage *pNew;                       /* Newly allocated page */
   50969   int rc;                              /* Return Code */
   50970   Pgno pgnoNew;                        /* Page number of pNew */
   50971 
   50972   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   50973   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   50974   assert( pPage->nOverflow==1 );
   50975 
   50976   /* This error condition is now caught prior to reaching this function */
   50977   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
   50978 
   50979   /* Allocate a new page. This page will become the right-sibling of
   50980   ** pPage. Make the parent page writable, so that the new divider cell
   50981   ** may be inserted. If both these operations are successful, proceed.
   50982   */
   50983   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
   50984 
   50985   if( rc==SQLITE_OK ){
   50986 
   50987     u8 *pOut = &pSpace[4];
   50988     u8 *pCell = pPage->aOvfl[0].pCell;
   50989     u16 szCell = cellSizePtr(pPage, pCell);
   50990     u8 *pStop;
   50991 
   50992     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
   50993     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
   50994     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
   50995     assemblePage(pNew, 1, &pCell, &szCell);
   50996 
   50997     /* If this is an auto-vacuum database, update the pointer map
   50998     ** with entries for the new page, and any pointer from the
   50999     ** cell on the page to an overflow page. If either of these
   51000     ** operations fails, the return code is set, but the contents
   51001     ** of the parent page are still manipulated by thh code below.
   51002     ** That is Ok, at this point the parent page is guaranteed to
   51003     ** be marked as dirty. Returning an error code will cause a
   51004     ** rollback, undoing any changes made to the parent page.
   51005     */
   51006     if( ISAUTOVACUUM ){
   51007       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
   51008       if( szCell>pNew->minLocal ){
   51009         ptrmapPutOvflPtr(pNew, pCell, &rc);
   51010       }
   51011     }
   51012 
   51013     /* Create a divider cell to insert into pParent. The divider cell
   51014     ** consists of a 4-byte page number (the page number of pPage) and
   51015     ** a variable length key value (which must be the same value as the
   51016     ** largest key on pPage).
   51017     **
   51018     ** To find the largest key value on pPage, first find the right-most
   51019     ** cell on pPage. The first two fields of this cell are the
   51020     ** record-length (a variable length integer at most 32-bits in size)
   51021     ** and the key value (a variable length integer, may have any value).
   51022     ** The first of the while(...) loops below skips over the record-length
   51023     ** field. The second while(...) loop copies the key value from the
   51024     ** cell on pPage into the pSpace buffer.
   51025     */
   51026     pCell = findCell(pPage, pPage->nCell-1);
   51027     pStop = &pCell[9];
   51028     while( (*(pCell++)&0x80) && pCell<pStop );
   51029     pStop = &pCell[9];
   51030     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
   51031 
   51032     /* Insert the new divider cell into pParent. */
   51033     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
   51034                0, pPage->pgno, &rc);
   51035 
   51036     /* Set the right-child pointer of pParent to point to the new page. */
   51037     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
   51038 
   51039     /* Release the reference to the new page. */
   51040     releasePage(pNew);
   51041   }
   51042 
   51043   return rc;
   51044 }
   51045 #endif /* SQLITE_OMIT_QUICKBALANCE */
   51046 
   51047 #if 0
   51048 /*
   51049 ** This function does not contribute anything to the operation of SQLite.
   51050 ** it is sometimes activated temporarily while debugging code responsible
   51051 ** for setting pointer-map entries.
   51052 */
   51053 static int ptrmapCheckPages(MemPage **apPage, int nPage){
   51054   int i, j;
   51055   for(i=0; i<nPage; i++){
   51056     Pgno n;
   51057     u8 e;
   51058     MemPage *pPage = apPage[i];
   51059     BtShared *pBt = pPage->pBt;
   51060     assert( pPage->isInit );
   51061 
   51062     for(j=0; j<pPage->nCell; j++){
   51063       CellInfo info;
   51064       u8 *z;
   51065 
   51066       z = findCell(pPage, j);
   51067       btreeParseCellPtr(pPage, z, &info);
   51068       if( info.iOverflow ){
   51069         Pgno ovfl = get4byte(&z[info.iOverflow]);
   51070         ptrmapGet(pBt, ovfl, &e, &n);
   51071         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
   51072       }
   51073       if( !pPage->leaf ){
   51074         Pgno child = get4byte(z);
   51075         ptrmapGet(pBt, child, &e, &n);
   51076         assert( n==pPage->pgno && e==PTRMAP_BTREE );
   51077       }
   51078     }
   51079     if( !pPage->leaf ){
   51080       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   51081       ptrmapGet(pBt, child, &e, &n);
   51082       assert( n==pPage->pgno && e==PTRMAP_BTREE );
   51083     }
   51084   }
   51085   return 1;
   51086 }
   51087 #endif
   51088 
   51089 /*
   51090 ** This function is used to copy the contents of the b-tree node stored
   51091 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
   51092 ** the pointer-map entries for each child page are updated so that the
   51093 ** parent page stored in the pointer map is page pTo. If pFrom contained
   51094 ** any cells with overflow page pointers, then the corresponding pointer
   51095 ** map entries are also updated so that the parent page is page pTo.
   51096 **
   51097 ** If pFrom is currently carrying any overflow cells (entries in the
   51098 ** MemPage.aOvfl[] array), they are not copied to pTo.
   51099 **
   51100 ** Before returning, page pTo is reinitialized using btreeInitPage().
   51101 **
   51102 ** The performance of this function is not critical. It is only used by
   51103 ** the balance_shallower() and balance_deeper() procedures, neither of
   51104 ** which are called often under normal circumstances.
   51105 */
   51106 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
   51107   if( (*pRC)==SQLITE_OK ){
   51108     BtShared * const pBt = pFrom->pBt;
   51109     u8 * const aFrom = pFrom->aData;
   51110     u8 * const aTo = pTo->aData;
   51111     int const iFromHdr = pFrom->hdrOffset;
   51112     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
   51113     int rc;
   51114     int iData;
   51115 
   51116 
   51117     assert( pFrom->isInit );
   51118     assert( pFrom->nFree>=iToHdr );
   51119     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
   51120 
   51121     /* Copy the b-tree node content from page pFrom to page pTo. */
   51122     iData = get2byte(&aFrom[iFromHdr+5]);
   51123     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
   51124     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
   51125 
   51126     /* Reinitialize page pTo so that the contents of the MemPage structure
   51127     ** match the new data. The initialization of pTo can actually fail under
   51128     ** fairly obscure circumstances, even though it is a copy of initialized
   51129     ** page pFrom.
   51130     */
   51131     pTo->isInit = 0;
   51132     rc = btreeInitPage(pTo);
   51133     if( rc!=SQLITE_OK ){
   51134       *pRC = rc;
   51135       return;
   51136     }
   51137 
   51138     /* If this is an auto-vacuum database, update the pointer-map entries
   51139     ** for any b-tree or overflow pages that pTo now contains the pointers to.
   51140     */
   51141     if( ISAUTOVACUUM ){
   51142       *pRC = setChildPtrmaps(pTo);
   51143     }
   51144   }
   51145 }
   51146 
   51147 /*
   51148 ** This routine redistributes cells on the iParentIdx'th child of pParent
   51149 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
   51150 ** same amount of free space. Usually a single sibling on either side of the
   51151 ** page are used in the balancing, though both siblings might come from one
   51152 ** side if the page is the first or last child of its parent. If the page
   51153 ** has fewer than 2 siblings (something which can only happen if the page
   51154 ** is a root page or a child of a root page) then all available siblings
   51155 ** participate in the balancing.
   51156 **
   51157 ** The number of siblings of the page might be increased or decreased by
   51158 ** one or two in an effort to keep pages nearly full but not over full.
   51159 **
   51160 ** Note that when this routine is called, some of the cells on the page
   51161 ** might not actually be stored in MemPage.aData[]. This can happen
   51162 ** if the page is overfull. This routine ensures that all cells allocated
   51163 ** to the page and its siblings fit into MemPage.aData[] before returning.
   51164 **
   51165 ** In the course of balancing the page and its siblings, cells may be
   51166 ** inserted into or removed from the parent page (pParent). Doing so
   51167 ** may cause the parent page to become overfull or underfull. If this
   51168 ** happens, it is the responsibility of the caller to invoke the correct
   51169 ** balancing routine to fix this problem (see the balance() routine).
   51170 **
   51171 ** If this routine fails for any reason, it might leave the database
   51172 ** in a corrupted state. So if this routine fails, the database should
   51173 ** be rolled back.
   51174 **
   51175 ** The third argument to this function, aOvflSpace, is a pointer to a
   51176 ** buffer big enough to hold one page. If while inserting cells into the parent
   51177 ** page (pParent) the parent page becomes overfull, this buffer is
   51178 ** used to store the parent's overflow cells. Because this function inserts
   51179 ** a maximum of four divider cells into the parent page, and the maximum
   51180 ** size of a cell stored within an internal node is always less than 1/4
   51181 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
   51182 ** enough for all overflow cells.
   51183 **
   51184 ** If aOvflSpace is set to a null pointer, this function returns
   51185 ** SQLITE_NOMEM.
   51186 */
   51187 static int balance_nonroot(
   51188   MemPage *pParent,               /* Parent page of siblings being balanced */
   51189   int iParentIdx,                 /* Index of "the page" in pParent */
   51190   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
   51191   int isRoot                      /* True if pParent is a root-page */
   51192 ){
   51193   BtShared *pBt;               /* The whole database */
   51194   int nCell = 0;               /* Number of cells in apCell[] */
   51195   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
   51196   int nNew = 0;                /* Number of pages in apNew[] */
   51197   int nOld;                    /* Number of pages in apOld[] */
   51198   int i, j, k;                 /* Loop counters */
   51199   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
   51200   int rc = SQLITE_OK;          /* The return code */
   51201   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
   51202   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
   51203   int usableSpace;             /* Bytes in pPage beyond the header */
   51204   int pageFlags;               /* Value of pPage->aData[0] */
   51205   int subtotal;                /* Subtotal of bytes in cells on one page */
   51206   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
   51207   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
   51208   int szScratch;               /* Size of scratch memory requested */
   51209   MemPage *apOld[NB];          /* pPage and up to two siblings */
   51210   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
   51211   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
   51212   u8 *pRight;                  /* Location in parent of right-sibling pointer */
   51213   u8 *apDiv[NB-1];             /* Divider cells in pParent */
   51214   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
   51215   int szNew[NB+2];             /* Combined size of cells place on i-th page */
   51216   u8 **apCell = 0;             /* All cells begin balanced */
   51217   u16 *szCell;                 /* Local size of all cells in apCell[] */
   51218   u8 *aSpace1;                 /* Space for copies of dividers cells */
   51219   Pgno pgno;                   /* Temp var to store a page number in */
   51220 
   51221   pBt = pParent->pBt;
   51222   assert( sqlite3_mutex_held(pBt->mutex) );
   51223   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   51224 
   51225 #if 0
   51226   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
   51227 #endif
   51228 
   51229   /* At this point pParent may have at most one overflow cell. And if
   51230   ** this overflow cell is present, it must be the cell with
   51231   ** index iParentIdx. This scenario comes about when this function
   51232   ** is called (indirectly) from sqlite3BtreeDelete().
   51233   */
   51234   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
   51235   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
   51236 
   51237   if( !aOvflSpace ){
   51238     return SQLITE_NOMEM;
   51239   }
   51240 
   51241   /* Find the sibling pages to balance. Also locate the cells in pParent
   51242   ** that divide the siblings. An attempt is made to find NN siblings on
   51243   ** either side of pPage. More siblings are taken from one side, however,
   51244   ** if there are fewer than NN siblings on the other side. If pParent
   51245   ** has NB or fewer children then all children of pParent are taken.
   51246   **
   51247   ** This loop also drops the divider cells from the parent page. This
   51248   ** way, the remainder of the function does not have to deal with any
   51249   ** overflow cells in the parent page, since if any existed they will
   51250   ** have already been removed.
   51251   */
   51252   i = pParent->nOverflow + pParent->nCell;
   51253   if( i<2 ){
   51254     nxDiv = 0;
   51255     nOld = i+1;
   51256   }else{
   51257     nOld = 3;
   51258     if( iParentIdx==0 ){
   51259       nxDiv = 0;
   51260     }else if( iParentIdx==i ){
   51261       nxDiv = i-2;
   51262     }else{
   51263       nxDiv = iParentIdx-1;
   51264     }
   51265     i = 2;
   51266   }
   51267   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
   51268     pRight = &pParent->aData[pParent->hdrOffset+8];
   51269   }else{
   51270     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
   51271   }
   51272   pgno = get4byte(pRight);
   51273   while( 1 ){
   51274     rc = getAndInitPage(pBt, pgno, &apOld[i]);
   51275     if( rc ){
   51276       memset(apOld, 0, (i+1)*sizeof(MemPage*));
   51277       goto balance_cleanup;
   51278     }
   51279     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
   51280     if( (i--)==0 ) break;
   51281 
   51282     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
   51283       apDiv[i] = pParent->aOvfl[0].pCell;
   51284       pgno = get4byte(apDiv[i]);
   51285       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   51286       pParent->nOverflow = 0;
   51287     }else{
   51288       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
   51289       pgno = get4byte(apDiv[i]);
   51290       szNew[i] = cellSizePtr(pParent, apDiv[i]);
   51291 
   51292       /* Drop the cell from the parent page. apDiv[i] still points to
   51293       ** the cell within the parent, even though it has been dropped.
   51294       ** This is safe because dropping a cell only overwrites the first
   51295       ** four bytes of it, and this function does not need the first
   51296       ** four bytes of the divider cell. So the pointer is safe to use
   51297       ** later on.
   51298       **
   51299       ** Unless SQLite is compiled in secure-delete mode. In this case,
   51300       ** the dropCell() routine will overwrite the entire cell with zeroes.
   51301       ** In this case, temporarily copy the cell into the aOvflSpace[]
   51302       ** buffer. It will be copied out again as soon as the aSpace[] buffer
   51303       ** is allocated.  */
   51304       if( pBt->secureDelete ){
   51305         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
   51306         if( (iOff+szNew[i])>(int)pBt->usableSize ){
   51307           rc = SQLITE_CORRUPT_BKPT;
   51308           memset(apOld, 0, (i+1)*sizeof(MemPage*));
   51309           goto balance_cleanup;
   51310         }else{
   51311           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
   51312           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
   51313         }
   51314       }
   51315       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
   51316     }
   51317   }
   51318 
   51319   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
   51320   ** alignment */
   51321   nMaxCells = (nMaxCells + 3)&~3;
   51322 
   51323   /*
   51324   ** Allocate space for memory structures
   51325   */
   51326   k = pBt->pageSize + ROUND8(sizeof(MemPage));
   51327   szScratch =
   51328        nMaxCells*sizeof(u8*)                       /* apCell */
   51329      + nMaxCells*sizeof(u16)                       /* szCell */
   51330      + pBt->pageSize                               /* aSpace1 */
   51331      + k*nOld;                                     /* Page copies (apCopy) */
   51332   apCell = sqlite3ScratchMalloc( szScratch );
   51333   if( apCell==0 ){
   51334     rc = SQLITE_NOMEM;
   51335     goto balance_cleanup;
   51336   }
   51337   szCell = (u16*)&apCell[nMaxCells];
   51338   aSpace1 = (u8*)&szCell[nMaxCells];
   51339   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
   51340 
   51341   /*
   51342   ** Load pointers to all cells on sibling pages and the divider cells
   51343   ** into the local apCell[] array.  Make copies of the divider cells
   51344   ** into space obtained from aSpace1[] and remove the the divider Cells
   51345   ** from pParent.
   51346   **
   51347   ** If the siblings are on leaf pages, then the child pointers of the
   51348   ** divider cells are stripped from the cells before they are copied
   51349   ** into aSpace1[].  In this way, all cells in apCell[] are without
   51350   ** child pointers.  If siblings are not leaves, then all cell in
   51351   ** apCell[] include child pointers.  Either way, all cells in apCell[]
   51352   ** are alike.
   51353   **
   51354   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
   51355   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
   51356   */
   51357   leafCorrection = apOld[0]->leaf*4;
   51358   leafData = apOld[0]->hasData;
   51359   for(i=0; i<nOld; i++){
   51360     int limit;
   51361 
   51362     /* Before doing anything else, take a copy of the i'th original sibling
   51363     ** The rest of this function will use data from the copies rather
   51364     ** that the original pages since the original pages will be in the
   51365     ** process of being overwritten.  */
   51366     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
   51367     memcpy(pOld, apOld[i], sizeof(MemPage));
   51368     pOld->aData = (void*)&pOld[1];
   51369     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
   51370 
   51371     limit = pOld->nCell+pOld->nOverflow;
   51372     for(j=0; j<limit; j++){
   51373       assert( nCell<nMaxCells );
   51374       apCell[nCell] = findOverflowCell(pOld, j);
   51375       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
   51376       nCell++;
   51377     }
   51378     if( i<nOld-1 && !leafData){
   51379       u16 sz = (u16)szNew[i];
   51380       u8 *pTemp;
   51381       assert( nCell<nMaxCells );
   51382       szCell[nCell] = sz;
   51383       pTemp = &aSpace1[iSpace1];
   51384       iSpace1 += sz;
   51385       assert( sz<=pBt->maxLocal+23 );
   51386       assert( iSpace1<=pBt->pageSize );
   51387       memcpy(pTemp, apDiv[i], sz);
   51388       apCell[nCell] = pTemp+leafCorrection;
   51389       assert( leafCorrection==0 || leafCorrection==4 );
   51390       szCell[nCell] = szCell[nCell] - leafCorrection;
   51391       if( !pOld->leaf ){
   51392         assert( leafCorrection==0 );
   51393         assert( pOld->hdrOffset==0 );
   51394         /* The right pointer of the child page pOld becomes the left
   51395         ** pointer of the divider cell */
   51396         memcpy(apCell[nCell], &pOld->aData[8], 4);
   51397       }else{
   51398         assert( leafCorrection==4 );
   51399         if( szCell[nCell]<4 ){
   51400           /* Do not allow any cells smaller than 4 bytes. */
   51401           szCell[nCell] = 4;
   51402         }
   51403       }
   51404       nCell++;
   51405     }
   51406   }
   51407 
   51408   /*
   51409   ** Figure out the number of pages needed to hold all nCell cells.
   51410   ** Store this number in "k".  Also compute szNew[] which is the total
   51411   ** size of all cells on the i-th page and cntNew[] which is the index
   51412   ** in apCell[] of the cell that divides page i from page i+1.
   51413   ** cntNew[k] should equal nCell.
   51414   **
   51415   ** Values computed by this block:
   51416   **
   51417   **           k: The total number of sibling pages
   51418   **    szNew[i]: Spaced used on the i-th sibling page.
   51419   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
   51420   **              the right of the i-th sibling page.
   51421   ** usableSpace: Number of bytes of space available on each sibling.
   51422   **
   51423   */
   51424   usableSpace = pBt->usableSize - 12 + leafCorrection;
   51425   for(subtotal=k=i=0; i<nCell; i++){
   51426     assert( i<nMaxCells );
   51427     subtotal += szCell[i] + 2;
   51428     if( subtotal > usableSpace ){
   51429       szNew[k] = subtotal - szCell[i];
   51430       cntNew[k] = i;
   51431       if( leafData ){ i--; }
   51432       subtotal = 0;
   51433       k++;
   51434       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
   51435     }
   51436   }
   51437   szNew[k] = subtotal;
   51438   cntNew[k] = nCell;
   51439   k++;
   51440 
   51441   /*
   51442   ** The packing computed by the previous block is biased toward the siblings
   51443   ** on the left side.  The left siblings are always nearly full, while the
   51444   ** right-most sibling might be nearly empty.  This block of code attempts
   51445   ** to adjust the packing of siblings to get a better balance.
   51446   **
   51447   ** This adjustment is more than an optimization.  The packing above might
   51448   ** be so out of balance as to be illegal.  For example, the right-most
   51449   ** sibling might be completely empty.  This adjustment is not optional.
   51450   */
   51451   for(i=k-1; i>0; i--){
   51452     int szRight = szNew[i];  /* Size of sibling on the right */
   51453     int szLeft = szNew[i-1]; /* Size of sibling on the left */
   51454     int r;              /* Index of right-most cell in left sibling */
   51455     int d;              /* Index of first cell to the left of right sibling */
   51456 
   51457     r = cntNew[i-1] - 1;
   51458     d = r + 1 - leafData;
   51459     assert( d<nMaxCells );
   51460     assert( r<nMaxCells );
   51461     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
   51462       szRight += szCell[d] + 2;
   51463       szLeft -= szCell[r] + 2;
   51464       cntNew[i-1]--;
   51465       r = cntNew[i-1] - 1;
   51466       d = r + 1 - leafData;
   51467     }
   51468     szNew[i] = szRight;
   51469     szNew[i-1] = szLeft;
   51470   }
   51471 
   51472   /* Either we found one or more cells (cntnew[0])>0) or pPage is
   51473   ** a virtual root page.  A virtual root page is when the real root
   51474   ** page is page 1 and we are the only child of that page.
   51475   */
   51476   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
   51477 
   51478   TRACE(("BALANCE: old: %d %d %d  ",
   51479     apOld[0]->pgno,
   51480     nOld>=2 ? apOld[1]->pgno : 0,
   51481     nOld>=3 ? apOld[2]->pgno : 0
   51482   ));
   51483 
   51484   /*
   51485   ** Allocate k new pages.  Reuse old pages where possible.
   51486   */
   51487   if( apOld[0]->pgno<=1 ){
   51488     rc = SQLITE_CORRUPT_BKPT;
   51489     goto balance_cleanup;
   51490   }
   51491   pageFlags = apOld[0]->aData[0];
   51492   for(i=0; i<k; i++){
   51493     MemPage *pNew;
   51494     if( i<nOld ){
   51495       pNew = apNew[i] = apOld[i];
   51496       apOld[i] = 0;
   51497       rc = sqlite3PagerWrite(pNew->pDbPage);
   51498       nNew++;
   51499       if( rc ) goto balance_cleanup;
   51500     }else{
   51501       assert( i>0 );
   51502       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
   51503       if( rc ) goto balance_cleanup;
   51504       apNew[i] = pNew;
   51505       nNew++;
   51506 
   51507       /* Set the pointer-map entry for the new sibling page. */
   51508       if( ISAUTOVACUUM ){
   51509         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
   51510         if( rc!=SQLITE_OK ){
   51511           goto balance_cleanup;
   51512         }
   51513       }
   51514     }
   51515   }
   51516 
   51517   /* Free any old pages that were not reused as new pages.
   51518   */
   51519   while( i<nOld ){
   51520     freePage(apOld[i], &rc);
   51521     if( rc ) goto balance_cleanup;
   51522     releasePage(apOld[i]);
   51523     apOld[i] = 0;
   51524     i++;
   51525   }
   51526 
   51527   /*
   51528   ** Put the new pages in accending order.  This helps to
   51529   ** keep entries in the disk file in order so that a scan
   51530   ** of the table is a linear scan through the file.  That
   51531   ** in turn helps the operating system to deliver pages
   51532   ** from the disk more rapidly.
   51533   **
   51534   ** An O(n^2) insertion sort algorithm is used, but since
   51535   ** n is never more than NB (a small constant), that should
   51536   ** not be a problem.
   51537   **
   51538   ** When NB==3, this one optimization makes the database
   51539   ** about 25% faster for large insertions and deletions.
   51540   */
   51541   for(i=0; i<k-1; i++){
   51542     int minV = apNew[i]->pgno;
   51543     int minI = i;
   51544     for(j=i+1; j<k; j++){
   51545       if( apNew[j]->pgno<(unsigned)minV ){
   51546         minI = j;
   51547         minV = apNew[j]->pgno;
   51548       }
   51549     }
   51550     if( minI>i ){
   51551       int t;
   51552       MemPage *pT;
   51553       t = apNew[i]->pgno;
   51554       pT = apNew[i];
   51555       apNew[i] = apNew[minI];
   51556       apNew[minI] = pT;
   51557     }
   51558   }
   51559   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
   51560     apNew[0]->pgno, szNew[0],
   51561     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
   51562     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
   51563     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
   51564     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
   51565 
   51566   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   51567   put4byte(pRight, apNew[nNew-1]->pgno);
   51568 
   51569   /*
   51570   ** Evenly distribute the data in apCell[] across the new pages.
   51571   ** Insert divider cells into pParent as necessary.
   51572   */
   51573   j = 0;
   51574   for(i=0; i<nNew; i++){
   51575     /* Assemble the new sibling page. */
   51576     MemPage *pNew = apNew[i];
   51577     assert( j<nMaxCells );
   51578     zeroPage(pNew, pageFlags);
   51579     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
   51580     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
   51581     assert( pNew->nOverflow==0 );
   51582 
   51583     j = cntNew[i];
   51584 
   51585     /* If the sibling page assembled above was not the right-most sibling,
   51586     ** insert a divider cell into the parent page.
   51587     */
   51588     assert( i<nNew-1 || j==nCell );
   51589     if( j<nCell ){
   51590       u8 *pCell;
   51591       u8 *pTemp;
   51592       int sz;
   51593 
   51594       assert( j<nMaxCells );
   51595       pCell = apCell[j];
   51596       sz = szCell[j] + leafCorrection;
   51597       pTemp = &aOvflSpace[iOvflSpace];
   51598       if( !pNew->leaf ){
   51599         memcpy(&pNew->aData[8], pCell, 4);
   51600       }else if( leafData ){
   51601         /* If the tree is a leaf-data tree, and the siblings are leaves,
   51602         ** then there is no divider cell in apCell[]. Instead, the divider
   51603         ** cell consists of the integer key for the right-most cell of
   51604         ** the sibling-page assembled above only.
   51605         */
   51606         CellInfo info;
   51607         j--;
   51608         btreeParseCellPtr(pNew, apCell[j], &info);
   51609         pCell = pTemp;
   51610         sz = 4 + putVarint(&pCell[4], info.nKey);
   51611         pTemp = 0;
   51612       }else{
   51613         pCell -= 4;
   51614         /* Obscure case for non-leaf-data trees: If the cell at pCell was
   51615         ** previously stored on a leaf node, and its reported size was 4
   51616         ** bytes, then it may actually be smaller than this
   51617         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
   51618         ** any cell). But it is important to pass the correct size to
   51619         ** insertCell(), so reparse the cell now.
   51620         **
   51621         ** Note that this can never happen in an SQLite data file, as all
   51622         ** cells are at least 4 bytes. It only happens in b-trees used
   51623         ** to evaluate "IN (SELECT ...)" and similar clauses.
   51624         */
   51625         if( szCell[j]==4 ){
   51626           assert(leafCorrection==4);
   51627           sz = cellSizePtr(pParent, pCell);
   51628         }
   51629       }
   51630       iOvflSpace += sz;
   51631       assert( sz<=pBt->maxLocal+23 );
   51632       assert( iOvflSpace<=pBt->pageSize );
   51633       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
   51634       if( rc!=SQLITE_OK ) goto balance_cleanup;
   51635       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   51636 
   51637       j++;
   51638       nxDiv++;
   51639     }
   51640   }
   51641   assert( j==nCell );
   51642   assert( nOld>0 );
   51643   assert( nNew>0 );
   51644   if( (pageFlags & PTF_LEAF)==0 ){
   51645     u8 *zChild = &apCopy[nOld-1]->aData[8];
   51646     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
   51647   }
   51648 
   51649   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
   51650     /* The root page of the b-tree now contains no cells. The only sibling
   51651     ** page is the right-child of the parent. Copy the contents of the
   51652     ** child page into the parent, decreasing the overall height of the
   51653     ** b-tree structure by one. This is described as the "balance-shallower"
   51654     ** sub-algorithm in some documentation.
   51655     **
   51656     ** If this is an auto-vacuum database, the call to copyNodeContent()
   51657     ** sets all pointer-map entries corresponding to database image pages
   51658     ** for which the pointer is stored within the content being copied.
   51659     **
   51660     ** The second assert below verifies that the child page is defragmented
   51661     ** (it must be, as it was just reconstructed using assemblePage()). This
   51662     ** is important if the parent page happens to be page 1 of the database
   51663     ** image.  */
   51664     assert( nNew==1 );
   51665     assert( apNew[0]->nFree ==
   51666         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
   51667     );
   51668     copyNodeContent(apNew[0], pParent, &rc);
   51669     freePage(apNew[0], &rc);
   51670   }else if( ISAUTOVACUUM ){
   51671     /* Fix the pointer-map entries for all the cells that were shifted around.
   51672     ** There are several different types of pointer-map entries that need to
   51673     ** be dealt with by this routine. Some of these have been set already, but
   51674     ** many have not. The following is a summary:
   51675     **
   51676     **   1) The entries associated with new sibling pages that were not
   51677     **      siblings when this function was called. These have already
   51678     **      been set. We don't need to worry about old siblings that were
   51679     **      moved to the free-list - the freePage() code has taken care
   51680     **      of those.
   51681     **
   51682     **   2) The pointer-map entries associated with the first overflow
   51683     **      page in any overflow chains used by new divider cells. These
   51684     **      have also already been taken care of by the insertCell() code.
   51685     **
   51686     **   3) If the sibling pages are not leaves, then the child pages of
   51687     **      cells stored on the sibling pages may need to be updated.
   51688     **
   51689     **   4) If the sibling pages are not internal intkey nodes, then any
   51690     **      overflow pages used by these cells may need to be updated
   51691     **      (internal intkey nodes never contain pointers to overflow pages).
   51692     **
   51693     **   5) If the sibling pages are not leaves, then the pointer-map
   51694     **      entries for the right-child pages of each sibling may need
   51695     **      to be updated.
   51696     **
   51697     ** Cases 1 and 2 are dealt with above by other code. The next
   51698     ** block deals with cases 3 and 4 and the one after that, case 5. Since
   51699     ** setting a pointer map entry is a relatively expensive operation, this
   51700     ** code only sets pointer map entries for child or overflow pages that have
   51701     ** actually moved between pages.  */
   51702     MemPage *pNew = apNew[0];
   51703     MemPage *pOld = apCopy[0];
   51704     int nOverflow = pOld->nOverflow;
   51705     int iNextOld = pOld->nCell + nOverflow;
   51706     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
   51707     j = 0;                             /* Current 'old' sibling page */
   51708     k = 0;                             /* Current 'new' sibling page */
   51709     for(i=0; i<nCell; i++){
   51710       int isDivider = 0;
   51711       while( i==iNextOld ){
   51712         /* Cell i is the cell immediately following the last cell on old
   51713         ** sibling page j. If the siblings are not leaf pages of an
   51714         ** intkey b-tree, then cell i was a divider cell. */
   51715         pOld = apCopy[++j];
   51716         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
   51717         if( pOld->nOverflow ){
   51718           nOverflow = pOld->nOverflow;
   51719           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
   51720         }
   51721         isDivider = !leafData;
   51722       }
   51723 
   51724       assert(nOverflow>0 || iOverflow<i );
   51725       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
   51726       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
   51727       if( i==iOverflow ){
   51728         isDivider = 1;
   51729         if( (--nOverflow)>0 ){
   51730           iOverflow++;
   51731         }
   51732       }
   51733 
   51734       if( i==cntNew[k] ){
   51735         /* Cell i is the cell immediately following the last cell on new
   51736         ** sibling page k. If the siblings are not leaf pages of an
   51737         ** intkey b-tree, then cell i is a divider cell.  */
   51738         pNew = apNew[++k];
   51739         if( !leafData ) continue;
   51740       }
   51741       assert( j<nOld );
   51742       assert( k<nNew );
   51743 
   51744       /* If the cell was originally divider cell (and is not now) or
   51745       ** an overflow cell, or if the cell was located on a different sibling
   51746       ** page before the balancing, then the pointer map entries associated
   51747       ** with any child or overflow pages need to be updated.  */
   51748       if( isDivider || pOld->pgno!=pNew->pgno ){
   51749         if( !leafCorrection ){
   51750           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
   51751         }
   51752         if( szCell[i]>pNew->minLocal ){
   51753           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
   51754         }
   51755       }
   51756     }
   51757 
   51758     if( !leafCorrection ){
   51759       for(i=0; i<nNew; i++){
   51760         u32 key = get4byte(&apNew[i]->aData[8]);
   51761         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
   51762       }
   51763     }
   51764 
   51765 #if 0
   51766     /* The ptrmapCheckPages() contains assert() statements that verify that
   51767     ** all pointer map pages are set correctly. This is helpful while
   51768     ** debugging. This is usually disabled because a corrupt database may
   51769     ** cause an assert() statement to fail.  */
   51770     ptrmapCheckPages(apNew, nNew);
   51771     ptrmapCheckPages(&pParent, 1);
   51772 #endif
   51773   }
   51774 
   51775   assert( pParent->isInit );
   51776   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
   51777           nOld, nNew, nCell));
   51778 
   51779   /*
   51780   ** Cleanup before returning.
   51781   */
   51782 balance_cleanup:
   51783   sqlite3ScratchFree(apCell);
   51784   for(i=0; i<nOld; i++){
   51785     releasePage(apOld[i]);
   51786   }
   51787   for(i=0; i<nNew; i++){
   51788     releasePage(apNew[i]);
   51789   }
   51790 
   51791   return rc;
   51792 }
   51793 
   51794 
   51795 /*
   51796 ** This function is called when the root page of a b-tree structure is
   51797 ** overfull (has one or more overflow pages).
   51798 **
   51799 ** A new child page is allocated and the contents of the current root
   51800 ** page, including overflow cells, are copied into the child. The root
   51801 ** page is then overwritten to make it an empty page with the right-child
   51802 ** pointer pointing to the new page.
   51803 **
   51804 ** Before returning, all pointer-map entries corresponding to pages
   51805 ** that the new child-page now contains pointers to are updated. The
   51806 ** entry corresponding to the new right-child pointer of the root
   51807 ** page is also updated.
   51808 **
   51809 ** If successful, *ppChild is set to contain a reference to the child
   51810 ** page and SQLITE_OK is returned. In this case the caller is required
   51811 ** to call releasePage() on *ppChild exactly once. If an error occurs,
   51812 ** an error code is returned and *ppChild is set to 0.
   51813 */
   51814 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   51815   int rc;                        /* Return value from subprocedures */
   51816   MemPage *pChild = 0;           /* Pointer to a new child page */
   51817   Pgno pgnoChild = 0;            /* Page number of the new child page */
   51818   BtShared *pBt = pRoot->pBt;    /* The BTree */
   51819 
   51820   assert( pRoot->nOverflow>0 );
   51821   assert( sqlite3_mutex_held(pBt->mutex) );
   51822 
   51823   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   51824   ** page that will become the new right-child of pPage. Copy the contents
   51825   ** of the node stored on pRoot into the new child page.
   51826   */
   51827   rc = sqlite3PagerWrite(pRoot->pDbPage);
   51828   if( rc==SQLITE_OK ){
   51829     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
   51830     copyNodeContent(pRoot, pChild, &rc);
   51831     if( ISAUTOVACUUM ){
   51832       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
   51833     }
   51834   }
   51835   if( rc ){
   51836     *ppChild = 0;
   51837     releasePage(pChild);
   51838     return rc;
   51839   }
   51840   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
   51841   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   51842   assert( pChild->nCell==pRoot->nCell );
   51843 
   51844   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
   51845 
   51846   /* Copy the overflow cells from pRoot to pChild */
   51847   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
   51848   pChild->nOverflow = pRoot->nOverflow;
   51849 
   51850   /* Zero the contents of pRoot. Then install pChild as the right-child. */
   51851   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
   51852   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
   51853 
   51854   *ppChild = pChild;
   51855   return SQLITE_OK;
   51856 }
   51857 
   51858 /*
   51859 ** The page that pCur currently points to has just been modified in
   51860 ** some way. This function figures out if this modification means the
   51861 ** tree needs to be balanced, and if so calls the appropriate balancing
   51862 ** routine. Balancing routines are:
   51863 **
   51864 **   balance_quick()
   51865 **   balance_deeper()
   51866 **   balance_nonroot()
   51867 */
   51868 static int balance(BtCursor *pCur){
   51869   int rc = SQLITE_OK;
   51870   const int nMin = pCur->pBt->usableSize * 2 / 3;
   51871   u8 aBalanceQuickSpace[13];
   51872   u8 *pFree = 0;
   51873 
   51874   TESTONLY( int balance_quick_called = 0 );
   51875   TESTONLY( int balance_deeper_called = 0 );
   51876 
   51877   do {
   51878     int iPage = pCur->iPage;
   51879     MemPage *pPage = pCur->apPage[iPage];
   51880 
   51881     if( iPage==0 ){
   51882       if( pPage->nOverflow ){
   51883         /* The root page of the b-tree is overfull. In this case call the
   51884         ** balance_deeper() function to create a new child for the root-page
   51885         ** and copy the current contents of the root-page to it. The
   51886         ** next iteration of the do-loop will balance the child page.
   51887         */
   51888         assert( (balance_deeper_called++)==0 );
   51889         rc = balance_deeper(pPage, &pCur->apPage[1]);
   51890         if( rc==SQLITE_OK ){
   51891           pCur->iPage = 1;
   51892           pCur->aiIdx[0] = 0;
   51893           pCur->aiIdx[1] = 0;
   51894           assert( pCur->apPage[1]->nOverflow );
   51895         }
   51896       }else{
   51897         break;
   51898       }
   51899     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
   51900       break;
   51901     }else{
   51902       MemPage * const pParent = pCur->apPage[iPage-1];
   51903       int const iIdx = pCur->aiIdx[iPage-1];
   51904 
   51905       rc = sqlite3PagerWrite(pParent->pDbPage);
   51906       if( rc==SQLITE_OK ){
   51907 #ifndef SQLITE_OMIT_QUICKBALANCE
   51908         if( pPage->hasData
   51909          && pPage->nOverflow==1
   51910          && pPage->aOvfl[0].idx==pPage->nCell
   51911          && pParent->pgno!=1
   51912          && pParent->nCell==iIdx
   51913         ){
   51914           /* Call balance_quick() to create a new sibling of pPage on which
   51915           ** to store the overflow cell. balance_quick() inserts a new cell
   51916           ** into pParent, which may cause pParent overflow. If this
   51917           ** happens, the next interation of the do-loop will balance pParent
   51918           ** use either balance_nonroot() or balance_deeper(). Until this
   51919           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
   51920           ** buffer.
   51921           **
   51922           ** The purpose of the following assert() is to check that only a
   51923           ** single call to balance_quick() is made for each call to this
   51924           ** function. If this were not verified, a subtle bug involving reuse
   51925           ** of the aBalanceQuickSpace[] might sneak in.
   51926           */
   51927           assert( (balance_quick_called++)==0 );
   51928           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
   51929         }else
   51930 #endif
   51931         {
   51932           /* In this case, call balance_nonroot() to redistribute cells
   51933           ** between pPage and up to 2 of its sibling pages. This involves
   51934           ** modifying the contents of pParent, which may cause pParent to
   51935           ** become overfull or underfull. The next iteration of the do-loop
   51936           ** will balance the parent page to correct this.
   51937           **
   51938           ** If the parent page becomes overfull, the overflow cell or cells
   51939           ** are stored in the pSpace buffer allocated immediately below.
   51940           ** A subsequent iteration of the do-loop will deal with this by
   51941           ** calling balance_nonroot() (balance_deeper() may be called first,
   51942           ** but it doesn't deal with overflow cells - just moves them to a
   51943           ** different page). Once this subsequent call to balance_nonroot()
   51944           ** has completed, it is safe to release the pSpace buffer used by
   51945           ** the previous call, as the overflow cell data will have been
   51946           ** copied either into the body of a database page or into the new
   51947           ** pSpace buffer passed to the latter call to balance_nonroot().
   51948           */
   51949           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
   51950           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
   51951           if( pFree ){
   51952             /* If pFree is not NULL, it points to the pSpace buffer used
   51953             ** by a previous call to balance_nonroot(). Its contents are
   51954             ** now stored either on real database pages or within the
   51955             ** new pSpace buffer, so it may be safely freed here. */
   51956             sqlite3PageFree(pFree);
   51957           }
   51958 
   51959           /* The pSpace buffer will be freed after the next call to
   51960           ** balance_nonroot(), or just before this function returns, whichever
   51961           ** comes first. */
   51962           pFree = pSpace;
   51963         }
   51964       }
   51965 
   51966       pPage->nOverflow = 0;
   51967 
   51968       /* The next iteration of the do-loop balances the parent page. */
   51969       releasePage(pPage);
   51970       pCur->iPage--;
   51971     }
   51972   }while( rc==SQLITE_OK );
   51973 
   51974   if( pFree ){
   51975     sqlite3PageFree(pFree);
   51976   }
   51977   return rc;
   51978 }
   51979 
   51980 
   51981 /*
   51982 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
   51983 ** and the data is given by (pData,nData).  The cursor is used only to
   51984 ** define what table the record should be inserted into.  The cursor
   51985 ** is left pointing at a random location.
   51986 **
   51987 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
   51988 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
   51989 **
   51990 ** If the seekResult parameter is non-zero, then a successful call to
   51991 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
   51992 ** been performed. seekResult is the search result returned (a negative
   51993 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
   51994 ** a positive value if pCur points at an etry that is larger than
   51995 ** (pKey, nKey)).
   51996 **
   51997 ** If the seekResult parameter is non-zero, then the caller guarantees that
   51998 ** cursor pCur is pointing at the existing copy of a row that is to be
   51999 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
   52000 ** point to any entry or to no entry at all and so this function has to seek
   52001 ** the cursor before the new key can be inserted.
   52002 */
   52003 SQLITE_PRIVATE int sqlite3BtreeInsert(
   52004   BtCursor *pCur,                /* Insert data into the table of this cursor */
   52005   const void *pKey, i64 nKey,    /* The key of the new record */
   52006   const void *pData, int nData,  /* The data of the new record */
   52007   int nZero,                     /* Number of extra 0 bytes to append to data */
   52008   int appendBias,                /* True if this is likely an append */
   52009   int seekResult                 /* Result of prior MovetoUnpacked() call */
   52010 ){
   52011   int rc;
   52012   int loc = seekResult;          /* -1: before desired location  +1: after */
   52013   int szNew = 0;
   52014   int idx;
   52015   MemPage *pPage;
   52016   Btree *p = pCur->pBtree;
   52017   BtShared *pBt = p->pBt;
   52018   unsigned char *oldCell;
   52019   unsigned char *newCell = 0;
   52020 
   52021   if( pCur->eState==CURSOR_FAULT ){
   52022     assert( pCur->skipNext!=SQLITE_OK );
   52023     return pCur->skipNext;
   52024   }
   52025 
   52026   assert( cursorHoldsMutex(pCur) );
   52027   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
   52028   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   52029 
   52030   /* Assert that the caller has been consistent. If this cursor was opened
   52031   ** expecting an index b-tree, then the caller should be inserting blob
   52032   ** keys with no associated data. If the cursor was opened expecting an
   52033   ** intkey table, the caller should be inserting integer keys with a
   52034   ** blob of associated data.  */
   52035   assert( (pKey==0)==(pCur->pKeyInfo==0) );
   52036 
   52037   /* If this is an insert into a table b-tree, invalidate any incrblob
   52038   ** cursors open on the row being replaced (assuming this is a replace
   52039   ** operation - if it is not, the following is a no-op).  */
   52040   if( pCur->pKeyInfo==0 ){
   52041     invalidateIncrblobCursors(p, nKey, 0);
   52042   }
   52043 
   52044   /* Save the positions of any other cursors open on this table.
   52045   **
   52046   ** In some cases, the call to btreeMoveto() below is a no-op. For
   52047   ** example, when inserting data into a table with auto-generated integer
   52048   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
   52049   ** integer key to use. It then calls this function to actually insert the
   52050   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   52051   ** that the cursor is already where it needs to be and returns without
   52052   ** doing any work. To avoid thwarting these optimizations, it is important
   52053   ** not to clear the cursor here.
   52054   */
   52055   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   52056   if( rc ) return rc;
   52057   if( !loc ){
   52058     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
   52059     if( rc ) return rc;
   52060   }
   52061   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
   52062 
   52063   pPage = pCur->apPage[pCur->iPage];
   52064   assert( pPage->intKey || nKey>=0 );
   52065   assert( pPage->leaf || !pPage->intKey );
   52066 
   52067   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
   52068           pCur->pgnoRoot, nKey, nData, pPage->pgno,
   52069           loc==0 ? "overwrite" : "new entry"));
   52070   assert( pPage->isInit );
   52071   allocateTempSpace(pBt);
   52072   newCell = pBt->pTmpSpace;
   52073   if( newCell==0 ) return SQLITE_NOMEM;
   52074   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
   52075   if( rc ) goto end_insert;
   52076   assert( szNew==cellSizePtr(pPage, newCell) );
   52077   assert( szNew<=MX_CELL_SIZE(pBt) );
   52078   idx = pCur->aiIdx[pCur->iPage];
   52079   if( loc==0 ){
   52080     u16 szOld;
   52081     assert( idx<pPage->nCell );
   52082     rc = sqlite3PagerWrite(pPage->pDbPage);
   52083     if( rc ){
   52084       goto end_insert;
   52085     }
   52086     oldCell = findCell(pPage, idx);
   52087     if( !pPage->leaf ){
   52088       memcpy(newCell, oldCell, 4);
   52089     }
   52090     szOld = cellSizePtr(pPage, oldCell);
   52091     rc = clearCell(pPage, oldCell);
   52092     dropCell(pPage, idx, szOld, &rc);
   52093     if( rc ) goto end_insert;
   52094   }else if( loc<0 && pPage->nCell>0 ){
   52095     assert( pPage->leaf );
   52096     idx = ++pCur->aiIdx[pCur->iPage];
   52097   }else{
   52098     assert( pPage->leaf );
   52099   }
   52100   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
   52101   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
   52102 
   52103   /* If no error has occured and pPage has an overflow cell, call balance()
   52104   ** to redistribute the cells within the tree. Since balance() may move
   52105   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
   52106   ** variables.
   52107   **
   52108   ** Previous versions of SQLite called moveToRoot() to move the cursor
   52109   ** back to the root page as balance() used to invalidate the contents
   52110   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
   52111   ** set the cursor state to "invalid". This makes common insert operations
   52112   ** slightly faster.
   52113   **
   52114   ** There is a subtle but important optimization here too. When inserting
   52115   ** multiple records into an intkey b-tree using a single cursor (as can
   52116   ** happen while processing an "INSERT INTO ... SELECT" statement), it
   52117   ** is advantageous to leave the cursor pointing to the last entry in
   52118   ** the b-tree if possible. If the cursor is left pointing to the last
   52119   ** entry in the table, and the next row inserted has an integer key
   52120   ** larger than the largest existing key, it is possible to insert the
   52121   ** row without seeking the cursor. This can be a big performance boost.
   52122   */
   52123   pCur->info.nSize = 0;
   52124   pCur->validNKey = 0;
   52125   if( rc==SQLITE_OK && pPage->nOverflow ){
   52126     rc = balance(pCur);
   52127 
   52128     /* Must make sure nOverflow is reset to zero even if the balance()
   52129     ** fails. Internal data structure corruption will result otherwise.
   52130     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
   52131     ** from trying to save the current position of the cursor.  */
   52132     pCur->apPage[pCur->iPage]->nOverflow = 0;
   52133     pCur->eState = CURSOR_INVALID;
   52134   }
   52135   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
   52136 
   52137 end_insert:
   52138   return rc;
   52139 }
   52140 
   52141 /*
   52142 ** Delete the entry that the cursor is pointing to.  The cursor
   52143 ** is left pointing at a arbitrary location.
   52144 */
   52145 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
   52146   Btree *p = pCur->pBtree;
   52147   BtShared *pBt = p->pBt;
   52148   int rc;                              /* Return code */
   52149   MemPage *pPage;                      /* Page to delete cell from */
   52150   unsigned char *pCell;                /* Pointer to cell to delete */
   52151   int iCellIdx;                        /* Index of cell to delete */
   52152   int iCellDepth;                      /* Depth of node containing pCell */
   52153 
   52154   assert( cursorHoldsMutex(pCur) );
   52155   assert( pBt->inTransaction==TRANS_WRITE );
   52156   assert( !pBt->readOnly );
   52157   assert( pCur->wrFlag );
   52158   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
   52159   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
   52160 
   52161   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
   52162    || NEVER(pCur->eState!=CURSOR_VALID)
   52163   ){
   52164     return SQLITE_ERROR;  /* Something has gone awry. */
   52165   }
   52166 
   52167   /* If this is a delete operation to remove a row from a table b-tree,
   52168   ** invalidate any incrblob cursors open on the row being deleted.  */
   52169   if( pCur->pKeyInfo==0 ){
   52170     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
   52171   }
   52172 
   52173   iCellDepth = pCur->iPage;
   52174   iCellIdx = pCur->aiIdx[iCellDepth];
   52175   pPage = pCur->apPage[iCellDepth];
   52176   pCell = findCell(pPage, iCellIdx);
   52177 
   52178   /* If the page containing the entry to delete is not a leaf page, move
   52179   ** the cursor to the largest entry in the tree that is smaller than
   52180   ** the entry being deleted. This cell will replace the cell being deleted
   52181   ** from the internal node. The 'previous' entry is used for this instead
   52182   ** of the 'next' entry, as the previous entry is always a part of the
   52183   ** sub-tree headed by the child page of the cell being deleted. This makes
   52184   ** balancing the tree following the delete operation easier.  */
   52185   if( !pPage->leaf ){
   52186     int notUsed;
   52187     rc = sqlite3BtreePrevious(pCur, &notUsed);
   52188     if( rc ) return rc;
   52189   }
   52190 
   52191   /* Save the positions of any other cursors open on this table before
   52192   ** making any modifications. Make the page containing the entry to be
   52193   ** deleted writable. Then free any overflow pages associated with the
   52194   ** entry and finally remove the cell itself from within the page.
   52195   */
   52196   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
   52197   if( rc ) return rc;
   52198   rc = sqlite3PagerWrite(pPage->pDbPage);
   52199   if( rc ) return rc;
   52200   rc = clearCell(pPage, pCell);
   52201   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
   52202   if( rc ) return rc;
   52203 
   52204   /* If the cell deleted was not located on a leaf page, then the cursor
   52205   ** is currently pointing to the largest entry in the sub-tree headed
   52206   ** by the child-page of the cell that was just deleted from an internal
   52207   ** node. The cell from the leaf node needs to be moved to the internal
   52208   ** node to replace the deleted cell.  */
   52209   if( !pPage->leaf ){
   52210     MemPage *pLeaf = pCur->apPage[pCur->iPage];
   52211     int nCell;
   52212     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
   52213     unsigned char *pTmp;
   52214 
   52215     pCell = findCell(pLeaf, pLeaf->nCell-1);
   52216     nCell = cellSizePtr(pLeaf, pCell);
   52217     assert( MX_CELL_SIZE(pBt)>=nCell );
   52218 
   52219     allocateTempSpace(pBt);
   52220     pTmp = pBt->pTmpSpace;
   52221 
   52222     rc = sqlite3PagerWrite(pLeaf->pDbPage);
   52223     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
   52224     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
   52225     if( rc ) return rc;
   52226   }
   52227 
   52228   /* Balance the tree. If the entry deleted was located on a leaf page,
   52229   ** then the cursor still points to that page. In this case the first
   52230   ** call to balance() repairs the tree, and the if(...) condition is
   52231   ** never true.
   52232   **
   52233   ** Otherwise, if the entry deleted was on an internal node page, then
   52234   ** pCur is pointing to the leaf page from which a cell was removed to
   52235   ** replace the cell deleted from the internal node. This is slightly
   52236   ** tricky as the leaf node may be underfull, and the internal node may
   52237   ** be either under or overfull. In this case run the balancing algorithm
   52238   ** on the leaf node first. If the balance proceeds far enough up the
   52239   ** tree that we can be sure that any problem in the internal node has
   52240   ** been corrected, so be it. Otherwise, after balancing the leaf node,
   52241   ** walk the cursor up the tree to the internal node and balance it as
   52242   ** well.  */
   52243   rc = balance(pCur);
   52244   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
   52245     while( pCur->iPage>iCellDepth ){
   52246       releasePage(pCur->apPage[pCur->iPage--]);
   52247     }
   52248     rc = balance(pCur);
   52249   }
   52250 
   52251   if( rc==SQLITE_OK ){
   52252     moveToRoot(pCur);
   52253   }
   52254   return rc;
   52255 }
   52256 
   52257 /*
   52258 ** Create a new BTree table.  Write into *piTable the page
   52259 ** number for the root page of the new table.
   52260 **
   52261 ** The type of type is determined by the flags parameter.  Only the
   52262 ** following values of flags are currently in use.  Other values for
   52263 ** flags might not work:
   52264 **
   52265 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
   52266 **     BTREE_ZERODATA                  Used for SQL indices
   52267 */
   52268 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   52269   BtShared *pBt = p->pBt;
   52270   MemPage *pRoot;
   52271   Pgno pgnoRoot;
   52272   int rc;
   52273   int ptfFlags;          /* Page-type flage for the root page of new table */
   52274 
   52275   assert( sqlite3BtreeHoldsMutex(p) );
   52276   assert( pBt->inTransaction==TRANS_WRITE );
   52277   assert( !pBt->readOnly );
   52278 
   52279 #ifdef SQLITE_OMIT_AUTOVACUUM
   52280   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   52281   if( rc ){
   52282     return rc;
   52283   }
   52284 #else
   52285   if( pBt->autoVacuum ){
   52286     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
   52287     MemPage *pPageMove; /* The page to move to. */
   52288 
   52289     /* Creating a new table may probably require moving an existing database
   52290     ** to make room for the new tables root page. In case this page turns
   52291     ** out to be an overflow page, delete all overflow page-map caches
   52292     ** held by open cursors.
   52293     */
   52294     invalidateAllOverflowCache(pBt);
   52295 
   52296     /* Read the value of meta[3] from the database to determine where the
   52297     ** root page of the new table should go. meta[3] is the largest root-page
   52298     ** created so far, so the new root-page is (meta[3]+1).
   52299     */
   52300     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
   52301     pgnoRoot++;
   52302 
   52303     /* The new root-page may not be allocated on a pointer-map page, or the
   52304     ** PENDING_BYTE page.
   52305     */
   52306     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
   52307         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
   52308       pgnoRoot++;
   52309     }
   52310     assert( pgnoRoot>=3 );
   52311 
   52312     /* Allocate a page. The page that currently resides at pgnoRoot will
   52313     ** be moved to the allocated page (unless the allocated page happens
   52314     ** to reside at pgnoRoot).
   52315     */
   52316     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
   52317     if( rc!=SQLITE_OK ){
   52318       return rc;
   52319     }
   52320 
   52321     if( pgnoMove!=pgnoRoot ){
   52322       /* pgnoRoot is the page that will be used for the root-page of
   52323       ** the new table (assuming an error did not occur). But we were
   52324       ** allocated pgnoMove. If required (i.e. if it was not allocated
   52325       ** by extending the file), the current page at position pgnoMove
   52326       ** is already journaled.
   52327       */
   52328       u8 eType = 0;
   52329       Pgno iPtrPage = 0;
   52330 
   52331       releasePage(pPageMove);
   52332 
   52333       /* Move the page currently at pgnoRoot to pgnoMove. */
   52334       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   52335       if( rc!=SQLITE_OK ){
   52336         return rc;
   52337       }
   52338       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
   52339       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
   52340         rc = SQLITE_CORRUPT_BKPT;
   52341       }
   52342       if( rc!=SQLITE_OK ){
   52343         releasePage(pRoot);
   52344         return rc;
   52345       }
   52346       assert( eType!=PTRMAP_ROOTPAGE );
   52347       assert( eType!=PTRMAP_FREEPAGE );
   52348       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
   52349       releasePage(pRoot);
   52350 
   52351       /* Obtain the page at pgnoRoot */
   52352       if( rc!=SQLITE_OK ){
   52353         return rc;
   52354       }
   52355       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
   52356       if( rc!=SQLITE_OK ){
   52357         return rc;
   52358       }
   52359       rc = sqlite3PagerWrite(pRoot->pDbPage);
   52360       if( rc!=SQLITE_OK ){
   52361         releasePage(pRoot);
   52362         return rc;
   52363       }
   52364     }else{
   52365       pRoot = pPageMove;
   52366     }
   52367 
   52368     /* Update the pointer-map and meta-data with the new root-page number. */
   52369     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
   52370     if( rc ){
   52371       releasePage(pRoot);
   52372       return rc;
   52373     }
   52374 
   52375     /* When the new root page was allocated, page 1 was made writable in
   52376     ** order either to increase the database filesize, or to decrement the
   52377     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
   52378     */
   52379     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
   52380     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
   52381     if( NEVER(rc) ){
   52382       releasePage(pRoot);
   52383       return rc;
   52384     }
   52385 
   52386   }else{
   52387     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
   52388     if( rc ) return rc;
   52389   }
   52390 #endif
   52391   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
   52392   if( createTabFlags & BTREE_INTKEY ){
   52393     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
   52394   }else{
   52395     ptfFlags = PTF_ZERODATA | PTF_LEAF;
   52396   }
   52397   zeroPage(pRoot, ptfFlags);
   52398   sqlite3PagerUnref(pRoot->pDbPage);
   52399   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
   52400   *piTable = (int)pgnoRoot;
   52401   return SQLITE_OK;
   52402 }
   52403 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
   52404   int rc;
   52405   sqlite3BtreeEnter(p);
   52406   rc = btreeCreateTable(p, piTable, flags);
   52407   sqlite3BtreeLeave(p);
   52408   return rc;
   52409 }
   52410 
   52411 /*
   52412 ** Erase the given database page and all its children.  Return
   52413 ** the page to the freelist.
   52414 */
   52415 static int clearDatabasePage(
   52416   BtShared *pBt,           /* The BTree that contains the table */
   52417   Pgno pgno,               /* Page number to clear */
   52418   int freePageFlag,        /* Deallocate page if true */
   52419   int *pnChange            /* Add number of Cells freed to this counter */
   52420 ){
   52421   MemPage *pPage;
   52422   int rc;
   52423   unsigned char *pCell;
   52424   int i;
   52425 
   52426   assert( sqlite3_mutex_held(pBt->mutex) );
   52427   if( pgno>btreePagecount(pBt) ){
   52428     return SQLITE_CORRUPT_BKPT;
   52429   }
   52430 
   52431   rc = getAndInitPage(pBt, pgno, &pPage);
   52432   if( rc ) return rc;
   52433   for(i=0; i<pPage->nCell; i++){
   52434     pCell = findCell(pPage, i);
   52435     if( !pPage->leaf ){
   52436       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
   52437       if( rc ) goto cleardatabasepage_out;
   52438     }
   52439     rc = clearCell(pPage, pCell);
   52440     if( rc ) goto cleardatabasepage_out;
   52441   }
   52442   if( !pPage->leaf ){
   52443     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
   52444     if( rc ) goto cleardatabasepage_out;
   52445   }else if( pnChange ){
   52446     assert( pPage->intKey );
   52447     *pnChange += pPage->nCell;
   52448   }
   52449   if( freePageFlag ){
   52450     freePage(pPage, &rc);
   52451   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
   52452     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
   52453   }
   52454 
   52455 cleardatabasepage_out:
   52456   releasePage(pPage);
   52457   return rc;
   52458 }
   52459 
   52460 /*
   52461 ** Delete all information from a single table in the database.  iTable is
   52462 ** the page number of the root of the table.  After this routine returns,
   52463 ** the root page is empty, but still exists.
   52464 **
   52465 ** This routine will fail with SQLITE_LOCKED if there are any open
   52466 ** read cursors on the table.  Open write cursors are moved to the
   52467 ** root of the table.
   52468 **
   52469 ** If pnChange is not NULL, then table iTable must be an intkey table. The
   52470 ** integer value pointed to by pnChange is incremented by the number of
   52471 ** entries in the table.
   52472 */
   52473 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
   52474   int rc;
   52475   BtShared *pBt = p->pBt;
   52476   sqlite3BtreeEnter(p);
   52477   assert( p->inTrans==TRANS_WRITE );
   52478 
   52479   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
   52480   ** is the root of a table b-tree - if it is not, the following call is
   52481   ** a no-op).  */
   52482   invalidateIncrblobCursors(p, 0, 1);
   52483 
   52484   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
   52485   if( SQLITE_OK==rc ){
   52486     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
   52487   }
   52488   sqlite3BtreeLeave(p);
   52489   return rc;
   52490 }
   52491 
   52492 /*
   52493 ** Erase all information in a table and add the root of the table to
   52494 ** the freelist.  Except, the root of the principle table (the one on
   52495 ** page 1) is never added to the freelist.
   52496 **
   52497 ** This routine will fail with SQLITE_LOCKED if there are any open
   52498 ** cursors on the table.
   52499 **
   52500 ** If AUTOVACUUM is enabled and the page at iTable is not the last
   52501 ** root page in the database file, then the last root page
   52502 ** in the database file is moved into the slot formerly occupied by
   52503 ** iTable and that last slot formerly occupied by the last root page
   52504 ** is added to the freelist instead of iTable.  In this say, all
   52505 ** root pages are kept at the beginning of the database file, which
   52506 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
   52507 ** page number that used to be the last root page in the file before
   52508 ** the move.  If no page gets moved, *piMoved is set to 0.
   52509 ** The last root page is recorded in meta[3] and the value of
   52510 ** meta[3] is updated by this procedure.
   52511 */
   52512 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
   52513   int rc;
   52514   MemPage *pPage = 0;
   52515   BtShared *pBt = p->pBt;
   52516 
   52517   assert( sqlite3BtreeHoldsMutex(p) );
   52518   assert( p->inTrans==TRANS_WRITE );
   52519 
   52520   /* It is illegal to drop a table if any cursors are open on the
   52521   ** database. This is because in auto-vacuum mode the backend may
   52522   ** need to move another root-page to fill a gap left by the deleted
   52523   ** root page. If an open cursor was using this page a problem would
   52524   ** occur.
   52525   **
   52526   ** This error is caught long before control reaches this point.
   52527   */
   52528   if( NEVER(pBt->pCursor) ){
   52529     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
   52530     return SQLITE_LOCKED_SHAREDCACHE;
   52531   }
   52532 
   52533   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
   52534   if( rc ) return rc;
   52535   rc = sqlite3BtreeClearTable(p, iTable, 0);
   52536   if( rc ){
   52537     releasePage(pPage);
   52538     return rc;
   52539   }
   52540 
   52541   *piMoved = 0;
   52542 
   52543   if( iTable>1 ){
   52544 #ifdef SQLITE_OMIT_AUTOVACUUM
   52545     freePage(pPage, &rc);
   52546     releasePage(pPage);
   52547 #else
   52548     if( pBt->autoVacuum ){
   52549       Pgno maxRootPgno;
   52550       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
   52551 
   52552       if( iTable==maxRootPgno ){
   52553         /* If the table being dropped is the table with the largest root-page
   52554         ** number in the database, put the root page on the free list.
   52555         */
   52556         freePage(pPage, &rc);
   52557         releasePage(pPage);
   52558         if( rc!=SQLITE_OK ){
   52559           return rc;
   52560         }
   52561       }else{
   52562         /* The table being dropped does not have the largest root-page
   52563         ** number in the database. So move the page that does into the
   52564         ** gap left by the deleted root-page.
   52565         */
   52566         MemPage *pMove;
   52567         releasePage(pPage);
   52568         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   52569         if( rc!=SQLITE_OK ){
   52570           return rc;
   52571         }
   52572         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
   52573         releasePage(pMove);
   52574         if( rc!=SQLITE_OK ){
   52575           return rc;
   52576         }
   52577         pMove = 0;
   52578         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
   52579         freePage(pMove, &rc);
   52580         releasePage(pMove);
   52581         if( rc!=SQLITE_OK ){
   52582           return rc;
   52583         }
   52584         *piMoved = maxRootPgno;
   52585       }
   52586 
   52587       /* Set the new 'max-root-page' value in the database header. This
   52588       ** is the old value less one, less one more if that happens to
   52589       ** be a root-page number, less one again if that is the
   52590       ** PENDING_BYTE_PAGE.
   52591       */
   52592       maxRootPgno--;
   52593       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
   52594              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
   52595         maxRootPgno--;
   52596       }
   52597       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
   52598 
   52599       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
   52600     }else{
   52601       freePage(pPage, &rc);
   52602       releasePage(pPage);
   52603     }
   52604 #endif
   52605   }else{
   52606     /* If sqlite3BtreeDropTable was called on page 1.
   52607     ** This really never should happen except in a corrupt
   52608     ** database.
   52609     */
   52610     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
   52611     releasePage(pPage);
   52612   }
   52613   return rc;
   52614 }
   52615 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   52616   int rc;
   52617   sqlite3BtreeEnter(p);
   52618   rc = btreeDropTable(p, iTable, piMoved);
   52619   sqlite3BtreeLeave(p);
   52620   return rc;
   52621 }
   52622 
   52623 
   52624 /*
   52625 ** This function may only be called if the b-tree connection already
   52626 ** has a read or write transaction open on the database.
   52627 **
   52628 ** Read the meta-information out of a database file.  Meta[0]
   52629 ** is the number of free pages currently in the database.  Meta[1]
   52630 ** through meta[15] are available for use by higher layers.  Meta[0]
   52631 ** is read-only, the others are read/write.
   52632 **
   52633 ** The schema layer numbers meta values differently.  At the schema
   52634 ** layer (and the SetCookie and ReadCookie opcodes) the number of
   52635 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
   52636 */
   52637 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
   52638   BtShared *pBt = p->pBt;
   52639 
   52640   sqlite3BtreeEnter(p);
   52641   assert( p->inTrans>TRANS_NONE );
   52642   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
   52643   assert( pBt->pPage1 );
   52644   assert( idx>=0 && idx<=15 );
   52645 
   52646   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
   52647 
   52648   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
   52649   ** database, mark the database as read-only.  */
   52650 #ifdef SQLITE_OMIT_AUTOVACUUM
   52651   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
   52652 #endif
   52653 
   52654   sqlite3BtreeLeave(p);
   52655 }
   52656 
   52657 /*
   52658 ** Write meta-information back into the database.  Meta[0] is
   52659 ** read-only and may not be written.
   52660 */
   52661 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   52662   BtShared *pBt = p->pBt;
   52663   unsigned char *pP1;
   52664   int rc;
   52665   assert( idx>=1 && idx<=15 );
   52666   sqlite3BtreeEnter(p);
   52667   assert( p->inTrans==TRANS_WRITE );
   52668   assert( pBt->pPage1!=0 );
   52669   pP1 = pBt->pPage1->aData;
   52670   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   52671   if( rc==SQLITE_OK ){
   52672     put4byte(&pP1[36 + idx*4], iMeta);
   52673 #ifndef SQLITE_OMIT_AUTOVACUUM
   52674     if( idx==BTREE_INCR_VACUUM ){
   52675       assert( pBt->autoVacuum || iMeta==0 );
   52676       assert( iMeta==0 || iMeta==1 );
   52677       pBt->incrVacuum = (u8)iMeta;
   52678     }
   52679 #endif
   52680   }
   52681   sqlite3BtreeLeave(p);
   52682   return rc;
   52683 }
   52684 
   52685 #ifndef SQLITE_OMIT_BTREECOUNT
   52686 /*
   52687 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
   52688 ** number of entries in the b-tree and write the result to *pnEntry.
   52689 **
   52690 ** SQLITE_OK is returned if the operation is successfully executed.
   52691 ** Otherwise, if an error is encountered (i.e. an IO error or database
   52692 ** corruption) an SQLite error code is returned.
   52693 */
   52694 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   52695   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   52696   int rc;                              /* Return code */
   52697   rc = moveToRoot(pCur);
   52698 
   52699   /* Unless an error occurs, the following loop runs one iteration for each
   52700   ** page in the B-Tree structure (not including overflow pages).
   52701   */
   52702   while( rc==SQLITE_OK ){
   52703     int iIdx;                          /* Index of child node in parent */
   52704     MemPage *pPage;                    /* Current page of the b-tree */
   52705 
   52706     /* If this is a leaf page or the tree is not an int-key tree, then
   52707     ** this page contains countable entries. Increment the entry counter
   52708     ** accordingly.
   52709     */
   52710     pPage = pCur->apPage[pCur->iPage];
   52711     if( pPage->leaf || !pPage->intKey ){
   52712       nEntry += pPage->nCell;
   52713     }
   52714 
   52715     /* pPage is a leaf node. This loop navigates the cursor so that it
   52716     ** points to the first interior cell that it points to the parent of
   52717     ** the next page in the tree that has not yet been visited. The
   52718     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
   52719     ** of the page, or to the number of cells in the page if the next page
   52720     ** to visit is the right-child of its parent.
   52721     **
   52722     ** If all pages in the tree have been visited, return SQLITE_OK to the
   52723     ** caller.
   52724     */
   52725     if( pPage->leaf ){
   52726       do {
   52727         if( pCur->iPage==0 ){
   52728           /* All pages of the b-tree have been visited. Return successfully. */
   52729           *pnEntry = nEntry;
   52730           return SQLITE_OK;
   52731         }
   52732         moveToParent(pCur);
   52733       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
   52734 
   52735       pCur->aiIdx[pCur->iPage]++;
   52736       pPage = pCur->apPage[pCur->iPage];
   52737     }
   52738 
   52739     /* Descend to the child node of the cell that the cursor currently
   52740     ** points at. This is the right-child if (iIdx==pPage->nCell).
   52741     */
   52742     iIdx = pCur->aiIdx[pCur->iPage];
   52743     if( iIdx==pPage->nCell ){
   52744       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
   52745     }else{
   52746       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
   52747     }
   52748   }
   52749 
   52750   /* An error has occurred. Return an error code. */
   52751   return rc;
   52752 }
   52753 #endif
   52754 
   52755 /*
   52756 ** Return the pager associated with a BTree.  This routine is used for
   52757 ** testing and debugging only.
   52758 */
   52759 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
   52760   return p->pBt->pPager;
   52761 }
   52762 
   52763 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   52764 /*
   52765 ** Append a message to the error message string.
   52766 */
   52767 static void checkAppendMsg(
   52768   IntegrityCk *pCheck,
   52769   char *zMsg1,
   52770   const char *zFormat,
   52771   ...
   52772 ){
   52773   va_list ap;
   52774   if( !pCheck->mxErr ) return;
   52775   pCheck->mxErr--;
   52776   pCheck->nErr++;
   52777   va_start(ap, zFormat);
   52778   if( pCheck->errMsg.nChar ){
   52779     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
   52780   }
   52781   if( zMsg1 ){
   52782     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
   52783   }
   52784   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
   52785   va_end(ap);
   52786   if( pCheck->errMsg.mallocFailed ){
   52787     pCheck->mallocFailed = 1;
   52788   }
   52789 }
   52790 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   52791 
   52792 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   52793 /*
   52794 ** Add 1 to the reference count for page iPage.  If this is the second
   52795 ** reference to the page, add an error message to pCheck->zErrMsg.
   52796 ** Return 1 if there are 2 ore more references to the page and 0 if
   52797 ** if this is the first reference to the page.
   52798 **
   52799 ** Also check that the page number is in bounds.
   52800 */
   52801 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
   52802   if( iPage==0 ) return 1;
   52803   if( iPage>pCheck->nPage ){
   52804     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
   52805     return 1;
   52806   }
   52807   if( pCheck->anRef[iPage]==1 ){
   52808     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
   52809     return 1;
   52810   }
   52811   return  (pCheck->anRef[iPage]++)>1;
   52812 }
   52813 
   52814 #ifndef SQLITE_OMIT_AUTOVACUUM
   52815 /*
   52816 ** Check that the entry in the pointer-map for page iChild maps to
   52817 ** page iParent, pointer type ptrType. If not, append an error message
   52818 ** to pCheck.
   52819 */
   52820 static void checkPtrmap(
   52821   IntegrityCk *pCheck,   /* Integrity check context */
   52822   Pgno iChild,           /* Child page number */
   52823   u8 eType,              /* Expected pointer map type */
   52824   Pgno iParent,          /* Expected pointer map parent page number */
   52825   char *zContext         /* Context description (used for error msg) */
   52826 ){
   52827   int rc;
   52828   u8 ePtrmapType;
   52829   Pgno iPtrmapParent;
   52830 
   52831   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   52832   if( rc!=SQLITE_OK ){
   52833     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
   52834     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
   52835     return;
   52836   }
   52837 
   52838   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
   52839     checkAppendMsg(pCheck, zContext,
   52840       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
   52841       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   52842   }
   52843 }
   52844 #endif
   52845 
   52846 /*
   52847 ** Check the integrity of the freelist or of an overflow page list.
   52848 ** Verify that the number of pages on the list is N.
   52849 */
   52850 static void checkList(
   52851   IntegrityCk *pCheck,  /* Integrity checking context */
   52852   int isFreeList,       /* True for a freelist.  False for overflow page list */
   52853   int iPage,            /* Page number for first page in the list */
   52854   int N,                /* Expected number of pages in the list */
   52855   char *zContext        /* Context for error messages */
   52856 ){
   52857   int i;
   52858   int expected = N;
   52859   int iFirst = iPage;
   52860   while( N-- > 0 && pCheck->mxErr ){
   52861     DbPage *pOvflPage;
   52862     unsigned char *pOvflData;
   52863     if( iPage<1 ){
   52864       checkAppendMsg(pCheck, zContext,
   52865          "%d of %d pages missing from overflow list starting at %d",
   52866           N+1, expected, iFirst);
   52867       break;
   52868     }
   52869     if( checkRef(pCheck, iPage, zContext) ) break;
   52870     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
   52871       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
   52872       break;
   52873     }
   52874     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
   52875     if( isFreeList ){
   52876       int n = get4byte(&pOvflData[4]);
   52877 #ifndef SQLITE_OMIT_AUTOVACUUM
   52878       if( pCheck->pBt->autoVacuum ){
   52879         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
   52880       }
   52881 #endif
   52882       if( n>(int)pCheck->pBt->usableSize/4-2 ){
   52883         checkAppendMsg(pCheck, zContext,
   52884            "freelist leaf count too big on page %d", iPage);
   52885         N--;
   52886       }else{
   52887         for(i=0; i<n; i++){
   52888           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
   52889 #ifndef SQLITE_OMIT_AUTOVACUUM
   52890           if( pCheck->pBt->autoVacuum ){
   52891             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
   52892           }
   52893 #endif
   52894           checkRef(pCheck, iFreePage, zContext);
   52895         }
   52896         N -= n;
   52897       }
   52898     }
   52899 #ifndef SQLITE_OMIT_AUTOVACUUM
   52900     else{
   52901       /* If this database supports auto-vacuum and iPage is not the last
   52902       ** page in this overflow list, check that the pointer-map entry for
   52903       ** the following page matches iPage.
   52904       */
   52905       if( pCheck->pBt->autoVacuum && N>0 ){
   52906         i = get4byte(pOvflData);
   52907         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
   52908       }
   52909     }
   52910 #endif
   52911     iPage = get4byte(pOvflData);
   52912     sqlite3PagerUnref(pOvflPage);
   52913   }
   52914 }
   52915 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   52916 
   52917 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   52918 /*
   52919 ** Do various sanity checks on a single page of a tree.  Return
   52920 ** the tree depth.  Root pages return 0.  Parents of root pages
   52921 ** return 1, and so forth.
   52922 **
   52923 ** These checks are done:
   52924 **
   52925 **      1.  Make sure that cells and freeblocks do not overlap
   52926 **          but combine to completely cover the page.
   52927 **  NO  2.  Make sure cell keys are in order.
   52928 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
   52929 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
   52930 **      5.  Check the integrity of overflow pages.
   52931 **      6.  Recursively call checkTreePage on all children.
   52932 **      7.  Verify that the depth of all children is the same.
   52933 **      8.  Make sure this page is at least 33% full or else it is
   52934 **          the root of the tree.
   52935 */
   52936 static int checkTreePage(
   52937   IntegrityCk *pCheck,  /* Context for the sanity check */
   52938   int iPage,            /* Page number of the page to check */
   52939   char *zParentContext, /* Parent context */
   52940   i64 *pnParentMinKey,
   52941   i64 *pnParentMaxKey
   52942 ){
   52943   MemPage *pPage;
   52944   int i, rc, depth, d2, pgno, cnt;
   52945   int hdr, cellStart;
   52946   int nCell;
   52947   u8 *data;
   52948   BtShared *pBt;
   52949   int usableSize;
   52950   char zContext[100];
   52951   char *hit = 0;
   52952   i64 nMinKey = 0;
   52953   i64 nMaxKey = 0;
   52954 
   52955   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
   52956 
   52957   /* Check that the page exists
   52958   */
   52959   pBt = pCheck->pBt;
   52960   usableSize = pBt->usableSize;
   52961   if( iPage==0 ) return 0;
   52962   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
   52963   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
   52964     checkAppendMsg(pCheck, zContext,
   52965        "unable to get the page. error code=%d", rc);
   52966     return 0;
   52967   }
   52968 
   52969   /* Clear MemPage.isInit to make sure the corruption detection code in
   52970   ** btreeInitPage() is executed.  */
   52971   pPage->isInit = 0;
   52972   if( (rc = btreeInitPage(pPage))!=0 ){
   52973     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
   52974     checkAppendMsg(pCheck, zContext,
   52975                    "btreeInitPage() returns error code %d", rc);
   52976     releasePage(pPage);
   52977     return 0;
   52978   }
   52979 
   52980   /* Check out all the cells.
   52981   */
   52982   depth = 0;
   52983   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
   52984     u8 *pCell;
   52985     u32 sz;
   52986     CellInfo info;
   52987 
   52988     /* Check payload overflow pages
   52989     */
   52990     sqlite3_snprintf(sizeof(zContext), zContext,
   52991              "On tree page %d cell %d: ", iPage, i);
   52992     pCell = findCell(pPage,i);
   52993     btreeParseCellPtr(pPage, pCell, &info);
   52994     sz = info.nData;
   52995     if( !pPage->intKey ) sz += (int)info.nKey;
   52996     /* For intKey pages, check that the keys are in order.
   52997     */
   52998     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
   52999     else{
   53000       if( info.nKey <= nMaxKey ){
   53001         checkAppendMsg(pCheck, zContext,
   53002             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
   53003       }
   53004       nMaxKey = info.nKey;
   53005     }
   53006     assert( sz==info.nPayload );
   53007     if( (sz>info.nLocal)
   53008      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
   53009     ){
   53010       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
   53011       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
   53012 #ifndef SQLITE_OMIT_AUTOVACUUM
   53013       if( pBt->autoVacuum ){
   53014         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
   53015       }
   53016 #endif
   53017       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
   53018     }
   53019 
   53020     /* Check sanity of left child page.
   53021     */
   53022     if( !pPage->leaf ){
   53023       pgno = get4byte(pCell);
   53024 #ifndef SQLITE_OMIT_AUTOVACUUM
   53025       if( pBt->autoVacuum ){
   53026         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   53027       }
   53028 #endif
   53029       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
   53030       if( i>0 && d2!=depth ){
   53031         checkAppendMsg(pCheck, zContext, "Child page depth differs");
   53032       }
   53033       depth = d2;
   53034     }
   53035   }
   53036 
   53037   if( !pPage->leaf ){
   53038     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
   53039     sqlite3_snprintf(sizeof(zContext), zContext,
   53040                      "On page %d at right child: ", iPage);
   53041 #ifndef SQLITE_OMIT_AUTOVACUUM
   53042     if( pBt->autoVacuum ){
   53043       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
   53044     }
   53045 #endif
   53046     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
   53047   }
   53048 
   53049   /* For intKey leaf pages, check that the min/max keys are in order
   53050   ** with any left/parent/right pages.
   53051   */
   53052   if( pPage->leaf && pPage->intKey ){
   53053     /* if we are a left child page */
   53054     if( pnParentMinKey ){
   53055       /* if we are the left most child page */
   53056       if( !pnParentMaxKey ){
   53057         if( nMaxKey > *pnParentMinKey ){
   53058           checkAppendMsg(pCheck, zContext,
   53059               "Rowid %lld out of order (max larger than parent min of %lld)",
   53060               nMaxKey, *pnParentMinKey);
   53061         }
   53062       }else{
   53063         if( nMinKey <= *pnParentMinKey ){
   53064           checkAppendMsg(pCheck, zContext,
   53065               "Rowid %lld out of order (min less than parent min of %lld)",
   53066               nMinKey, *pnParentMinKey);
   53067         }
   53068         if( nMaxKey > *pnParentMaxKey ){
   53069           checkAppendMsg(pCheck, zContext,
   53070               "Rowid %lld out of order (max larger than parent max of %lld)",
   53071               nMaxKey, *pnParentMaxKey);
   53072         }
   53073         *pnParentMinKey = nMaxKey;
   53074       }
   53075     /* else if we're a right child page */
   53076     } else if( pnParentMaxKey ){
   53077       if( nMinKey <= *pnParentMaxKey ){
   53078         checkAppendMsg(pCheck, zContext,
   53079             "Rowid %lld out of order (min less than parent max of %lld)",
   53080             nMinKey, *pnParentMaxKey);
   53081       }
   53082     }
   53083   }
   53084 
   53085   /* Check for complete coverage of the page
   53086   */
   53087   data = pPage->aData;
   53088   hdr = pPage->hdrOffset;
   53089   hit = sqlite3PageMalloc( pBt->pageSize );
   53090   if( hit==0 ){
   53091     pCheck->mallocFailed = 1;
   53092   }else{
   53093     int contentOffset = get2byteNotZero(&data[hdr+5]);
   53094     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
   53095     memset(hit+contentOffset, 0, usableSize-contentOffset);
   53096     memset(hit, 1, contentOffset);
   53097     nCell = get2byte(&data[hdr+3]);
   53098     cellStart = hdr + 12 - 4*pPage->leaf;
   53099     for(i=0; i<nCell; i++){
   53100       int pc = get2byte(&data[cellStart+i*2]);
   53101       u32 size = 65536;
   53102       int j;
   53103       if( pc<=usableSize-4 ){
   53104         size = cellSizePtr(pPage, &data[pc]);
   53105       }
   53106       if( (int)(pc+size-1)>=usableSize ){
   53107         checkAppendMsg(pCheck, 0,
   53108             "Corruption detected in cell %d on page %d",i,iPage);
   53109       }else{
   53110         for(j=pc+size-1; j>=pc; j--) hit[j]++;
   53111       }
   53112     }
   53113     i = get2byte(&data[hdr+1]);
   53114     while( i>0 ){
   53115       int size, j;
   53116       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
   53117       size = get2byte(&data[i+2]);
   53118       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
   53119       for(j=i+size-1; j>=i; j--) hit[j]++;
   53120       j = get2byte(&data[i]);
   53121       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
   53122       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
   53123       i = j;
   53124     }
   53125     for(i=cnt=0; i<usableSize; i++){
   53126       if( hit[i]==0 ){
   53127         cnt++;
   53128       }else if( hit[i]>1 ){
   53129         checkAppendMsg(pCheck, 0,
   53130           "Multiple uses for byte %d of page %d", i, iPage);
   53131         break;
   53132       }
   53133     }
   53134     if( cnt!=data[hdr+7] ){
   53135       checkAppendMsg(pCheck, 0,
   53136           "Fragmentation of %d bytes reported as %d on page %d",
   53137           cnt, data[hdr+7], iPage);
   53138     }
   53139   }
   53140   sqlite3PageFree(hit);
   53141   releasePage(pPage);
   53142   return depth+1;
   53143 }
   53144 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   53145 
   53146 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   53147 /*
   53148 ** This routine does a complete check of the given BTree file.  aRoot[] is
   53149 ** an array of pages numbers were each page number is the root page of
   53150 ** a table.  nRoot is the number of entries in aRoot.
   53151 **
   53152 ** A read-only or read-write transaction must be opened before calling
   53153 ** this function.
   53154 **
   53155 ** Write the number of error seen in *pnErr.  Except for some memory
   53156 ** allocation errors,  an error message held in memory obtained from
   53157 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
   53158 ** returned.  If a memory allocation error occurs, NULL is returned.
   53159 */
   53160 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   53161   Btree *p,     /* The btree to be checked */
   53162   int *aRoot,   /* An array of root pages numbers for individual trees */
   53163   int nRoot,    /* Number of entries in aRoot[] */
   53164   int mxErr,    /* Stop reporting errors after this many */
   53165   int *pnErr    /* Write number of errors seen to this variable */
   53166 ){
   53167   Pgno i;
   53168   int nRef;
   53169   IntegrityCk sCheck;
   53170   BtShared *pBt = p->pBt;
   53171   char zErr[100];
   53172 
   53173   sqlite3BtreeEnter(p);
   53174   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   53175   nRef = sqlite3PagerRefcount(pBt->pPager);
   53176   sCheck.pBt = pBt;
   53177   sCheck.pPager = pBt->pPager;
   53178   sCheck.nPage = btreePagecount(sCheck.pBt);
   53179   sCheck.mxErr = mxErr;
   53180   sCheck.nErr = 0;
   53181   sCheck.mallocFailed = 0;
   53182   *pnErr = 0;
   53183   if( sCheck.nPage==0 ){
   53184     sqlite3BtreeLeave(p);
   53185     return 0;
   53186   }
   53187   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
   53188   if( !sCheck.anRef ){
   53189     *pnErr = 1;
   53190     sqlite3BtreeLeave(p);
   53191     return 0;
   53192   }
   53193   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
   53194   i = PENDING_BYTE_PAGE(pBt);
   53195   if( i<=sCheck.nPage ){
   53196     sCheck.anRef[i] = 1;
   53197   }
   53198   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
   53199   sCheck.errMsg.useMalloc = 2;
   53200 
   53201   /* Check the integrity of the freelist
   53202   */
   53203   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
   53204             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
   53205 
   53206   /* Check all the tables.
   53207   */
   53208   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
   53209     if( aRoot[i]==0 ) continue;
   53210 #ifndef SQLITE_OMIT_AUTOVACUUM
   53211     if( pBt->autoVacuum && aRoot[i]>1 ){
   53212       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
   53213     }
   53214 #endif
   53215     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
   53216   }
   53217 
   53218   /* Make sure every page in the file is referenced
   53219   */
   53220   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
   53221 #ifdef SQLITE_OMIT_AUTOVACUUM
   53222     if( sCheck.anRef[i]==0 ){
   53223       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   53224     }
   53225 #else
   53226     /* If the database supports auto-vacuum, make sure no tables contain
   53227     ** references to pointer-map pages.
   53228     */
   53229     if( sCheck.anRef[i]==0 &&
   53230        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
   53231       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
   53232     }
   53233     if( sCheck.anRef[i]!=0 &&
   53234        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
   53235       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
   53236     }
   53237 #endif
   53238   }
   53239 
   53240   /* Make sure this analysis did not leave any unref() pages.
   53241   ** This is an internal consistency check; an integrity check
   53242   ** of the integrity check.
   53243   */
   53244   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
   53245     checkAppendMsg(&sCheck, 0,
   53246       "Outstanding page count goes from %d to %d during this analysis",
   53247       nRef, sqlite3PagerRefcount(pBt->pPager)
   53248     );
   53249   }
   53250 
   53251   /* Clean  up and report errors.
   53252   */
   53253   sqlite3BtreeLeave(p);
   53254   sqlite3_free(sCheck.anRef);
   53255   if( sCheck.mallocFailed ){
   53256     sqlite3StrAccumReset(&sCheck.errMsg);
   53257     *pnErr = sCheck.nErr+1;
   53258     return 0;
   53259   }
   53260   *pnErr = sCheck.nErr;
   53261   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
   53262   return sqlite3StrAccumFinish(&sCheck.errMsg);
   53263 }
   53264 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   53265 
   53266 /*
   53267 ** Return the full pathname of the underlying database file.
   53268 **
   53269 ** The pager filename is invariant as long as the pager is
   53270 ** open so it is safe to access without the BtShared mutex.
   53271 */
   53272 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
   53273   assert( p->pBt->pPager!=0 );
   53274   return sqlite3PagerFilename(p->pBt->pPager);
   53275 }
   53276 
   53277 /*
   53278 ** Return the pathname of the journal file for this database. The return
   53279 ** value of this routine is the same regardless of whether the journal file
   53280 ** has been created or not.
   53281 **
   53282 ** The pager journal filename is invariant as long as the pager is
   53283 ** open so it is safe to access without the BtShared mutex.
   53284 */
   53285 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
   53286   assert( p->pBt->pPager!=0 );
   53287   return sqlite3PagerJournalname(p->pBt->pPager);
   53288 }
   53289 
   53290 /*
   53291 ** Return non-zero if a transaction is active.
   53292 */
   53293 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
   53294   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
   53295   return (p && (p->inTrans==TRANS_WRITE));
   53296 }
   53297 
   53298 #ifndef SQLITE_OMIT_WAL
   53299 /*
   53300 ** Run a checkpoint on the Btree passed as the first argument.
   53301 **
   53302 ** Return SQLITE_LOCKED if this or any other connection has an open
   53303 ** transaction on the shared-cache the argument Btree is connected to.
   53304 */
   53305 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
   53306   int rc = SQLITE_OK;
   53307   if( p ){
   53308     BtShared *pBt = p->pBt;
   53309     sqlite3BtreeEnter(p);
   53310     if( pBt->inTransaction!=TRANS_NONE ){
   53311       rc = SQLITE_LOCKED;
   53312     }else{
   53313       rc = sqlite3PagerCheckpoint(pBt->pPager);
   53314     }
   53315     sqlite3BtreeLeave(p);
   53316   }
   53317   return rc;
   53318 }
   53319 #endif
   53320 
   53321 /*
   53322 ** Return non-zero if a read (or write) transaction is active.
   53323 */
   53324 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
   53325   assert( p );
   53326   assert( sqlite3_mutex_held(p->db->mutex) );
   53327   return p->inTrans!=TRANS_NONE;
   53328 }
   53329 
   53330 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   53331   assert( p );
   53332   assert( sqlite3_mutex_held(p->db->mutex) );
   53333   return p->nBackup!=0;
   53334 }
   53335 
   53336 /*
   53337 ** This function returns a pointer to a blob of memory associated with
   53338 ** a single shared-btree. The memory is used by client code for its own
   53339 ** purposes (for example, to store a high-level schema associated with
   53340 ** the shared-btree). The btree layer manages reference counting issues.
   53341 **
   53342 ** The first time this is called on a shared-btree, nBytes bytes of memory
   53343 ** are allocated, zeroed, and returned to the caller. For each subsequent
   53344 ** call the nBytes parameter is ignored and a pointer to the same blob
   53345 ** of memory returned.
   53346 **
   53347 ** If the nBytes parameter is 0 and the blob of memory has not yet been
   53348 ** allocated, a null pointer is returned. If the blob has already been
   53349 ** allocated, it is returned as normal.
   53350 **
   53351 ** Just before the shared-btree is closed, the function passed as the
   53352 ** xFree argument when the memory allocation was made is invoked on the
   53353 ** blob of allocated memory. This function should not call sqlite3_free()
   53354 ** on the memory, the btree layer does that.
   53355 */
   53356 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
   53357   BtShared *pBt = p->pBt;
   53358   sqlite3BtreeEnter(p);
   53359   if( !pBt->pSchema && nBytes ){
   53360     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
   53361     pBt->xFreeSchema = xFree;
   53362   }
   53363   sqlite3BtreeLeave(p);
   53364   return pBt->pSchema;
   53365 }
   53366 
   53367 /*
   53368 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
   53369 ** btree as the argument handle holds an exclusive lock on the
   53370 ** sqlite_master table. Otherwise SQLITE_OK.
   53371 */
   53372 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   53373   int rc;
   53374   assert( sqlite3_mutex_held(p->db->mutex) );
   53375   sqlite3BtreeEnter(p);
   53376   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
   53377   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   53378   sqlite3BtreeLeave(p);
   53379   return rc;
   53380 }
   53381 
   53382 
   53383 #ifndef SQLITE_OMIT_SHARED_CACHE
   53384 /*
   53385 ** Obtain a lock on the table whose root page is iTab.  The
   53386 ** lock is a write lock if isWritelock is true or a read lock
   53387 ** if it is false.
   53388 */
   53389 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
   53390   int rc = SQLITE_OK;
   53391   assert( p->inTrans!=TRANS_NONE );
   53392   if( p->sharable ){
   53393     u8 lockType = READ_LOCK + isWriteLock;
   53394     assert( READ_LOCK+1==WRITE_LOCK );
   53395     assert( isWriteLock==0 || isWriteLock==1 );
   53396 
   53397     sqlite3BtreeEnter(p);
   53398     rc = querySharedCacheTableLock(p, iTab, lockType);
   53399     if( rc==SQLITE_OK ){
   53400       rc = setSharedCacheTableLock(p, iTab, lockType);
   53401     }
   53402     sqlite3BtreeLeave(p);
   53403   }
   53404   return rc;
   53405 }
   53406 #endif
   53407 
   53408 #ifndef SQLITE_OMIT_INCRBLOB
   53409 /*
   53410 ** Argument pCsr must be a cursor opened for writing on an
   53411 ** INTKEY table currently pointing at a valid table entry.
   53412 ** This function modifies the data stored as part of that entry.
   53413 **
   53414 ** Only the data content may only be modified, it is not possible to
   53415 ** change the length of the data stored. If this function is called with
   53416 ** parameters that attempt to write past the end of the existing data,
   53417 ** no modifications are made and SQLITE_CORRUPT is returned.
   53418 */
   53419 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
   53420   int rc;
   53421   assert( cursorHoldsMutex(pCsr) );
   53422   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
   53423   assert( pCsr->isIncrblobHandle );
   53424 
   53425   rc = restoreCursorPosition(pCsr);
   53426   if( rc!=SQLITE_OK ){
   53427     return rc;
   53428   }
   53429   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
   53430   if( pCsr->eState!=CURSOR_VALID ){
   53431     return SQLITE_ABORT;
   53432   }
   53433 
   53434   /* Check some assumptions:
   53435   **   (a) the cursor is open for writing,
   53436   **   (b) there is a read/write transaction open,
   53437   **   (c) the connection holds a write-lock on the table (if required),
   53438   **   (d) there are no conflicting read-locks, and
   53439   **   (e) the cursor points at a valid row of an intKey table.
   53440   */
   53441   if( !pCsr->wrFlag ){
   53442     return SQLITE_READONLY;
   53443   }
   53444   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
   53445   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
   53446   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
   53447   assert( pCsr->apPage[pCsr->iPage]->intKey );
   53448 
   53449   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
   53450 }
   53451 
   53452 /*
   53453 ** Set a flag on this cursor to cache the locations of pages from the
   53454 ** overflow list for the current row. This is used by cursors opened
   53455 ** for incremental blob IO only.
   53456 **
   53457 ** This function sets a flag only. The actual page location cache
   53458 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
   53459 ** accessPayload() (the worker function for sqlite3BtreeData() and
   53460 ** sqlite3BtreePutData()).
   53461 */
   53462 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
   53463   assert( cursorHoldsMutex(pCur) );
   53464   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
   53465   invalidateOverflowCache(pCur);
   53466   pCur->isIncrblobHandle = 1;
   53467 }
   53468 #endif
   53469 
   53470 /*
   53471 ** Set both the "read version" (single byte at byte offset 18) and
   53472 ** "write version" (single byte at byte offset 19) fields in the database
   53473 ** header to iVersion.
   53474 */
   53475 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   53476   BtShared *pBt = pBtree->pBt;
   53477   int rc;                         /* Return code */
   53478 
   53479   assert( pBtree->inTrans==TRANS_NONE );
   53480   assert( iVersion==1 || iVersion==2 );
   53481 
   53482   /* If setting the version fields to 1, do not automatically open the
   53483   ** WAL connection, even if the version fields are currently set to 2.
   53484   */
   53485   pBt->doNotUseWAL = (u8)(iVersion==1);
   53486 
   53487   rc = sqlite3BtreeBeginTrans(pBtree, 0);
   53488   if( rc==SQLITE_OK ){
   53489     u8 *aData = pBt->pPage1->aData;
   53490     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
   53491       rc = sqlite3BtreeBeginTrans(pBtree, 2);
   53492       if( rc==SQLITE_OK ){
   53493         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
   53494         if( rc==SQLITE_OK ){
   53495           aData[18] = (u8)iVersion;
   53496           aData[19] = (u8)iVersion;
   53497         }
   53498       }
   53499     }
   53500   }
   53501 
   53502   pBt->doNotUseWAL = 0;
   53503   return rc;
   53504 }
   53505 
   53506 /************** End of btree.c ***********************************************/
   53507 /************** Begin file backup.c ******************************************/
   53508 /*
   53509 ** 2009 January 28
   53510 **
   53511 ** The author disclaims copyright to this source code.  In place of
   53512 ** a legal notice, here is a blessing:
   53513 **
   53514 **    May you do good and not evil.
   53515 **    May you find forgiveness for yourself and forgive others.
   53516 **    May you share freely, never taking more than you give.
   53517 **
   53518 *************************************************************************
   53519 ** This file contains the implementation of the sqlite3_backup_XXX()
   53520 ** API functions and the related features.
   53521 */
   53522 
   53523 /* Macro to find the minimum of two numeric values.
   53524 */
   53525 #ifndef MIN
   53526 # define MIN(x,y) ((x)<(y)?(x):(y))
   53527 #endif
   53528 
   53529 /*
   53530 ** Structure allocated for each backup operation.
   53531 */
   53532 struct sqlite3_backup {
   53533   sqlite3* pDestDb;        /* Destination database handle */
   53534   Btree *pDest;            /* Destination b-tree file */
   53535   u32 iDestSchema;         /* Original schema cookie in destination */
   53536   int bDestLocked;         /* True once a write-transaction is open on pDest */
   53537 
   53538   Pgno iNext;              /* Page number of the next source page to copy */
   53539   sqlite3* pSrcDb;         /* Source database handle */
   53540   Btree *pSrc;             /* Source b-tree file */
   53541 
   53542   int rc;                  /* Backup process error code */
   53543 
   53544   /* These two variables are set by every call to backup_step(). They are
   53545   ** read by calls to backup_remaining() and backup_pagecount().
   53546   */
   53547   Pgno nRemaining;         /* Number of pages left to copy */
   53548   Pgno nPagecount;         /* Total number of pages to copy */
   53549 
   53550   int isAttached;          /* True once backup has been registered with pager */
   53551   sqlite3_backup *pNext;   /* Next backup associated with source pager */
   53552 };
   53553 
   53554 /*
   53555 ** THREAD SAFETY NOTES:
   53556 **
   53557 **   Once it has been created using backup_init(), a single sqlite3_backup
   53558 **   structure may be accessed via two groups of thread-safe entry points:
   53559 **
   53560 **     * Via the sqlite3_backup_XXX() API function backup_step() and
   53561 **       backup_finish(). Both these functions obtain the source database
   53562 **       handle mutex and the mutex associated with the source BtShared
   53563 **       structure, in that order.
   53564 **
   53565 **     * Via the BackupUpdate() and BackupRestart() functions, which are
   53566 **       invoked by the pager layer to report various state changes in
   53567 **       the page cache associated with the source database. The mutex
   53568 **       associated with the source database BtShared structure will always
   53569 **       be held when either of these functions are invoked.
   53570 **
   53571 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
   53572 **   backup_pagecount() are not thread-safe functions. If they are called
   53573 **   while some other thread is calling backup_step() or backup_finish(),
   53574 **   the values returned may be invalid. There is no way for a call to
   53575 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
   53576 **   or backup_pagecount().
   53577 **
   53578 **   Depending on the SQLite configuration, the database handles and/or
   53579 **   the Btree objects may have their own mutexes that require locking.
   53580 **   Non-sharable Btrees (in-memory databases for example), do not have
   53581 **   associated mutexes.
   53582 */
   53583 
   53584 /*
   53585 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
   53586 ** in connection handle pDb. If such a database cannot be found, return
   53587 ** a NULL pointer and write an error message to pErrorDb.
   53588 **
   53589 ** If the "temp" database is requested, it may need to be opened by this
   53590 ** function. If an error occurs while doing so, return 0 and write an
   53591 ** error message to pErrorDb.
   53592 */
   53593 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
   53594   int i = sqlite3FindDbName(pDb, zDb);
   53595 
   53596   if( i==1 ){
   53597     Parse *pParse;
   53598     int rc = 0;
   53599     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
   53600     if( pParse==0 ){
   53601       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
   53602       rc = SQLITE_NOMEM;
   53603     }else{
   53604       pParse->db = pDb;
   53605       if( sqlite3OpenTempDatabase(pParse) ){
   53606         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
   53607         rc = SQLITE_ERROR;
   53608       }
   53609       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
   53610       sqlite3StackFree(pErrorDb, pParse);
   53611     }
   53612     if( rc ){
   53613       return 0;
   53614     }
   53615   }
   53616 
   53617   if( i<0 ){
   53618     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
   53619     return 0;
   53620   }
   53621 
   53622   return pDb->aDb[i].pBt;
   53623 }
   53624 
   53625 /*
   53626 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
   53627 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
   53628 ** a pointer to the new sqlite3_backup object.
   53629 **
   53630 ** If an error occurs, NULL is returned and an error code and error message
   53631 ** stored in database handle pDestDb.
   53632 */
   53633 SQLITE_API sqlite3_backup *sqlite3_backup_init(
   53634   sqlite3* pDestDb,                     /* Database to write to */
   53635   const char *zDestDb,                  /* Name of database within pDestDb */
   53636   sqlite3* pSrcDb,                      /* Database connection to read from */
   53637   const char *zSrcDb                    /* Name of database within pSrcDb */
   53638 ){
   53639   sqlite3_backup *p;                    /* Value to return */
   53640 
   53641   /* Lock the source database handle. The destination database
   53642   ** handle is not locked in this routine, but it is locked in
   53643   ** sqlite3_backup_step(). The user is required to ensure that no
   53644   ** other thread accesses the destination handle for the duration
   53645   ** of the backup operation.  Any attempt to use the destination
   53646   ** database connection while a backup is in progress may cause
   53647   ** a malfunction or a deadlock.
   53648   */
   53649   sqlite3_mutex_enter(pSrcDb->mutex);
   53650   sqlite3_mutex_enter(pDestDb->mutex);
   53651 
   53652   if( pSrcDb==pDestDb ){
   53653     sqlite3Error(
   53654         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
   53655     );
   53656     p = 0;
   53657   }else {
   53658     /* Allocate space for a new sqlite3_backup object...
   53659     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   53660     ** call to sqlite3_backup_init() and is destroyed by a call to
   53661     ** sqlite3_backup_finish(). */
   53662     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
   53663     if( !p ){
   53664       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
   53665     }
   53666   }
   53667 
   53668   /* If the allocation succeeded, populate the new object. */
   53669   if( p ){
   53670     memset(p, 0, sizeof(sqlite3_backup));
   53671     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
   53672     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
   53673     p->pDestDb = pDestDb;
   53674     p->pSrcDb = pSrcDb;
   53675     p->iNext = 1;
   53676     p->isAttached = 0;
   53677 
   53678     if( 0==p->pSrc || 0==p->pDest ){
   53679       /* One (or both) of the named databases did not exist. An error has
   53680       ** already been written into the pDestDb handle. All that is left
   53681       ** to do here is free the sqlite3_backup structure.
   53682       */
   53683       sqlite3_free(p);
   53684       p = 0;
   53685     }
   53686   }
   53687   if( p ){
   53688     p->pSrc->nBackup++;
   53689   }
   53690 
   53691   sqlite3_mutex_leave(pDestDb->mutex);
   53692   sqlite3_mutex_leave(pSrcDb->mutex);
   53693   return p;
   53694 }
   53695 
   53696 /*
   53697 ** Argument rc is an SQLite error code. Return true if this error is
   53698 ** considered fatal if encountered during a backup operation. All errors
   53699 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
   53700 */
   53701 static int isFatalError(int rc){
   53702   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
   53703 }
   53704 
   53705 /*
   53706 ** Parameter zSrcData points to a buffer containing the data for
   53707 ** page iSrcPg from the source database. Copy this data into the
   53708 ** destination database.
   53709 */
   53710 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
   53711   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
   53712   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
   53713   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   53714   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   53715   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
   53716 
   53717   int rc = SQLITE_OK;
   53718   i64 iOff;
   53719 
   53720   assert( p->bDestLocked );
   53721   assert( !isFatalError(p->rc) );
   53722   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
   53723   assert( zSrcData );
   53724 
   53725   /* Catch the case where the destination is an in-memory database and the
   53726   ** page sizes of the source and destination differ.
   53727   */
   53728   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
   53729     rc = SQLITE_READONLY;
   53730   }
   53731 
   53732 #ifdef SQLITE_HAS_CODEC
   53733   /* Backup is not possible if the page size of the destination is changing
   53734   ** a a codec is in use.
   53735   */
   53736   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
   53737     rc = SQLITE_READONLY;
   53738   }
   53739 #endif
   53740 
   53741   /* This loop runs once for each destination page spanned by the source
   53742   ** page. For each iteration, variable iOff is set to the byte offset
   53743   ** of the destination page.
   53744   */
   53745   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
   53746     DbPage *pDestPg = 0;
   53747     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
   53748     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
   53749     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
   53750      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
   53751     ){
   53752       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
   53753       u8 *zDestData = sqlite3PagerGetData(pDestPg);
   53754       u8 *zOut = &zDestData[iOff%nDestPgsz];
   53755 
   53756       /* Copy the data from the source page into the destination page.
   53757       ** Then clear the Btree layer MemPage.isInit flag. Both this module
   53758       ** and the pager code use this trick (clearing the first byte
   53759       ** of the page 'extra' space to invalidate the Btree layers
   53760       ** cached parse of the page). MemPage.isInit is marked
   53761       ** "MUST BE FIRST" for this purpose.
   53762       */
   53763       memcpy(zOut, zIn, nCopy);
   53764       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
   53765     }
   53766     sqlite3PagerUnref(pDestPg);
   53767   }
   53768 
   53769   return rc;
   53770 }
   53771 
   53772 /*
   53773 ** If pFile is currently larger than iSize bytes, then truncate it to
   53774 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
   53775 ** this function is a no-op.
   53776 **
   53777 ** Return SQLITE_OK if everything is successful, or an SQLite error
   53778 ** code if an error occurs.
   53779 */
   53780 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
   53781   i64 iCurrent;
   53782   int rc = sqlite3OsFileSize(pFile, &iCurrent);
   53783   if( rc==SQLITE_OK && iCurrent>iSize ){
   53784     rc = sqlite3OsTruncate(pFile, iSize);
   53785   }
   53786   return rc;
   53787 }
   53788 
   53789 /*
   53790 ** Register this backup object with the associated source pager for
   53791 ** callbacks when pages are changed or the cache invalidated.
   53792 */
   53793 static void attachBackupObject(sqlite3_backup *p){
   53794   sqlite3_backup **pp;
   53795   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
   53796   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   53797   p->pNext = *pp;
   53798   *pp = p;
   53799   p->isAttached = 1;
   53800 }
   53801 
   53802 /*
   53803 ** Copy nPage pages from the source b-tree to the destination.
   53804 */
   53805 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
   53806   int rc;
   53807   int destMode;       /* Destination journal mode */
   53808   int pgszSrc = 0;    /* Source page size */
   53809   int pgszDest = 0;   /* Destination page size */
   53810 
   53811   sqlite3_mutex_enter(p->pSrcDb->mutex);
   53812   sqlite3BtreeEnter(p->pSrc);
   53813   if( p->pDestDb ){
   53814     sqlite3_mutex_enter(p->pDestDb->mutex);
   53815   }
   53816 
   53817   rc = p->rc;
   53818   if( !isFatalError(rc) ){
   53819     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
   53820     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
   53821     int ii;                            /* Iterator variable */
   53822     int nSrcPage = -1;                 /* Size of source db in pages */
   53823     int bCloseTrans = 0;               /* True if src db requires unlocking */
   53824 
   53825     /* If the source pager is currently in a write-transaction, return
   53826     ** SQLITE_BUSY immediately.
   53827     */
   53828     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
   53829       rc = SQLITE_BUSY;
   53830     }else{
   53831       rc = SQLITE_OK;
   53832     }
   53833 
   53834     /* Lock the destination database, if it is not locked already. */
   53835     if( SQLITE_OK==rc && p->bDestLocked==0
   53836      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
   53837     ){
   53838       p->bDestLocked = 1;
   53839       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
   53840     }
   53841 
   53842     /* If there is no open read-transaction on the source database, open
   53843     ** one now. If a transaction is opened here, then it will be closed
   53844     ** before this function exits.
   53845     */
   53846     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
   53847       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
   53848       bCloseTrans = 1;
   53849     }
   53850 
   53851     /* Do not allow backup if the destination database is in WAL mode
   53852     ** and the page sizes are different between source and destination */
   53853     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
   53854     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
   53855     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
   53856     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
   53857       rc = SQLITE_READONLY;
   53858     }
   53859 
   53860     /* Now that there is a read-lock on the source database, query the
   53861     ** source pager for the number of pages in the database.
   53862     */
   53863     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
   53864     assert( nSrcPage>=0 );
   53865     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
   53866       const Pgno iSrcPg = p->iNext;                 /* Source page number */
   53867       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
   53868         DbPage *pSrcPg;                             /* Source page object */
   53869         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   53870         if( rc==SQLITE_OK ){
   53871           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
   53872           sqlite3PagerUnref(pSrcPg);
   53873         }
   53874       }
   53875       p->iNext++;
   53876     }
   53877     if( rc==SQLITE_OK ){
   53878       p->nPagecount = nSrcPage;
   53879       p->nRemaining = nSrcPage+1-p->iNext;
   53880       if( p->iNext>(Pgno)nSrcPage ){
   53881         rc = SQLITE_DONE;
   53882       }else if( !p->isAttached ){
   53883         attachBackupObject(p);
   53884       }
   53885     }
   53886 
   53887     /* Update the schema version field in the destination database. This
   53888     ** is to make sure that the schema-version really does change in
   53889     ** the case where the source and destination databases have the
   53890     ** same schema version.
   53891     */
   53892     if( rc==SQLITE_DONE
   53893      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
   53894     ){
   53895       int nDestTruncate;
   53896 
   53897       if( p->pDestDb ){
   53898         sqlite3ResetInternalSchema(p->pDestDb, 0);
   53899       }
   53900 
   53901       /* Set nDestTruncate to the final number of pages in the destination
   53902       ** database. The complication here is that the destination page
   53903       ** size may be different to the source page size.
   53904       **
   53905       ** If the source page size is smaller than the destination page size,
   53906       ** round up. In this case the call to sqlite3OsTruncate() below will
   53907       ** fix the size of the file. However it is important to call
   53908       ** sqlite3PagerTruncateImage() here so that any pages in the
   53909       ** destination file that lie beyond the nDestTruncate page mark are
   53910       ** journalled by PagerCommitPhaseOne() before they are destroyed
   53911       ** by the file truncation.
   53912       */
   53913       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
   53914       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
   53915       if( pgszSrc<pgszDest ){
   53916         int ratio = pgszDest/pgszSrc;
   53917         nDestTruncate = (nSrcPage+ratio-1)/ratio;
   53918         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
   53919           nDestTruncate--;
   53920         }
   53921       }else{
   53922         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
   53923       }
   53924       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
   53925 
   53926       if( pgszSrc<pgszDest ){
   53927         /* If the source page-size is smaller than the destination page-size,
   53928         ** two extra things may need to happen:
   53929         **
   53930         **   * The destination may need to be truncated, and
   53931         **
   53932         **   * Data stored on the pages immediately following the
   53933         **     pending-byte page in the source database may need to be
   53934         **     copied into the destination database.
   53935         */
   53936         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
   53937         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
   53938 
   53939         assert( pFile );
   53940         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
   53941               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
   53942            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
   53943         ));
   53944         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
   53945          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
   53946          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
   53947         ){
   53948           i64 iOff;
   53949           i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
   53950           for(
   53951             iOff=PENDING_BYTE+pgszSrc;
   53952             rc==SQLITE_OK && iOff<iEnd;
   53953             iOff+=pgszSrc
   53954           ){
   53955             PgHdr *pSrcPg = 0;
   53956             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
   53957             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
   53958             if( rc==SQLITE_OK ){
   53959               u8 *zData = sqlite3PagerGetData(pSrcPg);
   53960               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
   53961             }
   53962             sqlite3PagerUnref(pSrcPg);
   53963           }
   53964         }
   53965       }else{
   53966         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
   53967       }
   53968 
   53969       /* Finish committing the transaction to the destination database. */
   53970       if( SQLITE_OK==rc
   53971        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
   53972       ){
   53973         rc = SQLITE_DONE;
   53974       }
   53975     }
   53976 
   53977     /* If bCloseTrans is true, then this function opened a read transaction
   53978     ** on the source database. Close the read transaction here. There is
   53979     ** no need to check the return values of the btree methods here, as
   53980     ** "committing" a read-only transaction cannot fail.
   53981     */
   53982     if( bCloseTrans ){
   53983       TESTONLY( int rc2 );
   53984       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
   53985       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
   53986       assert( rc2==SQLITE_OK );
   53987     }
   53988 
   53989     if( rc==SQLITE_IOERR_NOMEM ){
   53990       rc = SQLITE_NOMEM;
   53991     }
   53992     p->rc = rc;
   53993   }
   53994   if( p->pDestDb ){
   53995     sqlite3_mutex_leave(p->pDestDb->mutex);
   53996   }
   53997   sqlite3BtreeLeave(p->pSrc);
   53998   sqlite3_mutex_leave(p->pSrcDb->mutex);
   53999   return rc;
   54000 }
   54001 
   54002 /*
   54003 ** Release all resources associated with an sqlite3_backup* handle.
   54004 */
   54005 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
   54006   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
   54007   sqlite3_mutex *mutex;                /* Mutex to protect source database */
   54008   int rc;                              /* Value to return */
   54009 
   54010   /* Enter the mutexes */
   54011   if( p==0 ) return SQLITE_OK;
   54012   sqlite3_mutex_enter(p->pSrcDb->mutex);
   54013   sqlite3BtreeEnter(p->pSrc);
   54014   mutex = p->pSrcDb->mutex;
   54015   if( p->pDestDb ){
   54016     sqlite3_mutex_enter(p->pDestDb->mutex);
   54017   }
   54018 
   54019   /* Detach this backup from the source pager. */
   54020   if( p->pDestDb ){
   54021     p->pSrc->nBackup--;
   54022   }
   54023   if( p->isAttached ){
   54024     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
   54025     while( *pp!=p ){
   54026       pp = &(*pp)->pNext;
   54027     }
   54028     *pp = p->pNext;
   54029   }
   54030 
   54031   /* If a transaction is still open on the Btree, roll it back. */
   54032   sqlite3BtreeRollback(p->pDest);
   54033 
   54034   /* Set the error code of the destination database handle. */
   54035   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
   54036   sqlite3Error(p->pDestDb, rc, 0);
   54037 
   54038   /* Exit the mutexes and free the backup context structure. */
   54039   if( p->pDestDb ){
   54040     sqlite3_mutex_leave(p->pDestDb->mutex);
   54041   }
   54042   sqlite3BtreeLeave(p->pSrc);
   54043   if( p->pDestDb ){
   54044     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
   54045     ** call to sqlite3_backup_init() and is destroyed by a call to
   54046     ** sqlite3_backup_finish(). */
   54047     sqlite3_free(p);
   54048   }
   54049   sqlite3_mutex_leave(mutex);
   54050   return rc;
   54051 }
   54052 
   54053 /*
   54054 ** Return the number of pages still to be backed up as of the most recent
   54055 ** call to sqlite3_backup_step().
   54056 */
   54057 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
   54058   return p->nRemaining;
   54059 }
   54060 
   54061 /*
   54062 ** Return the total number of pages in the source database as of the most
   54063 ** recent call to sqlite3_backup_step().
   54064 */
   54065 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
   54066   return p->nPagecount;
   54067 }
   54068 
   54069 /*
   54070 ** This function is called after the contents of page iPage of the
   54071 ** source database have been modified. If page iPage has already been
   54072 ** copied into the destination database, then the data written to the
   54073 ** destination is now invalidated. The destination copy of iPage needs
   54074 ** to be updated with the new data before the backup operation is
   54075 ** complete.
   54076 **
   54077 ** It is assumed that the mutex associated with the BtShared object
   54078 ** corresponding to the source database is held when this function is
   54079 ** called.
   54080 */
   54081 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
   54082   sqlite3_backup *p;                   /* Iterator variable */
   54083   for(p=pBackup; p; p=p->pNext){
   54084     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   54085     if( !isFatalError(p->rc) && iPage<p->iNext ){
   54086       /* The backup process p has already copied page iPage. But now it
   54087       ** has been modified by a transaction on the source pager. Copy
   54088       ** the new data into the backup.
   54089       */
   54090       int rc = backupOnePage(p, iPage, aData);
   54091       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
   54092       if( rc!=SQLITE_OK ){
   54093         p->rc = rc;
   54094       }
   54095     }
   54096   }
   54097 }
   54098 
   54099 /*
   54100 ** Restart the backup process. This is called when the pager layer
   54101 ** detects that the database has been modified by an external database
   54102 ** connection. In this case there is no way of knowing which of the
   54103 ** pages that have been copied into the destination database are still
   54104 ** valid and which are not, so the entire process needs to be restarted.
   54105 **
   54106 ** It is assumed that the mutex associated with the BtShared object
   54107 ** corresponding to the source database is held when this function is
   54108 ** called.
   54109 */
   54110 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
   54111   sqlite3_backup *p;                   /* Iterator variable */
   54112   for(p=pBackup; p; p=p->pNext){
   54113     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
   54114     p->iNext = 1;
   54115   }
   54116 }
   54117 
   54118 #ifndef SQLITE_OMIT_VACUUM
   54119 /*
   54120 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
   54121 ** must be active for both files.
   54122 **
   54123 ** The size of file pTo may be reduced by this operation. If anything
   54124 ** goes wrong, the transaction on pTo is rolled back. If successful, the
   54125 ** transaction is committed before returning.
   54126 */
   54127 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   54128   int rc;
   54129   sqlite3_backup b;
   54130   sqlite3BtreeEnter(pTo);
   54131   sqlite3BtreeEnter(pFrom);
   54132 
   54133   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   54134   ** to 0. This is used by the implementations of sqlite3_backup_step()
   54135   ** and sqlite3_backup_finish() to detect that they are being called
   54136   ** from this function, not directly by the user.
   54137   */
   54138   memset(&b, 0, sizeof(b));
   54139   b.pSrcDb = pFrom->db;
   54140   b.pSrc = pFrom;
   54141   b.pDest = pTo;
   54142   b.iNext = 1;
   54143 
   54144   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   54145   ** file. By passing this as the number of pages to copy to
   54146   ** sqlite3_backup_step(), we can guarantee that the copy finishes
   54147   ** within a single call (unless an error occurs). The assert() statement
   54148   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   54149   ** or an error code.
   54150   */
   54151   sqlite3_backup_step(&b, 0x7FFFFFFF);
   54152   assert( b.rc!=SQLITE_OK );
   54153   rc = sqlite3_backup_finish(&b);
   54154   if( rc==SQLITE_OK ){
   54155     pTo->pBt->pageSizeFixed = 0;
   54156   }
   54157 
   54158   sqlite3BtreeLeave(pFrom);
   54159   sqlite3BtreeLeave(pTo);
   54160   return rc;
   54161 }
   54162 #endif /* SQLITE_OMIT_VACUUM */
   54163 
   54164 /************** End of backup.c **********************************************/
   54165 /************** Begin file vdbemem.c *****************************************/
   54166 /*
   54167 ** 2004 May 26
   54168 **
   54169 ** The author disclaims copyright to this source code.  In place of
   54170 ** a legal notice, here is a blessing:
   54171 **
   54172 **    May you do good and not evil.
   54173 **    May you find forgiveness for yourself and forgive others.
   54174 **    May you share freely, never taking more than you give.
   54175 **
   54176 *************************************************************************
   54177 **
   54178 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
   54179 ** stores a single value in the VDBE.  Mem is an opaque structure visible
   54180 ** only within the VDBE.  Interface routines refer to a Mem using the
   54181 ** name sqlite_value
   54182 */
   54183 
   54184 /*
   54185 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
   54186 ** P if required.
   54187 */
   54188 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   54189 
   54190 /*
   54191 ** If pMem is an object with a valid string representation, this routine
   54192 ** ensures the internal encoding for the string representation is
   54193 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
   54194 **
   54195 ** If pMem is not a string object, or the encoding of the string
   54196 ** representation is already stored using the requested encoding, then this
   54197 ** routine is a no-op.
   54198 **
   54199 ** SQLITE_OK is returned if the conversion is successful (or not required).
   54200 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
   54201 ** between formats.
   54202 */
   54203 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
   54204   int rc;
   54205   assert( (pMem->flags&MEM_RowSet)==0 );
   54206   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
   54207            || desiredEnc==SQLITE_UTF16BE );
   54208   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
   54209     return SQLITE_OK;
   54210   }
   54211   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54212 #ifdef SQLITE_OMIT_UTF16
   54213   return SQLITE_ERROR;
   54214 #else
   54215 
   54216   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
   54217   ** then the encoding of the value may not have changed.
   54218   */
   54219   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
   54220   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
   54221   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
   54222   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
   54223   return rc;
   54224 #endif
   54225 }
   54226 
   54227 /*
   54228 ** Make sure pMem->z points to a writable allocation of at least
   54229 ** n bytes.
   54230 **
   54231 ** If the memory cell currently contains string or blob data
   54232 ** and the third argument passed to this function is true, the
   54233 ** current content of the cell is preserved. Otherwise, it may
   54234 ** be discarded.
   54235 **
   54236 ** This function sets the MEM_Dyn flag and clears any xDel callback.
   54237 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
   54238 ** not set, Mem.n is zeroed.
   54239 */
   54240 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
   54241   assert( 1 >=
   54242     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
   54243     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
   54244     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
   54245     ((pMem->flags&MEM_Static) ? 1 : 0)
   54246   );
   54247   assert( (pMem->flags&MEM_RowSet)==0 );
   54248 
   54249   if( n<32 ) n = 32;
   54250   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
   54251     if( preserve && pMem->z==pMem->zMalloc ){
   54252       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
   54253       preserve = 0;
   54254     }else{
   54255       sqlite3DbFree(pMem->db, pMem->zMalloc);
   54256       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
   54257     }
   54258   }
   54259 
   54260   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
   54261     memcpy(pMem->zMalloc, pMem->z, pMem->n);
   54262   }
   54263   if( pMem->flags&MEM_Dyn && pMem->xDel ){
   54264     pMem->xDel((void *)(pMem->z));
   54265   }
   54266 
   54267   pMem->z = pMem->zMalloc;
   54268   if( pMem->z==0 ){
   54269     pMem->flags = MEM_Null;
   54270   }else{
   54271     pMem->flags &= ~(MEM_Ephem|MEM_Static);
   54272   }
   54273   pMem->xDel = 0;
   54274   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
   54275 }
   54276 
   54277 /*
   54278 ** Make the given Mem object MEM_Dyn.  In other words, make it so
   54279 ** that any TEXT or BLOB content is stored in memory obtained from
   54280 ** malloc().  In this way, we know that the memory is safe to be
   54281 ** overwritten or altered.
   54282 **
   54283 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
   54284 */
   54285 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
   54286   int f;
   54287   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54288   assert( (pMem->flags&MEM_RowSet)==0 );
   54289   expandBlob(pMem);
   54290   f = pMem->flags;
   54291   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
   54292     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
   54293       return SQLITE_NOMEM;
   54294     }
   54295     pMem->z[pMem->n] = 0;
   54296     pMem->z[pMem->n+1] = 0;
   54297     pMem->flags |= MEM_Term;
   54298 #ifdef SQLITE_DEBUG
   54299     pMem->pScopyFrom = 0;
   54300 #endif
   54301   }
   54302 
   54303   return SQLITE_OK;
   54304 }
   54305 
   54306 /*
   54307 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
   54308 ** blob stored in dynamically allocated space.
   54309 */
   54310 #ifndef SQLITE_OMIT_INCRBLOB
   54311 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
   54312   if( pMem->flags & MEM_Zero ){
   54313     int nByte;
   54314     assert( pMem->flags&MEM_Blob );
   54315     assert( (pMem->flags&MEM_RowSet)==0 );
   54316     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54317 
   54318     /* Set nByte to the number of bytes required to store the expanded blob. */
   54319     nByte = pMem->n + pMem->u.nZero;
   54320     if( nByte<=0 ){
   54321       nByte = 1;
   54322     }
   54323     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
   54324       return SQLITE_NOMEM;
   54325     }
   54326 
   54327     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
   54328     pMem->n += pMem->u.nZero;
   54329     pMem->flags &= ~(MEM_Zero|MEM_Term);
   54330   }
   54331   return SQLITE_OK;
   54332 }
   54333 #endif
   54334 
   54335 
   54336 /*
   54337 ** Make sure the given Mem is \u0000 terminated.
   54338 */
   54339 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
   54340   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54341   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
   54342     return SQLITE_OK;   /* Nothing to do */
   54343   }
   54344   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
   54345     return SQLITE_NOMEM;
   54346   }
   54347   pMem->z[pMem->n] = 0;
   54348   pMem->z[pMem->n+1] = 0;
   54349   pMem->flags |= MEM_Term;
   54350   return SQLITE_OK;
   54351 }
   54352 
   54353 /*
   54354 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
   54355 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
   54356 ** is a no-op.
   54357 **
   54358 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
   54359 **
   54360 ** A MEM_Null value will never be passed to this function. This function is
   54361 ** used for converting values to text for returning to the user (i.e. via
   54362 ** sqlite3_value_text()), or for ensuring that values to be used as btree
   54363 ** keys are strings. In the former case a NULL pointer is returned the
   54364 ** user and the later is an internal programming error.
   54365 */
   54366 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
   54367   int rc = SQLITE_OK;
   54368   int fg = pMem->flags;
   54369   const int nByte = 32;
   54370 
   54371   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54372   assert( !(fg&MEM_Zero) );
   54373   assert( !(fg&(MEM_Str|MEM_Blob)) );
   54374   assert( fg&(MEM_Int|MEM_Real) );
   54375   assert( (pMem->flags&MEM_RowSet)==0 );
   54376   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54377 
   54378 
   54379   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   54380     return SQLITE_NOMEM;
   54381   }
   54382 
   54383   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
   54384   ** string representation of the value. Then, if the required encoding
   54385   ** is UTF-16le or UTF-16be do a translation.
   54386   **
   54387   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
   54388   */
   54389   if( fg & MEM_Int ){
   54390     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
   54391   }else{
   54392     assert( fg & MEM_Real );
   54393     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
   54394   }
   54395   pMem->n = sqlite3Strlen30(pMem->z);
   54396   pMem->enc = SQLITE_UTF8;
   54397   pMem->flags |= MEM_Str|MEM_Term;
   54398   sqlite3VdbeChangeEncoding(pMem, enc);
   54399   return rc;
   54400 }
   54401 
   54402 /*
   54403 ** Memory cell pMem contains the context of an aggregate function.
   54404 ** This routine calls the finalize method for that function.  The
   54405 ** result of the aggregate is stored back into pMem.
   54406 **
   54407 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
   54408 ** otherwise.
   54409 */
   54410 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
   54411   int rc = SQLITE_OK;
   54412   if( ALWAYS(pFunc && pFunc->xFinalize) ){
   54413     sqlite3_context ctx;
   54414     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
   54415     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54416     memset(&ctx, 0, sizeof(ctx));
   54417     ctx.s.flags = MEM_Null;
   54418     ctx.s.db = pMem->db;
   54419     ctx.pMem = pMem;
   54420     ctx.pFunc = pFunc;
   54421     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
   54422     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
   54423     sqlite3DbFree(pMem->db, pMem->zMalloc);
   54424     memcpy(pMem, &ctx.s, sizeof(ctx.s));
   54425     rc = ctx.isError;
   54426   }
   54427   return rc;
   54428 }
   54429 
   54430 /*
   54431 ** If the memory cell contains a string value that must be freed by
   54432 ** invoking an external callback, free it now. Calling this function
   54433 ** does not free any Mem.zMalloc buffer.
   54434 */
   54435 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
   54436   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   54437   testcase( p->flags & MEM_Agg );
   54438   testcase( p->flags & MEM_Dyn );
   54439   testcase( p->flags & MEM_RowSet );
   54440   testcase( p->flags & MEM_Frame );
   54441   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
   54442     if( p->flags&MEM_Agg ){
   54443       sqlite3VdbeMemFinalize(p, p->u.pDef);
   54444       assert( (p->flags & MEM_Agg)==0 );
   54445       sqlite3VdbeMemRelease(p);
   54446     }else if( p->flags&MEM_Dyn && p->xDel ){
   54447       assert( (p->flags&MEM_RowSet)==0 );
   54448       p->xDel((void *)p->z);
   54449       p->xDel = 0;
   54450     }else if( p->flags&MEM_RowSet ){
   54451       sqlite3RowSetClear(p->u.pRowSet);
   54452     }else if( p->flags&MEM_Frame ){
   54453       sqlite3VdbeMemSetNull(p);
   54454     }
   54455   }
   54456 }
   54457 
   54458 /*
   54459 ** Release any memory held by the Mem. This may leave the Mem in an
   54460 ** inconsistent state, for example with (Mem.z==0) and
   54461 ** (Mem.type==SQLITE_TEXT).
   54462 */
   54463 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
   54464   sqlite3VdbeMemReleaseExternal(p);
   54465   sqlite3DbFree(p->db, p->zMalloc);
   54466   p->z = 0;
   54467   p->zMalloc = 0;
   54468   p->xDel = 0;
   54469 }
   54470 
   54471 /*
   54472 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
   54473 ** If the double is too large, return 0x8000000000000000.
   54474 **
   54475 ** Most systems appear to do this simply by assigning
   54476 ** variables and without the extra range tests.  But
   54477 ** there are reports that windows throws an expection
   54478 ** if the floating point value is out of range. (See ticket #2880.)
   54479 ** Because we do not completely understand the problem, we will
   54480 ** take the conservative approach and always do range tests
   54481 ** before attempting the conversion.
   54482 */
   54483 static i64 doubleToInt64(double r){
   54484 #ifdef SQLITE_OMIT_FLOATING_POINT
   54485   /* When floating-point is omitted, double and int64 are the same thing */
   54486   return r;
   54487 #else
   54488   /*
   54489   ** Many compilers we encounter do not define constants for the
   54490   ** minimum and maximum 64-bit integers, or they define them
   54491   ** inconsistently.  And many do not understand the "LL" notation.
   54492   ** So we define our own static constants here using nothing
   54493   ** larger than a 32-bit integer constant.
   54494   */
   54495   static const i64 maxInt = LARGEST_INT64;
   54496   static const i64 minInt = SMALLEST_INT64;
   54497 
   54498   if( r<(double)minInt ){
   54499     return minInt;
   54500   }else if( r>(double)maxInt ){
   54501     /* minInt is correct here - not maxInt.  It turns out that assigning
   54502     ** a very large positive number to an integer results in a very large
   54503     ** negative integer.  This makes no sense, but it is what x86 hardware
   54504     ** does so for compatibility we will do the same in software. */
   54505     return minInt;
   54506   }else{
   54507     return (i64)r;
   54508   }
   54509 #endif
   54510 }
   54511 
   54512 /*
   54513 ** Return some kind of integer value which is the best we can do
   54514 ** at representing the value that *pMem describes as an integer.
   54515 ** If pMem is an integer, then the value is exact.  If pMem is
   54516 ** a floating-point then the value returned is the integer part.
   54517 ** If pMem is a string or blob, then we make an attempt to convert
   54518 ** it into a integer and return that.  If pMem represents an
   54519 ** an SQL-NULL value, return 0.
   54520 **
   54521 ** If pMem represents a string value, its encoding might be changed.
   54522 */
   54523 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
   54524   int flags;
   54525   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54526   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54527   flags = pMem->flags;
   54528   if( flags & MEM_Int ){
   54529     return pMem->u.i;
   54530   }else if( flags & MEM_Real ){
   54531     return doubleToInt64(pMem->r);
   54532   }else if( flags & (MEM_Str|MEM_Blob) ){
   54533     i64 value;
   54534     assert( pMem->z || pMem->n==0 );
   54535     testcase( pMem->z==0 );
   54536     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
   54537     return value;
   54538   }else{
   54539     return 0;
   54540   }
   54541 }
   54542 
   54543 /*
   54544 ** Return the best representation of pMem that we can get into a
   54545 ** double.  If pMem is already a double or an integer, return its
   54546 ** value.  If it is a string or blob, try to convert it to a double.
   54547 ** If it is a NULL, return 0.0.
   54548 */
   54549 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
   54550   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54551   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54552   if( pMem->flags & MEM_Real ){
   54553     return pMem->r;
   54554   }else if( pMem->flags & MEM_Int ){
   54555     return (double)pMem->u.i;
   54556   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
   54557     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   54558     double val = (double)0;
   54559     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
   54560     return val;
   54561   }else{
   54562     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   54563     return (double)0;
   54564   }
   54565 }
   54566 
   54567 /*
   54568 ** The MEM structure is already a MEM_Real.  Try to also make it a
   54569 ** MEM_Int if we can.
   54570 */
   54571 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
   54572   assert( pMem->flags & MEM_Real );
   54573   assert( (pMem->flags & MEM_RowSet)==0 );
   54574   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54575   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54576 
   54577   pMem->u.i = doubleToInt64(pMem->r);
   54578 
   54579   /* Only mark the value as an integer if
   54580   **
   54581   **    (1) the round-trip conversion real->int->real is a no-op, and
   54582   **    (2) The integer is neither the largest nor the smallest
   54583   **        possible integer (ticket #3922)
   54584   **
   54585   ** The second and third terms in the following conditional enforces
   54586   ** the second condition under the assumption that addition overflow causes
   54587   ** values to wrap around.  On x86 hardware, the third term is always
   54588   ** true and could be omitted.  But we leave it in because other
   54589   ** architectures might behave differently.
   54590   */
   54591   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
   54592       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
   54593     pMem->flags |= MEM_Int;
   54594   }
   54595 }
   54596 
   54597 /*
   54598 ** Convert pMem to type integer.  Invalidate any prior representations.
   54599 */
   54600 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
   54601   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54602   assert( (pMem->flags & MEM_RowSet)==0 );
   54603   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54604 
   54605   pMem->u.i = sqlite3VdbeIntValue(pMem);
   54606   MemSetTypeFlag(pMem, MEM_Int);
   54607   return SQLITE_OK;
   54608 }
   54609 
   54610 /*
   54611 ** Convert pMem so that it is of type MEM_Real.
   54612 ** Invalidate any prior representations.
   54613 */
   54614 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
   54615   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54616   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   54617 
   54618   pMem->r = sqlite3VdbeRealValue(pMem);
   54619   MemSetTypeFlag(pMem, MEM_Real);
   54620   return SQLITE_OK;
   54621 }
   54622 
   54623 /*
   54624 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
   54625 ** Invalidate any prior representations.
   54626 **
   54627 ** Every effort is made to force the conversion, even if the input
   54628 ** is a string that does not look completely like a number.  Convert
   54629 ** as much of the string as we can and ignore the rest.
   54630 */
   54631 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
   54632   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
   54633     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
   54634     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54635     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
   54636       MemSetTypeFlag(pMem, MEM_Int);
   54637     }else{
   54638       pMem->r = sqlite3VdbeRealValue(pMem);
   54639       MemSetTypeFlag(pMem, MEM_Real);
   54640       sqlite3VdbeIntegerAffinity(pMem);
   54641     }
   54642   }
   54643   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
   54644   pMem->flags &= ~(MEM_Str|MEM_Blob);
   54645   return SQLITE_OK;
   54646 }
   54647 
   54648 /*
   54649 ** Delete any previous value and set the value stored in *pMem to NULL.
   54650 */
   54651 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   54652   if( pMem->flags & MEM_Frame ){
   54653     VdbeFrame *pFrame = pMem->u.pFrame;
   54654     pFrame->pParent = pFrame->v->pDelFrame;
   54655     pFrame->v->pDelFrame = pFrame;
   54656   }
   54657   if( pMem->flags & MEM_RowSet ){
   54658     sqlite3RowSetClear(pMem->u.pRowSet);
   54659   }
   54660   MemSetTypeFlag(pMem, MEM_Null);
   54661   pMem->type = SQLITE_NULL;
   54662 }
   54663 
   54664 /*
   54665 ** Delete any previous value and set the value to be a BLOB of length
   54666 ** n containing all zeros.
   54667 */
   54668 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
   54669   sqlite3VdbeMemRelease(pMem);
   54670   pMem->flags = MEM_Blob|MEM_Zero;
   54671   pMem->type = SQLITE_BLOB;
   54672   pMem->n = 0;
   54673   if( n<0 ) n = 0;
   54674   pMem->u.nZero = n;
   54675   pMem->enc = SQLITE_UTF8;
   54676 
   54677 #ifdef SQLITE_OMIT_INCRBLOB
   54678   sqlite3VdbeMemGrow(pMem, n, 0);
   54679   if( pMem->z ){
   54680     pMem->n = n;
   54681     memset(pMem->z, 0, n);
   54682   }
   54683 #endif
   54684 }
   54685 
   54686 /*
   54687 ** Delete any previous value and set the value stored in *pMem to val,
   54688 ** manifest type INTEGER.
   54689 */
   54690 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
   54691   sqlite3VdbeMemRelease(pMem);
   54692   pMem->u.i = val;
   54693   pMem->flags = MEM_Int;
   54694   pMem->type = SQLITE_INTEGER;
   54695 }
   54696 
   54697 #ifndef SQLITE_OMIT_FLOATING_POINT
   54698 /*
   54699 ** Delete any previous value and set the value stored in *pMem to val,
   54700 ** manifest type REAL.
   54701 */
   54702 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
   54703   if( sqlite3IsNaN(val) ){
   54704     sqlite3VdbeMemSetNull(pMem);
   54705   }else{
   54706     sqlite3VdbeMemRelease(pMem);
   54707     pMem->r = val;
   54708     pMem->flags = MEM_Real;
   54709     pMem->type = SQLITE_FLOAT;
   54710   }
   54711 }
   54712 #endif
   54713 
   54714 /*
   54715 ** Delete any previous value and set the value of pMem to be an
   54716 ** empty boolean index.
   54717 */
   54718 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
   54719   sqlite3 *db = pMem->db;
   54720   assert( db!=0 );
   54721   assert( (pMem->flags & MEM_RowSet)==0 );
   54722   sqlite3VdbeMemRelease(pMem);
   54723   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
   54724   if( db->mallocFailed ){
   54725     pMem->flags = MEM_Null;
   54726   }else{
   54727     assert( pMem->zMalloc );
   54728     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
   54729                                        sqlite3DbMallocSize(db, pMem->zMalloc));
   54730     assert( pMem->u.pRowSet!=0 );
   54731     pMem->flags = MEM_RowSet;
   54732   }
   54733 }
   54734 
   54735 /*
   54736 ** Return true if the Mem object contains a TEXT or BLOB that is
   54737 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
   54738 */
   54739 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
   54740   assert( p->db!=0 );
   54741   if( p->flags & (MEM_Str|MEM_Blob) ){
   54742     int n = p->n;
   54743     if( p->flags & MEM_Zero ){
   54744       n += p->u.nZero;
   54745     }
   54746     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   54747   }
   54748   return 0;
   54749 }
   54750 
   54751 #ifdef SQLITE_DEBUG
   54752 /*
   54753 ** This routine prepares a memory cell for modication by breaking
   54754 ** its link to a shallow copy and by marking any current shallow
   54755 ** copies of this cell as invalid.
   54756 **
   54757 ** This is used for testing and debugging only - to make sure shallow
   54758 ** copies are not misused.
   54759 */
   54760 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
   54761   int i;
   54762   Mem *pX;
   54763   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
   54764     if( pX->pScopyFrom==pMem ){
   54765       pX->flags |= MEM_Invalid;
   54766       pX->pScopyFrom = 0;
   54767     }
   54768   }
   54769   pMem->pScopyFrom = 0;
   54770 }
   54771 #endif /* SQLITE_DEBUG */
   54772 
   54773 /*
   54774 ** Size of struct Mem not including the Mem.zMalloc member.
   54775 */
   54776 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
   54777 
   54778 /*
   54779 ** Make an shallow copy of pFrom into pTo.  Prior contents of
   54780 ** pTo are freed.  The pFrom->z field is not duplicated.  If
   54781 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
   54782 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
   54783 */
   54784 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
   54785   assert( (pFrom->flags & MEM_RowSet)==0 );
   54786   sqlite3VdbeMemReleaseExternal(pTo);
   54787   memcpy(pTo, pFrom, MEMCELLSIZE);
   54788   pTo->xDel = 0;
   54789   if( (pFrom->flags&MEM_Static)==0 ){
   54790     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
   54791     assert( srcType==MEM_Ephem || srcType==MEM_Static );
   54792     pTo->flags |= srcType;
   54793   }
   54794 }
   54795 
   54796 /*
   54797 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
   54798 ** freed before the copy is made.
   54799 */
   54800 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   54801   int rc = SQLITE_OK;
   54802 
   54803   assert( (pFrom->flags & MEM_RowSet)==0 );
   54804   sqlite3VdbeMemReleaseExternal(pTo);
   54805   memcpy(pTo, pFrom, MEMCELLSIZE);
   54806   pTo->flags &= ~MEM_Dyn;
   54807 
   54808   if( pTo->flags&(MEM_Str|MEM_Blob) ){
   54809     if( 0==(pFrom->flags&MEM_Static) ){
   54810       pTo->flags |= MEM_Ephem;
   54811       rc = sqlite3VdbeMemMakeWriteable(pTo);
   54812     }
   54813   }
   54814 
   54815   return rc;
   54816 }
   54817 
   54818 /*
   54819 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
   54820 ** freed. If pFrom contains ephemeral data, a copy is made.
   54821 **
   54822 ** pFrom contains an SQL NULL when this routine returns.
   54823 */
   54824 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
   54825   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
   54826   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
   54827   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
   54828 
   54829   sqlite3VdbeMemRelease(pTo);
   54830   memcpy(pTo, pFrom, sizeof(Mem));
   54831   pFrom->flags = MEM_Null;
   54832   pFrom->xDel = 0;
   54833   pFrom->zMalloc = 0;
   54834 }
   54835 
   54836 /*
   54837 ** Change the value of a Mem to be a string or a BLOB.
   54838 **
   54839 ** The memory management strategy depends on the value of the xDel
   54840 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
   54841 ** string is copied into a (possibly existing) buffer managed by the
   54842 ** Mem structure. Otherwise, any existing buffer is freed and the
   54843 ** pointer copied.
   54844 **
   54845 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
   54846 ** size limit) then no memory allocation occurs.  If the string can be
   54847 ** stored without allocating memory, then it is.  If a memory allocation
   54848 ** is required to store the string, then value of pMem is unchanged.  In
   54849 ** either case, SQLITE_TOOBIG is returned.
   54850 */
   54851 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
   54852   Mem *pMem,          /* Memory cell to set to string value */
   54853   const char *z,      /* String pointer */
   54854   int n,              /* Bytes in string, or negative */
   54855   u8 enc,             /* Encoding of z.  0 for BLOBs */
   54856   void (*xDel)(void*) /* Destructor function */
   54857 ){
   54858   int nByte = n;      /* New value for pMem->n */
   54859   int iLimit;         /* Maximum allowed string or blob size */
   54860   u16 flags = 0;      /* New value for pMem->flags */
   54861 
   54862   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
   54863   assert( (pMem->flags & MEM_RowSet)==0 );
   54864 
   54865   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
   54866   if( !z ){
   54867     sqlite3VdbeMemSetNull(pMem);
   54868     return SQLITE_OK;
   54869   }
   54870 
   54871   if( pMem->db ){
   54872     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
   54873   }else{
   54874     iLimit = SQLITE_MAX_LENGTH;
   54875   }
   54876   flags = (enc==0?MEM_Blob:MEM_Str);
   54877   if( nByte<0 ){
   54878     assert( enc!=0 );
   54879     if( enc==SQLITE_UTF8 ){
   54880       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
   54881     }else{
   54882       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
   54883     }
   54884     flags |= MEM_Term;
   54885   }
   54886 
   54887   /* The following block sets the new values of Mem.z and Mem.xDel. It
   54888   ** also sets a flag in local variable "flags" to indicate the memory
   54889   ** management (one of MEM_Dyn or MEM_Static).
   54890   */
   54891   if( xDel==SQLITE_TRANSIENT ){
   54892     int nAlloc = nByte;
   54893     if( flags&MEM_Term ){
   54894       nAlloc += (enc==SQLITE_UTF8?1:2);
   54895     }
   54896     if( nByte>iLimit ){
   54897       return SQLITE_TOOBIG;
   54898     }
   54899     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
   54900       return SQLITE_NOMEM;
   54901     }
   54902     memcpy(pMem->z, z, nAlloc);
   54903   }else if( xDel==SQLITE_DYNAMIC ){
   54904     sqlite3VdbeMemRelease(pMem);
   54905     pMem->zMalloc = pMem->z = (char *)z;
   54906     pMem->xDel = 0;
   54907   }else{
   54908     sqlite3VdbeMemRelease(pMem);
   54909     pMem->z = (char *)z;
   54910     pMem->xDel = xDel;
   54911     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
   54912   }
   54913 
   54914   pMem->n = nByte;
   54915   pMem->flags = flags;
   54916   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
   54917   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
   54918 
   54919 #ifndef SQLITE_OMIT_UTF16
   54920   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
   54921     return SQLITE_NOMEM;
   54922   }
   54923 #endif
   54924 
   54925   if( nByte>iLimit ){
   54926     return SQLITE_TOOBIG;
   54927   }
   54928 
   54929   return SQLITE_OK;
   54930 }
   54931 
   54932 /*
   54933 ** Compare the values contained by the two memory cells, returning
   54934 ** negative, zero or positive if pMem1 is less than, equal to, or greater
   54935 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   54936 ** and reals) sorted numerically, followed by text ordered by the collating
   54937 ** sequence pColl and finally blob's ordered by memcmp().
   54938 **
   54939 ** Two NULL values are considered equal by this function.
   54940 */
   54941 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   54942   int rc;
   54943   int f1, f2;
   54944   int combined_flags;
   54945 
   54946   f1 = pMem1->flags;
   54947   f2 = pMem2->flags;
   54948   combined_flags = f1|f2;
   54949   assert( (combined_flags & MEM_RowSet)==0 );
   54950 
   54951   /* If one value is NULL, it is less than the other. If both values
   54952   ** are NULL, return 0.
   54953   */
   54954   if( combined_flags&MEM_Null ){
   54955     return (f2&MEM_Null) - (f1&MEM_Null);
   54956   }
   54957 
   54958   /* If one value is a number and the other is not, the number is less.
   54959   ** If both are numbers, compare as reals if one is a real, or as integers
   54960   ** if both values are integers.
   54961   */
   54962   if( combined_flags&(MEM_Int|MEM_Real) ){
   54963     if( !(f1&(MEM_Int|MEM_Real)) ){
   54964       return 1;
   54965     }
   54966     if( !(f2&(MEM_Int|MEM_Real)) ){
   54967       return -1;
   54968     }
   54969     if( (f1 & f2 & MEM_Int)==0 ){
   54970       double r1, r2;
   54971       if( (f1&MEM_Real)==0 ){
   54972         r1 = (double)pMem1->u.i;
   54973       }else{
   54974         r1 = pMem1->r;
   54975       }
   54976       if( (f2&MEM_Real)==0 ){
   54977         r2 = (double)pMem2->u.i;
   54978       }else{
   54979         r2 = pMem2->r;
   54980       }
   54981       if( r1<r2 ) return -1;
   54982       if( r1>r2 ) return 1;
   54983       return 0;
   54984     }else{
   54985       assert( f1&MEM_Int );
   54986       assert( f2&MEM_Int );
   54987       if( pMem1->u.i < pMem2->u.i ) return -1;
   54988       if( pMem1->u.i > pMem2->u.i ) return 1;
   54989       return 0;
   54990     }
   54991   }
   54992 
   54993   /* If one value is a string and the other is a blob, the string is less.
   54994   ** If both are strings, compare using the collating functions.
   54995   */
   54996   if( combined_flags&MEM_Str ){
   54997     if( (f1 & MEM_Str)==0 ){
   54998       return 1;
   54999     }
   55000     if( (f2 & MEM_Str)==0 ){
   55001       return -1;
   55002     }
   55003 
   55004     assert( pMem1->enc==pMem2->enc );
   55005     assert( pMem1->enc==SQLITE_UTF8 ||
   55006             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   55007 
   55008     /* The collation sequence must be defined at this point, even if
   55009     ** the user deletes the collation sequence after the vdbe program is
   55010     ** compiled (this was not always the case).
   55011     */
   55012     assert( !pColl || pColl->xCmp );
   55013 
   55014     if( pColl ){
   55015       if( pMem1->enc==pColl->enc ){
   55016         /* The strings are already in the correct encoding.  Call the
   55017         ** comparison function directly */
   55018         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   55019       }else{
   55020         const void *v1, *v2;
   55021         int n1, n2;
   55022         Mem c1;
   55023         Mem c2;
   55024         memset(&c1, 0, sizeof(c1));
   55025         memset(&c2, 0, sizeof(c2));
   55026         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   55027         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   55028         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   55029         n1 = v1==0 ? 0 : c1.n;
   55030         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   55031         n2 = v2==0 ? 0 : c2.n;
   55032         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   55033         sqlite3VdbeMemRelease(&c1);
   55034         sqlite3VdbeMemRelease(&c2);
   55035         return rc;
   55036       }
   55037     }
   55038     /* If a NULL pointer was passed as the collate function, fall through
   55039     ** to the blob case and use memcmp().  */
   55040   }
   55041 
   55042   /* Both values must be blobs.  Compare using memcmp().  */
   55043   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   55044   if( rc==0 ){
   55045     rc = pMem1->n - pMem2->n;
   55046   }
   55047   return rc;
   55048 }
   55049 
   55050 /*
   55051 ** Move data out of a btree key or data field and into a Mem structure.
   55052 ** The data or key is taken from the entry that pCur is currently pointing
   55053 ** to.  offset and amt determine what portion of the data or key to retrieve.
   55054 ** key is true to get the key or false to get data.  The result is written
   55055 ** into the pMem element.
   55056 **
   55057 ** The pMem structure is assumed to be uninitialized.  Any prior content
   55058 ** is overwritten without being freed.
   55059 **
   55060 ** If this routine fails for any reason (malloc returns NULL or unable
   55061 ** to read from the disk) then the pMem is left in an inconsistent state.
   55062 */
   55063 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   55064   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   55065   int offset,       /* Offset from the start of data to return bytes from. */
   55066   int amt,          /* Number of bytes to return. */
   55067   int key,          /* If true, retrieve from the btree key, not data. */
   55068   Mem *pMem         /* OUT: Return data in this Mem structure. */
   55069 ){
   55070   char *zData;        /* Data from the btree layer */
   55071   int available = 0;  /* Number of bytes available on the local btree page */
   55072   int rc = SQLITE_OK; /* Return code */
   55073 
   55074   assert( sqlite3BtreeCursorIsValid(pCur) );
   55075 
   55076   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   55077   ** that both the BtShared and database handle mutexes are held. */
   55078   assert( (pMem->flags & MEM_RowSet)==0 );
   55079   if( key ){
   55080     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
   55081   }else{
   55082     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
   55083   }
   55084   assert( zData!=0 );
   55085 
   55086   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
   55087     sqlite3VdbeMemRelease(pMem);
   55088     pMem->z = &zData[offset];
   55089     pMem->flags = MEM_Blob|MEM_Ephem;
   55090   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   55091     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
   55092     pMem->enc = 0;
   55093     pMem->type = SQLITE_BLOB;
   55094     if( key ){
   55095       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   55096     }else{
   55097       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   55098     }
   55099     pMem->z[amt] = 0;
   55100     pMem->z[amt+1] = 0;
   55101     if( rc!=SQLITE_OK ){
   55102       sqlite3VdbeMemRelease(pMem);
   55103     }
   55104   }
   55105   pMem->n = amt;
   55106 
   55107   return rc;
   55108 }
   55109 
   55110 /* This function is only available internally, it is not part of the
   55111 ** external API. It works in a similar way to sqlite3_value_text(),
   55112 ** except the data returned is in the encoding specified by the second
   55113 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
   55114 ** SQLITE_UTF8.
   55115 **
   55116 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
   55117 ** If that is the case, then the result must be aligned on an even byte
   55118 ** boundary.
   55119 */
   55120 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
   55121   if( !pVal ) return 0;
   55122 
   55123   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
   55124   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
   55125   assert( (pVal->flags & MEM_RowSet)==0 );
   55126 
   55127   if( pVal->flags&MEM_Null ){
   55128     return 0;
   55129   }
   55130   assert( (MEM_Blob>>3) == MEM_Str );
   55131   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
   55132   expandBlob(pVal);
   55133   if( pVal->flags&MEM_Str ){
   55134     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
   55135     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
   55136       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
   55137       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
   55138         return 0;
   55139       }
   55140     }
   55141     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
   55142   }else{
   55143     assert( (pVal->flags&MEM_Blob)==0 );
   55144     sqlite3VdbeMemStringify(pVal, enc);
   55145     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
   55146   }
   55147   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
   55148               || pVal->db->mallocFailed );
   55149   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
   55150     return pVal->z;
   55151   }else{
   55152     return 0;
   55153   }
   55154 }
   55155 
   55156 /*
   55157 ** Create a new sqlite3_value object.
   55158 */
   55159 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
   55160   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
   55161   if( p ){
   55162     p->flags = MEM_Null;
   55163     p->type = SQLITE_NULL;
   55164     p->db = db;
   55165   }
   55166   return p;
   55167 }
   55168 
   55169 /*
   55170 ** Create a new sqlite3_value object, containing the value of pExpr.
   55171 **
   55172 ** This only works for very simple expressions that consist of one constant
   55173 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
   55174 ** be converted directly into a value, then the value is allocated and
   55175 ** a pointer written to *ppVal. The caller is responsible for deallocating
   55176 ** the value by passing it to sqlite3ValueFree() later on. If the expression
   55177 ** cannot be converted to a value, then *ppVal is set to NULL.
   55178 */
   55179 SQLITE_PRIVATE int sqlite3ValueFromExpr(
   55180   sqlite3 *db,              /* The database connection */
   55181   Expr *pExpr,              /* The expression to evaluate */
   55182   u8 enc,                   /* Encoding to use */
   55183   u8 affinity,              /* Affinity to use */
   55184   sqlite3_value **ppVal     /* Write the new value here */
   55185 ){
   55186   int op;
   55187   char *zVal = 0;
   55188   sqlite3_value *pVal = 0;
   55189   int negInt = 1;
   55190   const char *zNeg = "";
   55191 
   55192   if( !pExpr ){
   55193     *ppVal = 0;
   55194     return SQLITE_OK;
   55195   }
   55196   op = pExpr->op;
   55197 
   55198   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
   55199   ** The ifdef here is to enable us to achieve 100% branch test coverage even
   55200   ** when SQLITE_ENABLE_STAT2 is omitted.
   55201   */
   55202 #ifdef SQLITE_ENABLE_STAT2
   55203   if( op==TK_REGISTER ) op = pExpr->op2;
   55204 #else
   55205   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
   55206 #endif
   55207 
   55208   /* Handle negative integers in a single step.  This is needed in the
   55209   ** case when the value is -9223372036854775808.
   55210   */
   55211   if( op==TK_UMINUS
   55212    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
   55213     pExpr = pExpr->pLeft;
   55214     op = pExpr->op;
   55215     negInt = -1;
   55216     zNeg = "-";
   55217   }
   55218 
   55219   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
   55220     pVal = sqlite3ValueNew(db);
   55221     if( pVal==0 ) goto no_mem;
   55222     if( ExprHasProperty(pExpr, EP_IntValue) ){
   55223       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
   55224     }else{
   55225       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
   55226       if( zVal==0 ) goto no_mem;
   55227       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
   55228       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
   55229     }
   55230     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
   55231       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
   55232     }else{
   55233       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
   55234     }
   55235     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
   55236     if( enc!=SQLITE_UTF8 ){
   55237       sqlite3VdbeChangeEncoding(pVal, enc);
   55238     }
   55239   }else if( op==TK_UMINUS ) {
   55240     /* This branch happens for multiple negative signs.  Ex: -(-5) */
   55241     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
   55242       sqlite3VdbeMemNumerify(pVal);
   55243       pVal->u.i = -1 * pVal->u.i;
   55244       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
   55245       pVal->r = (double)-1 * pVal->r;
   55246       sqlite3ValueApplyAffinity(pVal, affinity, enc);
   55247     }
   55248   }
   55249 #ifndef SQLITE_OMIT_BLOB_LITERAL
   55250   else if( op==TK_BLOB ){
   55251     int nVal;
   55252     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   55253     assert( pExpr->u.zToken[1]=='\'' );
   55254     pVal = sqlite3ValueNew(db);
   55255     if( !pVal ) goto no_mem;
   55256     zVal = &pExpr->u.zToken[2];
   55257     nVal = sqlite3Strlen30(zVal)-1;
   55258     assert( zVal[nVal]=='\'' );
   55259     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
   55260                          0, SQLITE_DYNAMIC);
   55261   }
   55262 #endif
   55263 
   55264   if( pVal ){
   55265     sqlite3VdbeMemStoreType(pVal);
   55266   }
   55267   *ppVal = pVal;
   55268   return SQLITE_OK;
   55269 
   55270 no_mem:
   55271   db->mallocFailed = 1;
   55272   sqlite3DbFree(db, zVal);
   55273   sqlite3ValueFree(pVal);
   55274   *ppVal = 0;
   55275   return SQLITE_NOMEM;
   55276 }
   55277 
   55278 /*
   55279 ** Change the string value of an sqlite3_value object
   55280 */
   55281 SQLITE_PRIVATE void sqlite3ValueSetStr(
   55282   sqlite3_value *v,     /* Value to be set */
   55283   int n,                /* Length of string z */
   55284   const void *z,        /* Text of the new string */
   55285   u8 enc,               /* Encoding to use */
   55286   void (*xDel)(void*)   /* Destructor for the string */
   55287 ){
   55288   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
   55289 }
   55290 
   55291 /*
   55292 ** Free an sqlite3_value object
   55293 */
   55294 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
   55295   if( !v ) return;
   55296   sqlite3VdbeMemRelease((Mem *)v);
   55297   sqlite3DbFree(((Mem*)v)->db, v);
   55298 }
   55299 
   55300 /*
   55301 ** Return the number of bytes in the sqlite3_value object assuming
   55302 ** that it uses the encoding "enc"
   55303 */
   55304 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
   55305   Mem *p = (Mem*)pVal;
   55306   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
   55307     if( p->flags & MEM_Zero ){
   55308       return p->n + p->u.nZero;
   55309     }else{
   55310       return p->n;
   55311     }
   55312   }
   55313   return 0;
   55314 }
   55315 
   55316 /************** End of vdbemem.c *********************************************/
   55317 /************** Begin file vdbeaux.c *****************************************/
   55318 /*
   55319 ** 2003 September 6
   55320 **
   55321 ** The author disclaims copyright to this source code.  In place of
   55322 ** a legal notice, here is a blessing:
   55323 **
   55324 **    May you do good and not evil.
   55325 **    May you find forgiveness for yourself and forgive others.
   55326 **    May you share freely, never taking more than you give.
   55327 **
   55328 *************************************************************************
   55329 ** This file contains code used for creating, destroying, and populating
   55330 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
   55331 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
   55332 ** But that file was getting too big so this subroutines were split out.
   55333 */
   55334 
   55335 
   55336 
   55337 /*
   55338 ** When debugging the code generator in a symbolic debugger, one can
   55339 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
   55340 ** as they are added to the instruction stream.
   55341 */
   55342 #ifdef SQLITE_DEBUG
   55343 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
   55344 #endif
   55345 
   55346 
   55347 /*
   55348 ** Create a new virtual database engine.
   55349 */
   55350 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
   55351   Vdbe *p;
   55352   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
   55353   if( p==0 ) return 0;
   55354   p->db = db;
   55355   if( db->pVdbe ){
   55356     db->pVdbe->pPrev = p;
   55357   }
   55358   p->pNext = db->pVdbe;
   55359   p->pPrev = 0;
   55360   db->pVdbe = p;
   55361   p->magic = VDBE_MAGIC_INIT;
   55362   return p;
   55363 }
   55364 
   55365 /*
   55366 ** Remember the SQL string for a prepared statement.
   55367 */
   55368 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
   55369   assert( isPrepareV2==1 || isPrepareV2==0 );
   55370   if( p==0 ) return;
   55371 #ifdef SQLITE_OMIT_TRACE
   55372   if( !isPrepareV2 ) return;
   55373 #endif
   55374   assert( p->zSql==0 );
   55375   p->zSql = sqlite3DbStrNDup(p->db, z, n);
   55376   p->isPrepareV2 = (u8)isPrepareV2;
   55377 }
   55378 
   55379 /*
   55380 ** Return the SQL associated with a prepared statement
   55381 */
   55382 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
   55383   Vdbe *p = (Vdbe *)pStmt;
   55384   return (p && p->isPrepareV2) ? p->zSql : 0;
   55385 }
   55386 
   55387 /*
   55388 ** Swap all content between two VDBE structures.
   55389 */
   55390 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   55391   Vdbe tmp, *pTmp;
   55392   char *zTmp;
   55393   tmp = *pA;
   55394   *pA = *pB;
   55395   *pB = tmp;
   55396   pTmp = pA->pNext;
   55397   pA->pNext = pB->pNext;
   55398   pB->pNext = pTmp;
   55399   pTmp = pA->pPrev;
   55400   pA->pPrev = pB->pPrev;
   55401   pB->pPrev = pTmp;
   55402   zTmp = pA->zSql;
   55403   pA->zSql = pB->zSql;
   55404   pB->zSql = zTmp;
   55405   pB->isPrepareV2 = pA->isPrepareV2;
   55406 }
   55407 
   55408 #ifdef SQLITE_DEBUG
   55409 /*
   55410 ** Turn tracing on or off
   55411 */
   55412 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
   55413   p->trace = trace;
   55414 }
   55415 #endif
   55416 
   55417 /*
   55418 ** Resize the Vdbe.aOp array so that it is at least one op larger than
   55419 ** it was.
   55420 **
   55421 ** If an out-of-memory error occurs while resizing the array, return
   55422 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
   55423 ** unchanged (this is so that any opcodes already allocated can be
   55424 ** correctly deallocated along with the rest of the Vdbe).
   55425 */
   55426 static int growOpArray(Vdbe *p){
   55427   VdbeOp *pNew;
   55428   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
   55429   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
   55430   if( pNew ){
   55431     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
   55432     p->aOp = pNew;
   55433   }
   55434   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
   55435 }
   55436 
   55437 /*
   55438 ** Add a new instruction to the list of instructions current in the
   55439 ** VDBE.  Return the address of the new instruction.
   55440 **
   55441 ** Parameters:
   55442 **
   55443 **    p               Pointer to the VDBE
   55444 **
   55445 **    op              The opcode for this instruction
   55446 **
   55447 **    p1, p2, p3      Operands
   55448 **
   55449 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
   55450 ** the sqlite3VdbeChangeP4() function to change the value of the P4
   55451 ** operand.
   55452 */
   55453 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
   55454   int i;
   55455   VdbeOp *pOp;
   55456 
   55457   i = p->nOp;
   55458   assert( p->magic==VDBE_MAGIC_INIT );
   55459   assert( op>0 && op<0xff );
   55460   if( p->nOpAlloc<=i ){
   55461     if( growOpArray(p) ){
   55462       return 1;
   55463     }
   55464   }
   55465   p->nOp++;
   55466   pOp = &p->aOp[i];
   55467   pOp->opcode = (u8)op;
   55468   pOp->p5 = 0;
   55469   pOp->p1 = p1;
   55470   pOp->p2 = p2;
   55471   pOp->p3 = p3;
   55472   pOp->p4.p = 0;
   55473   pOp->p4type = P4_NOTUSED;
   55474   p->expired = 0;
   55475 #ifdef SQLITE_DEBUG
   55476   pOp->zComment = 0;
   55477   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
   55478 #endif
   55479 #ifdef VDBE_PROFILE
   55480   pOp->cycles = 0;
   55481   pOp->cnt = 0;
   55482 #endif
   55483   return i;
   55484 }
   55485 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
   55486   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   55487 }
   55488 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   55489   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
   55490 }
   55491 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
   55492   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
   55493 }
   55494 
   55495 
   55496 /*
   55497 ** Add an opcode that includes the p4 value as a pointer.
   55498 */
   55499 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
   55500   Vdbe *p,            /* Add the opcode to this VM */
   55501   int op,             /* The new opcode */
   55502   int p1,             /* The P1 operand */
   55503   int p2,             /* The P2 operand */
   55504   int p3,             /* The P3 operand */
   55505   const char *zP4,    /* The P4 operand */
   55506   int p4type          /* P4 operand type */
   55507 ){
   55508   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   55509   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
   55510   return addr;
   55511 }
   55512 
   55513 /*
   55514 ** Add an opcode that includes the p4 value as an integer.
   55515 */
   55516 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
   55517   Vdbe *p,            /* Add the opcode to this VM */
   55518   int op,             /* The new opcode */
   55519   int p1,             /* The P1 operand */
   55520   int p2,             /* The P2 operand */
   55521   int p3,             /* The P3 operand */
   55522   int p4              /* The P4 operand as an integer */
   55523 ){
   55524   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
   55525   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
   55526   return addr;
   55527 }
   55528 
   55529 /*
   55530 ** Create a new symbolic label for an instruction that has yet to be
   55531 ** coded.  The symbolic label is really just a negative number.  The
   55532 ** label can be used as the P2 value of an operation.  Later, when
   55533 ** the label is resolved to a specific address, the VDBE will scan
   55534 ** through its operation list and change all values of P2 which match
   55535 ** the label into the resolved address.
   55536 **
   55537 ** The VDBE knows that a P2 value is a label because labels are
   55538 ** always negative and P2 values are suppose to be non-negative.
   55539 ** Hence, a negative P2 value is a label that has yet to be resolved.
   55540 **
   55541 ** Zero is returned if a malloc() fails.
   55542 */
   55543 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
   55544   int i;
   55545   i = p->nLabel++;
   55546   assert( p->magic==VDBE_MAGIC_INIT );
   55547   if( i>=p->nLabelAlloc ){
   55548     int n = p->nLabelAlloc*2 + 5;
   55549     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
   55550                                        n*sizeof(p->aLabel[0]));
   55551     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
   55552   }
   55553   if( p->aLabel ){
   55554     p->aLabel[i] = -1;
   55555   }
   55556   return -1-i;
   55557 }
   55558 
   55559 /*
   55560 ** Resolve label "x" to be the address of the next instruction to
   55561 ** be inserted.  The parameter "x" must have been obtained from
   55562 ** a prior call to sqlite3VdbeMakeLabel().
   55563 */
   55564 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   55565   int j = -1-x;
   55566   assert( p->magic==VDBE_MAGIC_INIT );
   55567   assert( j>=0 && j<p->nLabel );
   55568   if( p->aLabel ){
   55569     p->aLabel[j] = p->nOp;
   55570   }
   55571 }
   55572 
   55573 /*
   55574 ** Mark the VDBE as one that can only be run one time.
   55575 */
   55576 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
   55577   p->runOnlyOnce = 1;
   55578 }
   55579 
   55580 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
   55581 
   55582 /*
   55583 ** The following type and function are used to iterate through all opcodes
   55584 ** in a Vdbe main program and each of the sub-programs (triggers) it may
   55585 ** invoke directly or indirectly. It should be used as follows:
   55586 **
   55587 **   Op *pOp;
   55588 **   VdbeOpIter sIter;
   55589 **
   55590 **   memset(&sIter, 0, sizeof(sIter));
   55591 **   sIter.v = v;                            // v is of type Vdbe*
   55592 **   while( (pOp = opIterNext(&sIter)) ){
   55593 **     // Do something with pOp
   55594 **   }
   55595 **   sqlite3DbFree(v->db, sIter.apSub);
   55596 **
   55597 */
   55598 typedef struct VdbeOpIter VdbeOpIter;
   55599 struct VdbeOpIter {
   55600   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
   55601   SubProgram **apSub;        /* Array of subprograms */
   55602   int nSub;                  /* Number of entries in apSub */
   55603   int iAddr;                 /* Address of next instruction to return */
   55604   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
   55605 };
   55606 static Op *opIterNext(VdbeOpIter *p){
   55607   Vdbe *v = p->v;
   55608   Op *pRet = 0;
   55609   Op *aOp;
   55610   int nOp;
   55611 
   55612   if( p->iSub<=p->nSub ){
   55613 
   55614     if( p->iSub==0 ){
   55615       aOp = v->aOp;
   55616       nOp = v->nOp;
   55617     }else{
   55618       aOp = p->apSub[p->iSub-1]->aOp;
   55619       nOp = p->apSub[p->iSub-1]->nOp;
   55620     }
   55621     assert( p->iAddr<nOp );
   55622 
   55623     pRet = &aOp[p->iAddr];
   55624     p->iAddr++;
   55625     if( p->iAddr==nOp ){
   55626       p->iSub++;
   55627       p->iAddr = 0;
   55628     }
   55629 
   55630     if( pRet->p4type==P4_SUBPROGRAM ){
   55631       int nByte = (p->nSub+1)*sizeof(SubProgram*);
   55632       int j;
   55633       for(j=0; j<p->nSub; j++){
   55634         if( p->apSub[j]==pRet->p4.pProgram ) break;
   55635       }
   55636       if( j==p->nSub ){
   55637         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
   55638         if( !p->apSub ){
   55639           pRet = 0;
   55640         }else{
   55641           p->apSub[p->nSub++] = pRet->p4.pProgram;
   55642         }
   55643       }
   55644     }
   55645   }
   55646 
   55647   return pRet;
   55648 }
   55649 
   55650 /*
   55651 ** Check if the program stored in the VM associated with pParse may
   55652 ** throw an ABORT exception (causing the statement, but not entire transaction
   55653 ** to be rolled back). This condition is true if the main program or any
   55654 ** sub-programs contains any of the following:
   55655 **
   55656 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   55657 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
   55658 **   *  OP_Destroy
   55659 **   *  OP_VUpdate
   55660 **   *  OP_VRename
   55661 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
   55662 **
   55663 ** Then check that the value of Parse.mayAbort is true if an
   55664 ** ABORT may be thrown, or false otherwise. Return true if it does
   55665 ** match, or false otherwise. This function is intended to be used as
   55666 ** part of an assert statement in the compiler. Similar to:
   55667 **
   55668 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
   55669 */
   55670 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
   55671   int hasAbort = 0;
   55672   Op *pOp;
   55673   VdbeOpIter sIter;
   55674   memset(&sIter, 0, sizeof(sIter));
   55675   sIter.v = v;
   55676 
   55677   while( (pOp = opIterNext(&sIter))!=0 ){
   55678     int opcode = pOp->opcode;
   55679     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
   55680 #ifndef SQLITE_OMIT_FOREIGN_KEY
   55681      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
   55682 #endif
   55683      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
   55684       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
   55685     ){
   55686       hasAbort = 1;
   55687       break;
   55688     }
   55689   }
   55690   sqlite3DbFree(v->db, sIter.apSub);
   55691 
   55692   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
   55693   ** If malloc failed, then the while() loop above may not have iterated
   55694   ** through all opcodes and hasAbort may be set incorrectly. Return
   55695   ** true for this case to prevent the assert() in the callers frame
   55696   ** from failing.  */
   55697   return ( v->db->mallocFailed || hasAbort==mayAbort );
   55698 }
   55699 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
   55700 
   55701 /*
   55702 ** Loop through the program looking for P2 values that are negative
   55703 ** on jump instructions.  Each such value is a label.  Resolve the
   55704 ** label by setting the P2 value to its correct non-zero value.
   55705 **
   55706 ** This routine is called once after all opcodes have been inserted.
   55707 **
   55708 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
   55709 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
   55710 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
   55711 **
   55712 ** The Op.opflags field is set on all opcodes.
   55713 */
   55714 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
   55715   int i;
   55716   int nMaxArgs = *pMaxFuncArgs;
   55717   Op *pOp;
   55718   int *aLabel = p->aLabel;
   55719   p->readOnly = 1;
   55720   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   55721     u8 opcode = pOp->opcode;
   55722 
   55723     pOp->opflags = sqlite3OpcodeProperty[opcode];
   55724     if( opcode==OP_Function || opcode==OP_AggStep ){
   55725       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   55726     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
   55727       p->readOnly = 0;
   55728 #ifndef SQLITE_OMIT_VIRTUALTABLE
   55729     }else if( opcode==OP_VUpdate ){
   55730       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   55731     }else if( opcode==OP_VFilter ){
   55732       int n;
   55733       assert( p->nOp - i >= 3 );
   55734       assert( pOp[-1].opcode==OP_Integer );
   55735       n = pOp[-1].p1;
   55736       if( n>nMaxArgs ) nMaxArgs = n;
   55737 #endif
   55738     }
   55739 
   55740     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   55741       assert( -1-pOp->p2<p->nLabel );
   55742       pOp->p2 = aLabel[-1-pOp->p2];
   55743     }
   55744   }
   55745   sqlite3DbFree(p->db, p->aLabel);
   55746   p->aLabel = 0;
   55747 
   55748   *pMaxFuncArgs = nMaxArgs;
   55749 }
   55750 
   55751 /*
   55752 ** Return the address of the next instruction to be inserted.
   55753 */
   55754 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
   55755   assert( p->magic==VDBE_MAGIC_INIT );
   55756   return p->nOp;
   55757 }
   55758 
   55759 /*
   55760 ** This function returns a pointer to the array of opcodes associated with
   55761 ** the Vdbe passed as the first argument. It is the callers responsibility
   55762 ** to arrange for the returned array to be eventually freed using the
   55763 ** vdbeFreeOpArray() function.
   55764 **
   55765 ** Before returning, *pnOp is set to the number of entries in the returned
   55766 ** array. Also, *pnMaxArg is set to the larger of its current value and
   55767 ** the number of entries in the Vdbe.apArg[] array required to execute the
   55768 ** returned program.
   55769 */
   55770 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
   55771   VdbeOp *aOp = p->aOp;
   55772   assert( aOp && !p->db->mallocFailed );
   55773 
   55774   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
   55775   assert( p->aMutex.nMutex==0 );
   55776 
   55777   resolveP2Values(p, pnMaxArg);
   55778   *pnOp = p->nOp;
   55779   p->aOp = 0;
   55780   return aOp;
   55781 }
   55782 
   55783 /*
   55784 ** Add a whole list of operations to the operation stack.  Return the
   55785 ** address of the first operation added.
   55786 */
   55787 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
   55788   int addr;
   55789   assert( p->magic==VDBE_MAGIC_INIT );
   55790   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
   55791     return 0;
   55792   }
   55793   addr = p->nOp;
   55794   if( ALWAYS(nOp>0) ){
   55795     int i;
   55796     VdbeOpList const *pIn = aOp;
   55797     for(i=0; i<nOp; i++, pIn++){
   55798       int p2 = pIn->p2;
   55799       VdbeOp *pOut = &p->aOp[i+addr];
   55800       pOut->opcode = pIn->opcode;
   55801       pOut->p1 = pIn->p1;
   55802       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
   55803         pOut->p2 = addr + ADDR(p2);
   55804       }else{
   55805         pOut->p2 = p2;
   55806       }
   55807       pOut->p3 = pIn->p3;
   55808       pOut->p4type = P4_NOTUSED;
   55809       pOut->p4.p = 0;
   55810       pOut->p5 = 0;
   55811 #ifdef SQLITE_DEBUG
   55812       pOut->zComment = 0;
   55813       if( sqlite3VdbeAddopTrace ){
   55814         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   55815       }
   55816 #endif
   55817     }
   55818     p->nOp += nOp;
   55819   }
   55820   return addr;
   55821 }
   55822 
   55823 /*
   55824 ** Change the value of the P1 operand for a specific instruction.
   55825 ** This routine is useful when a large program is loaded from a
   55826 ** static array using sqlite3VdbeAddOpList but we want to make a
   55827 ** few minor changes to the program.
   55828 */
   55829 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
   55830   assert( p!=0 );
   55831   assert( addr>=0 );
   55832   if( p->nOp>addr ){
   55833     p->aOp[addr].p1 = val;
   55834   }
   55835 }
   55836 
   55837 /*
   55838 ** Change the value of the P2 operand for a specific instruction.
   55839 ** This routine is useful for setting a jump destination.
   55840 */
   55841 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
   55842   assert( p!=0 );
   55843   assert( addr>=0 );
   55844   if( p->nOp>addr ){
   55845     p->aOp[addr].p2 = val;
   55846   }
   55847 }
   55848 
   55849 /*
   55850 ** Change the value of the P3 operand for a specific instruction.
   55851 */
   55852 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
   55853   assert( p!=0 );
   55854   assert( addr>=0 );
   55855   if( p->nOp>addr ){
   55856     p->aOp[addr].p3 = val;
   55857   }
   55858 }
   55859 
   55860 /*
   55861 ** Change the value of the P5 operand for the most recently
   55862 ** added operation.
   55863 */
   55864 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
   55865   assert( p!=0 );
   55866   if( p->aOp ){
   55867     assert( p->nOp>0 );
   55868     p->aOp[p->nOp-1].p5 = val;
   55869   }
   55870 }
   55871 
   55872 /*
   55873 ** Change the P2 operand of instruction addr so that it points to
   55874 ** the address of the next instruction to be coded.
   55875 */
   55876 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   55877   sqlite3VdbeChangeP2(p, addr, p->nOp);
   55878 }
   55879 
   55880 
   55881 /*
   55882 ** If the input FuncDef structure is ephemeral, then free it.  If
   55883 ** the FuncDef is not ephermal, then do nothing.
   55884 */
   55885 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   55886   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
   55887     sqlite3DbFree(db, pDef);
   55888   }
   55889 }
   55890 
   55891 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
   55892 
   55893 /*
   55894 ** Delete a P4 value if necessary.
   55895 */
   55896 static void freeP4(sqlite3 *db, int p4type, void *p4){
   55897   if( p4 ){
   55898     assert( db );
   55899     switch( p4type ){
   55900       case P4_REAL:
   55901       case P4_INT64:
   55902       case P4_DYNAMIC:
   55903       case P4_KEYINFO:
   55904       case P4_INTARRAY:
   55905       case P4_KEYINFO_HANDOFF: {
   55906         sqlite3DbFree(db, p4);
   55907         break;
   55908       }
   55909       case P4_MPRINTF: {
   55910         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
   55911         break;
   55912       }
   55913       case P4_VDBEFUNC: {
   55914         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
   55915         freeEphemeralFunction(db, pVdbeFunc->pFunc);
   55916         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
   55917         sqlite3DbFree(db, pVdbeFunc);
   55918         break;
   55919       }
   55920       case P4_FUNCDEF: {
   55921         freeEphemeralFunction(db, (FuncDef*)p4);
   55922         break;
   55923       }
   55924       case P4_MEM: {
   55925         if( db->pnBytesFreed==0 ){
   55926           sqlite3ValueFree((sqlite3_value*)p4);
   55927         }else{
   55928           Mem *p = (Mem*)p4;
   55929           sqlite3DbFree(db, p->zMalloc);
   55930           sqlite3DbFree(db, p);
   55931         }
   55932         break;
   55933       }
   55934       case P4_VTAB : {
   55935         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
   55936         break;
   55937       }
   55938     }
   55939   }
   55940 }
   55941 
   55942 /*
   55943 ** Free the space allocated for aOp and any p4 values allocated for the
   55944 ** opcodes contained within. If aOp is not NULL it is assumed to contain
   55945 ** nOp entries.
   55946 */
   55947 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   55948   if( aOp ){
   55949     Op *pOp;
   55950     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
   55951       freeP4(db, pOp->p4type, pOp->p4.p);
   55952 #ifdef SQLITE_DEBUG
   55953       sqlite3DbFree(db, pOp->zComment);
   55954 #endif
   55955     }
   55956   }
   55957   sqlite3DbFree(db, aOp);
   55958 }
   55959 
   55960 /*
   55961 ** Link the SubProgram object passed as the second argument into the linked
   55962 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
   55963 ** objects when the VM is no longer required.
   55964 */
   55965 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
   55966   p->pNext = pVdbe->pProgram;
   55967   pVdbe->pProgram = p;
   55968 }
   55969 
   55970 /*
   55971 ** Change N opcodes starting at addr to No-ops.
   55972 */
   55973 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
   55974   if( p->aOp ){
   55975     VdbeOp *pOp = &p->aOp[addr];
   55976     sqlite3 *db = p->db;
   55977     while( N-- ){
   55978       freeP4(db, pOp->p4type, pOp->p4.p);
   55979       memset(pOp, 0, sizeof(pOp[0]));
   55980       pOp->opcode = OP_Noop;
   55981       pOp++;
   55982     }
   55983   }
   55984 }
   55985 
   55986 /*
   55987 ** Change the value of the P4 operand for a specific instruction.
   55988 ** This routine is useful when a large program is loaded from a
   55989 ** static array using sqlite3VdbeAddOpList but we want to make a
   55990 ** few minor changes to the program.
   55991 **
   55992 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
   55993 ** the string is made into memory obtained from sqlite3_malloc().
   55994 ** A value of n==0 means copy bytes of zP4 up to and including the
   55995 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
   55996 **
   55997 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
   55998 ** A copy is made of the KeyInfo structure into memory obtained from
   55999 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
   56000 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
   56001 ** stored in memory that the caller has obtained from sqlite3_malloc. The
   56002 ** caller should not free the allocation, it will be freed when the Vdbe is
   56003 ** finalized.
   56004 **
   56005 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
   56006 ** to a string or structure that is guaranteed to exist for the lifetime of
   56007 ** the Vdbe. In these cases we can just copy the pointer.
   56008 **
   56009 ** If addr<0 then change P4 on the most recently inserted instruction.
   56010 */
   56011 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
   56012   Op *pOp;
   56013   sqlite3 *db;
   56014   assert( p!=0 );
   56015   db = p->db;
   56016   assert( p->magic==VDBE_MAGIC_INIT );
   56017   if( p->aOp==0 || db->mallocFailed ){
   56018     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
   56019       freeP4(db, n, (void*)*(char**)&zP4);
   56020     }
   56021     return;
   56022   }
   56023   assert( p->nOp>0 );
   56024   assert( addr<p->nOp );
   56025   if( addr<0 ){
   56026     addr = p->nOp - 1;
   56027   }
   56028   pOp = &p->aOp[addr];
   56029   freeP4(db, pOp->p4type, pOp->p4.p);
   56030   pOp->p4.p = 0;
   56031   if( n==P4_INT32 ){
   56032     /* Note: this cast is safe, because the origin data point was an int
   56033     ** that was cast to a (const char *). */
   56034     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   56035     pOp->p4type = P4_INT32;
   56036   }else if( zP4==0 ){
   56037     pOp->p4.p = 0;
   56038     pOp->p4type = P4_NOTUSED;
   56039   }else if( n==P4_KEYINFO ){
   56040     KeyInfo *pKeyInfo;
   56041     int nField, nByte;
   56042 
   56043     nField = ((KeyInfo*)zP4)->nField;
   56044     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   56045     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
   56046     pOp->p4.pKeyInfo = pKeyInfo;
   56047     if( pKeyInfo ){
   56048       u8 *aSortOrder;
   56049       memcpy((char*)pKeyInfo, zP4, nByte - nField);
   56050       aSortOrder = pKeyInfo->aSortOrder;
   56051       if( aSortOrder ){
   56052         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   56053         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
   56054       }
   56055       pOp->p4type = P4_KEYINFO;
   56056     }else{
   56057       p->db->mallocFailed = 1;
   56058       pOp->p4type = P4_NOTUSED;
   56059     }
   56060   }else if( n==P4_KEYINFO_HANDOFF ){
   56061     pOp->p4.p = (void*)zP4;
   56062     pOp->p4type = P4_KEYINFO;
   56063   }else if( n==P4_VTAB ){
   56064     pOp->p4.p = (void*)zP4;
   56065     pOp->p4type = P4_VTAB;
   56066     sqlite3VtabLock((VTable *)zP4);
   56067     assert( ((VTable *)zP4)->db==p->db );
   56068   }else if( n<0 ){
   56069     pOp->p4.p = (void*)zP4;
   56070     pOp->p4type = (signed char)n;
   56071   }else{
   56072     if( n==0 ) n = sqlite3Strlen30(zP4);
   56073     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
   56074     pOp->p4type = P4_DYNAMIC;
   56075   }
   56076 }
   56077 
   56078 #ifndef NDEBUG
   56079 /*
   56080 ** Change the comment on the the most recently coded instruction.  Or
   56081 ** insert a No-op and add the comment to that new instruction.  This
   56082 ** makes the code easier to read during debugging.  None of this happens
   56083 ** in a production build.
   56084 */
   56085 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
   56086   va_list ap;
   56087   if( !p ) return;
   56088   assert( p->nOp>0 || p->aOp==0 );
   56089   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   56090   if( p->nOp ){
   56091     char **pz = &p->aOp[p->nOp-1].zComment;
   56092     va_start(ap, zFormat);
   56093     sqlite3DbFree(p->db, *pz);
   56094     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
   56095     va_end(ap);
   56096   }
   56097 }
   56098 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
   56099   va_list ap;
   56100   if( !p ) return;
   56101   sqlite3VdbeAddOp0(p, OP_Noop);
   56102   assert( p->nOp>0 || p->aOp==0 );
   56103   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
   56104   if( p->nOp ){
   56105     char **pz = &p->aOp[p->nOp-1].zComment;
   56106     va_start(ap, zFormat);
   56107     sqlite3DbFree(p->db, *pz);
   56108     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
   56109     va_end(ap);
   56110   }
   56111 }
   56112 #endif  /* NDEBUG */
   56113 
   56114 /*
   56115 ** Return the opcode for a given address.  If the address is -1, then
   56116 ** return the most recently inserted opcode.
   56117 **
   56118 ** If a memory allocation error has occurred prior to the calling of this
   56119 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   56120 ** is readable but not writable, though it is cast to a writable value.
   56121 ** The return of a dummy opcode allows the call to continue functioning
   56122 ** after a OOM fault without having to check to see if the return from
   56123 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
   56124 ** dummy will never be written to.  This is verified by code inspection and
   56125 ** by running with Valgrind.
   56126 **
   56127 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
   56128 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
   56129 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
   56130 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
   56131 ** having to double-check to make sure that the result is non-negative. But
   56132 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
   56133 ** check the value of p->nOp-1 before continuing.
   56134 */
   56135 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
   56136   /* C89 specifies that the constant "dummy" will be initialized to all
   56137   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
   56138   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
   56139   assert( p->magic==VDBE_MAGIC_INIT );
   56140   if( addr<0 ){
   56141 #ifdef SQLITE_OMIT_TRACE
   56142     if( p->nOp==0 ) return (VdbeOp*)&dummy;
   56143 #endif
   56144     addr = p->nOp - 1;
   56145   }
   56146   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
   56147   if( p->db->mallocFailed ){
   56148     return (VdbeOp*)&dummy;
   56149   }else{
   56150     return &p->aOp[addr];
   56151   }
   56152 }
   56153 
   56154 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
   56155      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   56156 /*
   56157 ** Compute a string that describes the P4 parameter for an opcode.
   56158 ** Use zTemp for any required temporary buffer space.
   56159 */
   56160 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
   56161   char *zP4 = zTemp;
   56162   assert( nTemp>=20 );
   56163   switch( pOp->p4type ){
   56164     case P4_KEYINFO_STATIC:
   56165     case P4_KEYINFO: {
   56166       int i, j;
   56167       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
   56168       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
   56169       i = sqlite3Strlen30(zTemp);
   56170       for(j=0; j<pKeyInfo->nField; j++){
   56171         CollSeq *pColl = pKeyInfo->aColl[j];
   56172         if( pColl ){
   56173           int n = sqlite3Strlen30(pColl->zName);
   56174           if( i+n>nTemp-6 ){
   56175             memcpy(&zTemp[i],",...",4);
   56176             break;
   56177           }
   56178           zTemp[i++] = ',';
   56179           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
   56180             zTemp[i++] = '-';
   56181           }
   56182           memcpy(&zTemp[i], pColl->zName,n+1);
   56183           i += n;
   56184         }else if( i+4<nTemp-6 ){
   56185           memcpy(&zTemp[i],",nil",4);
   56186           i += 4;
   56187         }
   56188       }
   56189       zTemp[i++] = ')';
   56190       zTemp[i] = 0;
   56191       assert( i<nTemp );
   56192       break;
   56193     }
   56194     case P4_COLLSEQ: {
   56195       CollSeq *pColl = pOp->p4.pColl;
   56196       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
   56197       break;
   56198     }
   56199     case P4_FUNCDEF: {
   56200       FuncDef *pDef = pOp->p4.pFunc;
   56201       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
   56202       break;
   56203     }
   56204     case P4_INT64: {
   56205       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
   56206       break;
   56207     }
   56208     case P4_INT32: {
   56209       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
   56210       break;
   56211     }
   56212     case P4_REAL: {
   56213       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
   56214       break;
   56215     }
   56216     case P4_MEM: {
   56217       Mem *pMem = pOp->p4.pMem;
   56218       assert( (pMem->flags & MEM_Null)==0 );
   56219       if( pMem->flags & MEM_Str ){
   56220         zP4 = pMem->z;
   56221       }else if( pMem->flags & MEM_Int ){
   56222         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
   56223       }else if( pMem->flags & MEM_Real ){
   56224         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
   56225       }else{
   56226         assert( pMem->flags & MEM_Blob );
   56227         zP4 = "(blob)";
   56228       }
   56229       break;
   56230     }
   56231 #ifndef SQLITE_OMIT_VIRTUALTABLE
   56232     case P4_VTAB: {
   56233       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
   56234       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
   56235       break;
   56236     }
   56237 #endif
   56238     case P4_INTARRAY: {
   56239       sqlite3_snprintf(nTemp, zTemp, "intarray");
   56240       break;
   56241     }
   56242     case P4_SUBPROGRAM: {
   56243       sqlite3_snprintf(nTemp, zTemp, "program");
   56244       break;
   56245     }
   56246     default: {
   56247       zP4 = pOp->p4.z;
   56248       if( zP4==0 ){
   56249         zP4 = zTemp;
   56250         zTemp[0] = 0;
   56251       }
   56252     }
   56253   }
   56254   assert( zP4!=0 );
   56255   return zP4;
   56256 }
   56257 #endif
   56258 
   56259 /*
   56260 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
   56261 **
   56262 ** The prepared statement has to know in advance which Btree objects
   56263 ** will be used so that it can acquire mutexes on them all in sorted
   56264 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
   56265 ** in order (and released in reverse order) to avoid deadlocks.
   56266 */
   56267 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
   56268   int mask;
   56269   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
   56270   assert( i<(int)sizeof(p->btreeMask)*8 );
   56271   mask = ((u32)1)<<i;
   56272   if( (p->btreeMask & mask)==0 ){
   56273     p->btreeMask |= mask;
   56274     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
   56275   }
   56276 }
   56277 
   56278 
   56279 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
   56280 /*
   56281 ** Print a single opcode.  This routine is used for debugging only.
   56282 */
   56283 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
   56284   char *zP4;
   56285   char zPtr[50];
   56286   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
   56287   if( pOut==0 ) pOut = stdout;
   56288   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
   56289   fprintf(pOut, zFormat1, pc,
   56290       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
   56291 #ifdef SQLITE_DEBUG
   56292       pOp->zComment ? pOp->zComment : ""
   56293 #else
   56294       ""
   56295 #endif
   56296   );
   56297   fflush(pOut);
   56298 }
   56299 #endif
   56300 
   56301 /*
   56302 ** Release an array of N Mem elements
   56303 */
   56304 static void releaseMemArray(Mem *p, int N){
   56305   if( p && N ){
   56306     Mem *pEnd;
   56307     sqlite3 *db = p->db;
   56308     u8 malloc_failed = db->mallocFailed;
   56309     if( db->pnBytesFreed ){
   56310       for(pEnd=&p[N]; p<pEnd; p++){
   56311         sqlite3DbFree(db, p->zMalloc);
   56312       }
   56313       return;
   56314     }
   56315     for(pEnd=&p[N]; p<pEnd; p++){
   56316       assert( (&p[1])==pEnd || p[0].db==p[1].db );
   56317 
   56318       /* This block is really an inlined version of sqlite3VdbeMemRelease()
   56319       ** that takes advantage of the fact that the memory cell value is
   56320       ** being set to NULL after releasing any dynamic resources.
   56321       **
   56322       ** The justification for duplicating code is that according to
   56323       ** callgrind, this causes a certain test case to hit the CPU 4.7
   56324       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
   56325       ** sqlite3MemRelease() were called from here. With -O2, this jumps
   56326       ** to 6.6 percent. The test case is inserting 1000 rows into a table
   56327       ** with no indexes using a single prepared INSERT statement, bind()
   56328       ** and reset(). Inserts are grouped into a transaction.
   56329       */
   56330       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
   56331         sqlite3VdbeMemRelease(p);
   56332       }else if( p->zMalloc ){
   56333         sqlite3DbFree(db, p->zMalloc);
   56334         p->zMalloc = 0;
   56335       }
   56336 
   56337       p->flags = MEM_Null;
   56338     }
   56339     db->mallocFailed = malloc_failed;
   56340   }
   56341 }
   56342 
   56343 /*
   56344 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
   56345 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
   56346 */
   56347 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
   56348   int i;
   56349   Mem *aMem = VdbeFrameMem(p);
   56350   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
   56351   for(i=0; i<p->nChildCsr; i++){
   56352     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
   56353   }
   56354   releaseMemArray(aMem, p->nChildMem);
   56355   sqlite3DbFree(p->v->db, p);
   56356 }
   56357 
   56358 #ifndef SQLITE_OMIT_EXPLAIN
   56359 /*
   56360 ** Give a listing of the program in the virtual machine.
   56361 **
   56362 ** The interface is the same as sqlite3VdbeExec().  But instead of
   56363 ** running the code, it invokes the callback once for each instruction.
   56364 ** This feature is used to implement "EXPLAIN".
   56365 **
   56366 ** When p->explain==1, each instruction is listed.  When
   56367 ** p->explain==2, only OP_Explain instructions are listed and these
   56368 ** are shown in a different format.  p->explain==2 is used to implement
   56369 ** EXPLAIN QUERY PLAN.
   56370 **
   56371 ** When p->explain==1, first the main program is listed, then each of
   56372 ** the trigger subprograms are listed one by one.
   56373 */
   56374 SQLITE_PRIVATE int sqlite3VdbeList(
   56375   Vdbe *p                   /* The VDBE */
   56376 ){
   56377   int nRow;                            /* Stop when row count reaches this */
   56378   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   56379   SubProgram **apSub = 0;              /* Array of sub-vdbes */
   56380   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
   56381   sqlite3 *db = p->db;                 /* The database connection */
   56382   int i;                               /* Loop counter */
   56383   int rc = SQLITE_OK;                  /* Return code */
   56384   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
   56385 
   56386   assert( p->explain );
   56387   assert( p->magic==VDBE_MAGIC_RUN );
   56388   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
   56389 
   56390   /* Even though this opcode does not use dynamic strings for
   56391   ** the result, result columns may become dynamic if the user calls
   56392   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
   56393   */
   56394   releaseMemArray(pMem, 8);
   56395 
   56396   if( p->rc==SQLITE_NOMEM ){
   56397     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   56398     ** sqlite3_column_text16() failed.  */
   56399     db->mallocFailed = 1;
   56400     return SQLITE_ERROR;
   56401   }
   56402 
   56403   /* When the number of output rows reaches nRow, that means the
   56404   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
   56405   ** nRow is the sum of the number of rows in the main program, plus
   56406   ** the sum of the number of rows in all trigger subprograms encountered
   56407   ** so far.  The nRow value will increase as new trigger subprograms are
   56408   ** encountered, but p->pc will eventually catch up to nRow.
   56409   */
   56410   nRow = p->nOp;
   56411   if( p->explain==1 ){
   56412     /* The first 8 memory cells are used for the result set.  So we will
   56413     ** commandeer the 9th cell to use as storage for an array of pointers
   56414     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
   56415     ** cells.  */
   56416     assert( p->nMem>9 );
   56417     pSub = &p->aMem[9];
   56418     if( pSub->flags&MEM_Blob ){
   56419       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
   56420       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
   56421       nSub = pSub->n/sizeof(Vdbe*);
   56422       apSub = (SubProgram **)pSub->z;
   56423     }
   56424     for(i=0; i<nSub; i++){
   56425       nRow += apSub[i]->nOp;
   56426     }
   56427   }
   56428 
   56429   do{
   56430     i = p->pc++;
   56431   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
   56432   if( i>=nRow ){
   56433     p->rc = SQLITE_OK;
   56434     rc = SQLITE_DONE;
   56435   }else if( db->u1.isInterrupted ){
   56436     p->rc = SQLITE_INTERRUPT;
   56437     rc = SQLITE_ERROR;
   56438     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
   56439   }else{
   56440     char *z;
   56441     Op *pOp;
   56442     if( i<p->nOp ){
   56443       /* The output line number is small enough that we are still in the
   56444       ** main program. */
   56445       pOp = &p->aOp[i];
   56446     }else{
   56447       /* We are currently listing subprograms.  Figure out which one and
   56448       ** pick up the appropriate opcode. */
   56449       int j;
   56450       i -= p->nOp;
   56451       for(j=0; i>=apSub[j]->nOp; j++){
   56452         i -= apSub[j]->nOp;
   56453       }
   56454       pOp = &apSub[j]->aOp[i];
   56455     }
   56456     if( p->explain==1 ){
   56457       pMem->flags = MEM_Int;
   56458       pMem->type = SQLITE_INTEGER;
   56459       pMem->u.i = i;                                /* Program counter */
   56460       pMem++;
   56461 
   56462       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
   56463       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
   56464       assert( pMem->z!=0 );
   56465       pMem->n = sqlite3Strlen30(pMem->z);
   56466       pMem->type = SQLITE_TEXT;
   56467       pMem->enc = SQLITE_UTF8;
   56468       pMem++;
   56469 
   56470       /* When an OP_Program opcode is encounter (the only opcode that has
   56471       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
   56472       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
   56473       ** has not already been seen.
   56474       */
   56475       if( pOp->p4type==P4_SUBPROGRAM ){
   56476         int nByte = (nSub+1)*sizeof(SubProgram*);
   56477         int j;
   56478         for(j=0; j<nSub; j++){
   56479           if( apSub[j]==pOp->p4.pProgram ) break;
   56480         }
   56481         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
   56482           apSub = (SubProgram **)pSub->z;
   56483           apSub[nSub++] = pOp->p4.pProgram;
   56484           pSub->flags |= MEM_Blob;
   56485           pSub->n = nSub*sizeof(SubProgram*);
   56486         }
   56487       }
   56488     }
   56489 
   56490     pMem->flags = MEM_Int;
   56491     pMem->u.i = pOp->p1;                          /* P1 */
   56492     pMem->type = SQLITE_INTEGER;
   56493     pMem++;
   56494 
   56495     pMem->flags = MEM_Int;
   56496     pMem->u.i = pOp->p2;                          /* P2 */
   56497     pMem->type = SQLITE_INTEGER;
   56498     pMem++;
   56499 
   56500     pMem->flags = MEM_Int;
   56501     pMem->u.i = pOp->p3;                          /* P3 */
   56502     pMem->type = SQLITE_INTEGER;
   56503     pMem++;
   56504 
   56505     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
   56506       assert( p->db->mallocFailed );
   56507       return SQLITE_ERROR;
   56508     }
   56509     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   56510     z = displayP4(pOp, pMem->z, 32);
   56511     if( z!=pMem->z ){
   56512       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
   56513     }else{
   56514       assert( pMem->z!=0 );
   56515       pMem->n = sqlite3Strlen30(pMem->z);
   56516       pMem->enc = SQLITE_UTF8;
   56517     }
   56518     pMem->type = SQLITE_TEXT;
   56519     pMem++;
   56520 
   56521     if( p->explain==1 ){
   56522       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
   56523         assert( p->db->mallocFailed );
   56524         return SQLITE_ERROR;
   56525       }
   56526       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
   56527       pMem->n = 2;
   56528       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
   56529       pMem->type = SQLITE_TEXT;
   56530       pMem->enc = SQLITE_UTF8;
   56531       pMem++;
   56532 
   56533 #ifdef SQLITE_DEBUG
   56534       if( pOp->zComment ){
   56535         pMem->flags = MEM_Str|MEM_Term;
   56536         pMem->z = pOp->zComment;
   56537         pMem->n = sqlite3Strlen30(pMem->z);
   56538         pMem->enc = SQLITE_UTF8;
   56539         pMem->type = SQLITE_TEXT;
   56540       }else
   56541 #endif
   56542       {
   56543         pMem->flags = MEM_Null;                       /* Comment */
   56544         pMem->type = SQLITE_NULL;
   56545       }
   56546     }
   56547 
   56548     p->nResColumn = 8 - 4*(p->explain-1);
   56549     p->rc = SQLITE_OK;
   56550     rc = SQLITE_ROW;
   56551   }
   56552   return rc;
   56553 }
   56554 #endif /* SQLITE_OMIT_EXPLAIN */
   56555 
   56556 #ifdef SQLITE_DEBUG
   56557 /*
   56558 ** Print the SQL that was used to generate a VDBE program.
   56559 */
   56560 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
   56561   int nOp = p->nOp;
   56562   VdbeOp *pOp;
   56563   if( nOp<1 ) return;
   56564   pOp = &p->aOp[0];
   56565   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   56566     const char *z = pOp->p4.z;
   56567     while( sqlite3Isspace(*z) ) z++;
   56568     printf("SQL: [%s]\n", z);
   56569   }
   56570 }
   56571 #endif
   56572 
   56573 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   56574 /*
   56575 ** Print an IOTRACE message showing SQL content.
   56576 */
   56577 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
   56578   int nOp = p->nOp;
   56579   VdbeOp *pOp;
   56580   if( sqlite3IoTrace==0 ) return;
   56581   if( nOp<1 ) return;
   56582   pOp = &p->aOp[0];
   56583   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
   56584     int i, j;
   56585     char z[1000];
   56586     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
   56587     for(i=0; sqlite3Isspace(z[i]); i++){}
   56588     for(j=0; z[i]; i++){
   56589       if( sqlite3Isspace(z[i]) ){
   56590         if( z[i-1]!=' ' ){
   56591           z[j++] = ' ';
   56592         }
   56593       }else{
   56594         z[j++] = z[i];
   56595       }
   56596     }
   56597     z[j] = 0;
   56598     sqlite3IoTrace("SQL %s\n", z);
   56599   }
   56600 }
   56601 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
   56602 
   56603 /*
   56604 ** Allocate space from a fixed size buffer and return a pointer to
   56605 ** that space.  If insufficient space is available, return NULL.
   56606 **
   56607 ** The pBuf parameter is the initial value of a pointer which will
   56608 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
   56609 ** NULL, it means that memory space has already been allocated and that
   56610 ** this routine should not allocate any new memory.  When pBuf is not
   56611 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
   56612 ** is NULL.
   56613 **
   56614 ** nByte is the number of bytes of space needed.
   56615 **
   56616 ** *ppFrom points to available space and pEnd points to the end of the
   56617 ** available space.  When space is allocated, *ppFrom is advanced past
   56618 ** the end of the allocated space.
   56619 **
   56620 ** *pnByte is a counter of the number of bytes of space that have failed
   56621 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
   56622 ** request, then increment *pnByte by the amount of the request.
   56623 */
   56624 static void *allocSpace(
   56625   void *pBuf,          /* Where return pointer will be stored */
   56626   int nByte,           /* Number of bytes to allocate */
   56627   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
   56628   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
   56629   int *pnByte          /* If allocation cannot be made, increment *pnByte */
   56630 ){
   56631   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
   56632   if( pBuf ) return pBuf;
   56633   nByte = ROUND8(nByte);
   56634   if( &(*ppFrom)[nByte] <= pEnd ){
   56635     pBuf = (void*)*ppFrom;
   56636     *ppFrom += nByte;
   56637   }else{
   56638     *pnByte += nByte;
   56639   }
   56640   return pBuf;
   56641 }
   56642 
   56643 /*
   56644 ** Prepare a virtual machine for execution.  This involves things such
   56645 ** as allocating stack space and initializing the program counter.
   56646 ** After the VDBE has be prepped, it can be executed by one or more
   56647 ** calls to sqlite3VdbeExec().
   56648 **
   56649 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
   56650 ** VDBE_MAGIC_RUN.
   56651 **
   56652 ** This function may be called more than once on a single virtual machine.
   56653 ** The first call is made while compiling the SQL statement. Subsequent
   56654 ** calls are made as part of the process of resetting a statement to be
   56655 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
   56656 ** and isExplain parameters are only passed correct values the first time
   56657 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
   56658 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
   56659 */
   56660 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   56661   Vdbe *p,                       /* The VDBE */
   56662   int nVar,                      /* Number of '?' see in the SQL statement */
   56663   int nMem,                      /* Number of memory cells to allocate */
   56664   int nCursor,                   /* Number of cursors to allocate */
   56665   int nArg,                      /* Maximum number of args in SubPrograms */
   56666   int isExplain,                 /* True if the EXPLAIN keywords is present */
   56667   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
   56668 ){
   56669   int n;
   56670   sqlite3 *db = p->db;
   56671 
   56672   assert( p!=0 );
   56673   assert( p->magic==VDBE_MAGIC_INIT );
   56674 
   56675   /* There should be at least one opcode.
   56676   */
   56677   assert( p->nOp>0 );
   56678 
   56679   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
   56680   p->magic = VDBE_MAGIC_RUN;
   56681 
   56682   /* For each cursor required, also allocate a memory cell. Memory
   56683   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
   56684   ** the vdbe program. Instead they are used to allocate space for
   56685   ** VdbeCursor/BtCursor structures. The blob of memory associated with
   56686   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
   56687   ** stores the blob of memory associated with cursor 1, etc.
   56688   **
   56689   ** See also: allocateCursor().
   56690   */
   56691   nMem += nCursor;
   56692 
   56693   /* Allocate space for memory registers, SQL variables, VDBE cursors and
   56694   ** an array to marshal SQL function arguments in. This is only done the
   56695   ** first time this function is called for a given VDBE, not when it is
   56696   ** being called from sqlite3_reset() to reset the virtual machine.
   56697   */
   56698   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
   56699     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
   56700     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
   56701     int nByte;                              /* How much extra memory needed */
   56702 
   56703     resolveP2Values(p, &nArg);
   56704     p->usesStmtJournal = (u8)usesStmtJournal;
   56705     if( isExplain && nMem<10 ){
   56706       nMem = 10;
   56707     }
   56708     memset(zCsr, 0, zEnd-zCsr);
   56709     zCsr += (zCsr - (u8*)0)&7;
   56710     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
   56711 
   56712     /* Memory for registers, parameters, cursor, etc, is allocated in two
   56713     ** passes.  On the first pass, we try to reuse unused space at the
   56714     ** end of the opcode array.  If we are unable to satisfy all memory
   56715     ** requirements by reusing the opcode array tail, then the second
   56716     ** pass will fill in the rest using a fresh allocation.
   56717     **
   56718     ** This two-pass approach that reuses as much memory as possible from
   56719     ** the leftover space at the end of the opcode array can significantly
   56720     ** reduce the amount of memory held by a prepared statement.
   56721     */
   56722     do {
   56723       nByte = 0;
   56724       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
   56725       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
   56726       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
   56727       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
   56728       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
   56729                             &zCsr, zEnd, &nByte);
   56730       if( nByte ){
   56731         p->pFree = sqlite3DbMallocZero(db, nByte);
   56732       }
   56733       zCsr = p->pFree;
   56734       zEnd = &zCsr[nByte];
   56735     }while( nByte && !db->mallocFailed );
   56736 
   56737     p->nCursor = (u16)nCursor;
   56738     if( p->aVar ){
   56739       p->nVar = (ynVar)nVar;
   56740       for(n=0; n<nVar; n++){
   56741         p->aVar[n].flags = MEM_Null;
   56742         p->aVar[n].db = db;
   56743       }
   56744     }
   56745     if( p->aMem ){
   56746       p->aMem--;                      /* aMem[] goes from 1..nMem */
   56747       p->nMem = nMem;                 /*       not from 0..nMem-1 */
   56748       for(n=1; n<=nMem; n++){
   56749         p->aMem[n].flags = MEM_Null;
   56750         p->aMem[n].db = db;
   56751       }
   56752     }
   56753   }
   56754 #ifdef SQLITE_DEBUG
   56755   for(n=1; n<p->nMem; n++){
   56756     assert( p->aMem[n].db==db );
   56757   }
   56758 #endif
   56759 
   56760   p->pc = -1;
   56761   p->rc = SQLITE_OK;
   56762   p->errorAction = OE_Abort;
   56763   p->explain |= isExplain;
   56764   p->magic = VDBE_MAGIC_RUN;
   56765   p->nChange = 0;
   56766   p->cacheCtr = 1;
   56767   p->minWriteFileFormat = 255;
   56768   p->iStatement = 0;
   56769   p->nFkConstraint = 0;
   56770 #ifdef VDBE_PROFILE
   56771   {
   56772     int i;
   56773     for(i=0; i<p->nOp; i++){
   56774       p->aOp[i].cnt = 0;
   56775       p->aOp[i].cycles = 0;
   56776     }
   56777   }
   56778 #endif
   56779 }
   56780 
   56781 /*
   56782 ** Close a VDBE cursor and release all the resources that cursor
   56783 ** happens to hold.
   56784 */
   56785 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
   56786   if( pCx==0 ){
   56787     return;
   56788   }
   56789   if( pCx->pBt ){
   56790     sqlite3BtreeClose(pCx->pBt);
   56791     /* The pCx->pCursor will be close automatically, if it exists, by
   56792     ** the call above. */
   56793   }else if( pCx->pCursor ){
   56794     sqlite3BtreeCloseCursor(pCx->pCursor);
   56795   }
   56796 #ifndef SQLITE_OMIT_VIRTUALTABLE
   56797   if( pCx->pVtabCursor ){
   56798     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
   56799     const sqlite3_module *pModule = pCx->pModule;
   56800     p->inVtabMethod = 1;
   56801     pModule->xClose(pVtabCursor);
   56802     p->inVtabMethod = 0;
   56803   }
   56804 #endif
   56805 }
   56806 
   56807 /*
   56808 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
   56809 ** is used, for example, when a trigger sub-program is halted to restore
   56810 ** control to the main program.
   56811 */
   56812 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
   56813   Vdbe *v = pFrame->v;
   56814   v->aOp = pFrame->aOp;
   56815   v->nOp = pFrame->nOp;
   56816   v->aMem = pFrame->aMem;
   56817   v->nMem = pFrame->nMem;
   56818   v->apCsr = pFrame->apCsr;
   56819   v->nCursor = pFrame->nCursor;
   56820   v->db->lastRowid = pFrame->lastRowid;
   56821   v->nChange = pFrame->nChange;
   56822   return pFrame->pc;
   56823 }
   56824 
   56825 /*
   56826 ** Close all cursors.
   56827 **
   56828 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
   56829 ** cell array. This is necessary as the memory cell array may contain
   56830 ** pointers to VdbeFrame objects, which may in turn contain pointers to
   56831 ** open cursors.
   56832 */
   56833 static void closeAllCursors(Vdbe *p){
   56834   if( p->pFrame ){
   56835     VdbeFrame *pFrame = p->pFrame;
   56836     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
   56837     sqlite3VdbeFrameRestore(pFrame);
   56838   }
   56839   p->pFrame = 0;
   56840   p->nFrame = 0;
   56841 
   56842   if( p->apCsr ){
   56843     int i;
   56844     for(i=0; i<p->nCursor; i++){
   56845       VdbeCursor *pC = p->apCsr[i];
   56846       if( pC ){
   56847         sqlite3VdbeFreeCursor(p, pC);
   56848         p->apCsr[i] = 0;
   56849       }
   56850     }
   56851   }
   56852   if( p->aMem ){
   56853     releaseMemArray(&p->aMem[1], p->nMem);
   56854   }
   56855   while( p->pDelFrame ){
   56856     VdbeFrame *pDel = p->pDelFrame;
   56857     p->pDelFrame = pDel->pParent;
   56858     sqlite3VdbeFrameDelete(pDel);
   56859   }
   56860 }
   56861 
   56862 /*
   56863 ** Clean up the VM after execution.
   56864 **
   56865 ** This routine will automatically close any cursors, lists, and/or
   56866 ** sorters that were left open.  It also deletes the values of
   56867 ** variables in the aVar[] array.
   56868 */
   56869 static void Cleanup(Vdbe *p){
   56870   sqlite3 *db = p->db;
   56871 
   56872 #ifdef SQLITE_DEBUG
   56873   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   56874   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   56875   int i;
   56876   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
   56877   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
   56878 #endif
   56879 
   56880   sqlite3DbFree(db, p->zErrMsg);
   56881   p->zErrMsg = 0;
   56882   p->pResultSet = 0;
   56883 }
   56884 
   56885 /*
   56886 ** Set the number of result columns that will be returned by this SQL
   56887 ** statement. This is now set at compile time, rather than during
   56888 ** execution of the vdbe program so that sqlite3_column_count() can
   56889 ** be called on an SQL statement before sqlite3_step().
   56890 */
   56891 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
   56892   Mem *pColName;
   56893   int n;
   56894   sqlite3 *db = p->db;
   56895 
   56896   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   56897   sqlite3DbFree(db, p->aColName);
   56898   n = nResColumn*COLNAME_N;
   56899   p->nResColumn = (u16)nResColumn;
   56900   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
   56901   if( p->aColName==0 ) return;
   56902   while( n-- > 0 ){
   56903     pColName->flags = MEM_Null;
   56904     pColName->db = p->db;
   56905     pColName++;
   56906   }
   56907 }
   56908 
   56909 /*
   56910 ** Set the name of the idx'th column to be returned by the SQL statement.
   56911 ** zName must be a pointer to a nul terminated string.
   56912 **
   56913 ** This call must be made after a call to sqlite3VdbeSetNumCols().
   56914 **
   56915 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
   56916 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
   56917 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
   56918 */
   56919 SQLITE_PRIVATE int sqlite3VdbeSetColName(
   56920   Vdbe *p,                         /* Vdbe being configured */
   56921   int idx,                         /* Index of column zName applies to */
   56922   int var,                         /* One of the COLNAME_* constants */
   56923   const char *zName,               /* Pointer to buffer containing name */
   56924   void (*xDel)(void*)              /* Memory management strategy for zName */
   56925 ){
   56926   int rc;
   56927   Mem *pColName;
   56928   assert( idx<p->nResColumn );
   56929   assert( var<COLNAME_N );
   56930   if( p->db->mallocFailed ){
   56931     assert( !zName || xDel!=SQLITE_DYNAMIC );
   56932     return SQLITE_NOMEM;
   56933   }
   56934   assert( p->aColName!=0 );
   56935   pColName = &(p->aColName[idx+var*p->nResColumn]);
   56936   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
   56937   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
   56938   return rc;
   56939 }
   56940 
   56941 /*
   56942 ** A read or write transaction may or may not be active on database handle
   56943 ** db. If a transaction is active, commit it. If there is a
   56944 ** write-transaction spanning more than one database file, this routine
   56945 ** takes care of the master journal trickery.
   56946 */
   56947 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   56948   int i;
   56949   int nTrans = 0;  /* Number of databases with an active write-transaction */
   56950   int rc = SQLITE_OK;
   56951   int needXcommit = 0;
   56952 
   56953 #ifdef SQLITE_OMIT_VIRTUALTABLE
   56954   /* With this option, sqlite3VtabSync() is defined to be simply
   56955   ** SQLITE_OK so p is not used.
   56956   */
   56957   UNUSED_PARAMETER(p);
   56958 #endif
   56959 
   56960   /* Before doing anything else, call the xSync() callback for any
   56961   ** virtual module tables written in this transaction. This has to
   56962   ** be done before determining whether a master journal file is
   56963   ** required, as an xSync() callback may add an attached database
   56964   ** to the transaction.
   56965   */
   56966   rc = sqlite3VtabSync(db, &p->zErrMsg);
   56967 
   56968   /* This loop determines (a) if the commit hook should be invoked and
   56969   ** (b) how many database files have open write transactions, not
   56970   ** including the temp database. (b) is important because if more than
   56971   ** one database file has an open write transaction, a master journal
   56972   ** file is required for an atomic commit.
   56973   */
   56974   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   56975     Btree *pBt = db->aDb[i].pBt;
   56976     if( sqlite3BtreeIsInTrans(pBt) ){
   56977       needXcommit = 1;
   56978       if( i!=1 ) nTrans++;
   56979       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
   56980     }
   56981   }
   56982   if( rc!=SQLITE_OK ){
   56983     return rc;
   56984   }
   56985 
   56986   /* If there are any write-transactions at all, invoke the commit hook */
   56987   if( needXcommit && db->xCommitCallback ){
   56988     rc = db->xCommitCallback(db->pCommitArg);
   56989     if( rc ){
   56990       return SQLITE_CONSTRAINT;
   56991     }
   56992   }
   56993 
   56994   /* The simple case - no more than one database file (not counting the
   56995   ** TEMP database) has a transaction active.   There is no need for the
   56996   ** master-journal.
   56997   **
   56998   ** If the return value of sqlite3BtreeGetFilename() is a zero length
   56999   ** string, it means the main database is :memory: or a temp file.  In
   57000   ** that case we do not support atomic multi-file commits, so use the
   57001   ** simple case then too.
   57002   */
   57003   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
   57004    || nTrans<=1
   57005   ){
   57006     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   57007       Btree *pBt = db->aDb[i].pBt;
   57008       if( pBt ){
   57009         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
   57010       }
   57011     }
   57012 
   57013     /* Do the commit only if all databases successfully complete phase 1.
   57014     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
   57015     ** IO error while deleting or truncating a journal file. It is unlikely,
   57016     ** but could happen. In this case abandon processing and return the error.
   57017     */
   57018     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   57019       Btree *pBt = db->aDb[i].pBt;
   57020       if( pBt ){
   57021         rc = sqlite3BtreeCommitPhaseTwo(pBt);
   57022       }
   57023     }
   57024     if( rc==SQLITE_OK ){
   57025       sqlite3VtabCommit(db);
   57026     }
   57027   }
   57028 
   57029   /* The complex case - There is a multi-file write-transaction active.
   57030   ** This requires a master journal file to ensure the transaction is
   57031   ** committed atomicly.
   57032   */
   57033 #ifndef SQLITE_OMIT_DISKIO
   57034   else{
   57035     sqlite3_vfs *pVfs = db->pVfs;
   57036     int needSync = 0;
   57037     char *zMaster = 0;   /* File-name for the master journal */
   57038     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
   57039     sqlite3_file *pMaster = 0;
   57040     i64 offset = 0;
   57041     int res;
   57042 
   57043     /* Select a master journal file name */
   57044     do {
   57045       u32 iRandom;
   57046       sqlite3DbFree(db, zMaster);
   57047       sqlite3_randomness(sizeof(iRandom), &iRandom);
   57048       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
   57049       if( !zMaster ){
   57050         return SQLITE_NOMEM;
   57051       }
   57052       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
   57053     }while( rc==SQLITE_OK && res );
   57054     if( rc==SQLITE_OK ){
   57055       /* Open the master journal. */
   57056       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
   57057           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
   57058           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
   57059       );
   57060     }
   57061     if( rc!=SQLITE_OK ){
   57062       sqlite3DbFree(db, zMaster);
   57063       return rc;
   57064     }
   57065 
   57066     /* Write the name of each database file in the transaction into the new
   57067     ** master journal file. If an error occurs at this point close
   57068     ** and delete the master journal file. All the individual journal files
   57069     ** still have 'null' as the master journal pointer, so they will roll
   57070     ** back independently if a failure occurs.
   57071     */
   57072     for(i=0; i<db->nDb; i++){
   57073       Btree *pBt = db->aDb[i].pBt;
   57074       if( sqlite3BtreeIsInTrans(pBt) ){
   57075         char const *zFile = sqlite3BtreeGetJournalname(pBt);
   57076         if( zFile==0 ){
   57077           continue;  /* Ignore TEMP and :memory: databases */
   57078         }
   57079         assert( zFile[0]!=0 );
   57080         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
   57081           needSync = 1;
   57082         }
   57083         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
   57084         offset += sqlite3Strlen30(zFile)+1;
   57085         if( rc!=SQLITE_OK ){
   57086           sqlite3OsCloseFree(pMaster);
   57087           sqlite3OsDelete(pVfs, zMaster, 0);
   57088           sqlite3DbFree(db, zMaster);
   57089           return rc;
   57090         }
   57091       }
   57092     }
   57093 
   57094     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
   57095     ** flag is set this is not required.
   57096     */
   57097     if( needSync
   57098      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
   57099      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
   57100     ){
   57101       sqlite3OsCloseFree(pMaster);
   57102       sqlite3OsDelete(pVfs, zMaster, 0);
   57103       sqlite3DbFree(db, zMaster);
   57104       return rc;
   57105     }
   57106 
   57107     /* Sync all the db files involved in the transaction. The same call
   57108     ** sets the master journal pointer in each individual journal. If
   57109     ** an error occurs here, do not delete the master journal file.
   57110     **
   57111     ** If the error occurs during the first call to
   57112     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
   57113     ** master journal file will be orphaned. But we cannot delete it,
   57114     ** in case the master journal file name was written into the journal
   57115     ** file before the failure occurred.
   57116     */
   57117     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   57118       Btree *pBt = db->aDb[i].pBt;
   57119       if( pBt ){
   57120         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
   57121       }
   57122     }
   57123     sqlite3OsCloseFree(pMaster);
   57124     assert( rc!=SQLITE_BUSY );
   57125     if( rc!=SQLITE_OK ){
   57126       sqlite3DbFree(db, zMaster);
   57127       return rc;
   57128     }
   57129 
   57130     /* Delete the master journal file. This commits the transaction. After
   57131     ** doing this the directory is synced again before any individual
   57132     ** transaction files are deleted.
   57133     */
   57134     rc = sqlite3OsDelete(pVfs, zMaster, 1);
   57135     sqlite3DbFree(db, zMaster);
   57136     zMaster = 0;
   57137     if( rc ){
   57138       return rc;
   57139     }
   57140 
   57141     /* All files and directories have already been synced, so the following
   57142     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
   57143     ** deleting or truncating journals. If something goes wrong while
   57144     ** this is happening we don't really care. The integrity of the
   57145     ** transaction is already guaranteed, but some stray 'cold' journals
   57146     ** may be lying around. Returning an error code won't help matters.
   57147     */
   57148     disable_simulated_io_errors();
   57149     sqlite3BeginBenignMalloc();
   57150     for(i=0; i<db->nDb; i++){
   57151       Btree *pBt = db->aDb[i].pBt;
   57152       if( pBt ){
   57153         sqlite3BtreeCommitPhaseTwo(pBt);
   57154       }
   57155     }
   57156     sqlite3EndBenignMalloc();
   57157     enable_simulated_io_errors();
   57158 
   57159     sqlite3VtabCommit(db);
   57160   }
   57161 #endif
   57162 
   57163   return rc;
   57164 }
   57165 
   57166 /*
   57167 ** This routine checks that the sqlite3.activeVdbeCnt count variable
   57168 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
   57169 ** currently active. An assertion fails if the two counts do not match.
   57170 ** This is an internal self-check only - it is not an essential processing
   57171 ** step.
   57172 **
   57173 ** This is a no-op if NDEBUG is defined.
   57174 */
   57175 #ifndef NDEBUG
   57176 static void checkActiveVdbeCnt(sqlite3 *db){
   57177   Vdbe *p;
   57178   int cnt = 0;
   57179   int nWrite = 0;
   57180   p = db->pVdbe;
   57181   while( p ){
   57182     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
   57183       cnt++;
   57184       if( p->readOnly==0 ) nWrite++;
   57185     }
   57186     p = p->pNext;
   57187   }
   57188   assert( cnt==db->activeVdbeCnt );
   57189   assert( nWrite==db->writeVdbeCnt );
   57190 }
   57191 #else
   57192 #define checkActiveVdbeCnt(x)
   57193 #endif
   57194 
   57195 /*
   57196 ** For every Btree that in database connection db which
   57197 ** has been modified, "trip" or invalidate each cursor in
   57198 ** that Btree might have been modified so that the cursor
   57199 ** can never be used again.  This happens when a rollback
   57200 *** occurs.  We have to trip all the other cursors, even
   57201 ** cursor from other VMs in different database connections,
   57202 ** so that none of them try to use the data at which they
   57203 ** were pointing and which now may have been changed due
   57204 ** to the rollback.
   57205 **
   57206 ** Remember that a rollback can delete tables complete and
   57207 ** reorder rootpages.  So it is not sufficient just to save
   57208 ** the state of the cursor.  We have to invalidate the cursor
   57209 ** so that it is never used again.
   57210 */
   57211 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
   57212   int i;
   57213   for(i=0; i<db->nDb; i++){
   57214     Btree *p = db->aDb[i].pBt;
   57215     if( p && sqlite3BtreeIsInTrans(p) ){
   57216       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
   57217     }
   57218   }
   57219 }
   57220 
   57221 /*
   57222 ** If the Vdbe passed as the first argument opened a statement-transaction,
   57223 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
   57224 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
   57225 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
   57226 ** statement transaction is commtted.
   57227 **
   57228 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
   57229 ** Otherwise SQLITE_OK.
   57230 */
   57231 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
   57232   sqlite3 *const db = p->db;
   57233   int rc = SQLITE_OK;
   57234 
   57235   /* If p->iStatement is greater than zero, then this Vdbe opened a
   57236   ** statement transaction that should be closed here. The only exception
   57237   ** is that an IO error may have occured, causing an emergency rollback.
   57238   ** In this case (db->nStatement==0), and there is nothing to do.
   57239   */
   57240   if( db->nStatement && p->iStatement ){
   57241     int i;
   57242     const int iSavepoint = p->iStatement-1;
   57243 
   57244     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
   57245     assert( db->nStatement>0 );
   57246     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
   57247 
   57248     for(i=0; i<db->nDb; i++){
   57249       int rc2 = SQLITE_OK;
   57250       Btree *pBt = db->aDb[i].pBt;
   57251       if( pBt ){
   57252         if( eOp==SAVEPOINT_ROLLBACK ){
   57253           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
   57254         }
   57255         if( rc2==SQLITE_OK ){
   57256           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
   57257         }
   57258         if( rc==SQLITE_OK ){
   57259           rc = rc2;
   57260         }
   57261       }
   57262     }
   57263     db->nStatement--;
   57264     p->iStatement = 0;
   57265 
   57266     /* If the statement transaction is being rolled back, also restore the
   57267     ** database handles deferred constraint counter to the value it had when
   57268     ** the statement transaction was opened.  */
   57269     if( eOp==SAVEPOINT_ROLLBACK ){
   57270       db->nDeferredCons = p->nStmtDefCons;
   57271     }
   57272   }
   57273   return rc;
   57274 }
   57275 
   57276 /*
   57277 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
   57278 ** this routine obtains the mutex associated with each BtShared structure
   57279 ** that may be accessed by the VM passed as an argument. In doing so it
   57280 ** sets the BtShared.db member of each of the BtShared structures, ensuring
   57281 ** that the correct busy-handler callback is invoked if required.
   57282 **
   57283 ** If SQLite is not threadsafe but does support shared-cache mode, then
   57284 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
   57285 ** of all of BtShared structures accessible via the database handle
   57286 ** associated with the VM. Of course only a subset of these structures
   57287 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
   57288 ** that subset out, but there is no advantage to doing so.
   57289 **
   57290 ** If SQLite is not threadsafe and does not support shared-cache mode, this
   57291 ** function is a no-op.
   57292 */
   57293 #ifndef SQLITE_OMIT_SHARED_CACHE
   57294 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
   57295 #if SQLITE_THREADSAFE
   57296   sqlite3BtreeMutexArrayEnter(&p->aMutex);
   57297 #else
   57298   sqlite3BtreeEnterAll(p->db);
   57299 #endif
   57300 }
   57301 #endif
   57302 
   57303 /*
   57304 ** This function is called when a transaction opened by the database
   57305 ** handle associated with the VM passed as an argument is about to be
   57306 ** committed. If there are outstanding deferred foreign key constraint
   57307 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
   57308 **
   57309 ** If there are outstanding FK violations and this function returns
   57310 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
   57311 ** an error message to it. Then return SQLITE_ERROR.
   57312 */
   57313 #ifndef SQLITE_OMIT_FOREIGN_KEY
   57314 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   57315   sqlite3 *db = p->db;
   57316   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
   57317     p->rc = SQLITE_CONSTRAINT;
   57318     p->errorAction = OE_Abort;
   57319     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
   57320     return SQLITE_ERROR;
   57321   }
   57322   return SQLITE_OK;
   57323 }
   57324 #endif
   57325 
   57326 /*
   57327 ** This routine is called the when a VDBE tries to halt.  If the VDBE
   57328 ** has made changes and is in autocommit mode, then commit those
   57329 ** changes.  If a rollback is needed, then do the rollback.
   57330 **
   57331 ** This routine is the only way to move the state of a VM from
   57332 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
   57333 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
   57334 **
   57335 ** Return an error code.  If the commit could not complete because of
   57336 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
   57337 ** means the close did not happen and needs to be repeated.
   57338 */
   57339 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   57340   int rc;                         /* Used to store transient return codes */
   57341   sqlite3 *db = p->db;
   57342 
   57343   /* This function contains the logic that determines if a statement or
   57344   ** transaction will be committed or rolled back as a result of the
   57345   ** execution of this virtual machine.
   57346   **
   57347   ** If any of the following errors occur:
   57348   **
   57349   **     SQLITE_NOMEM
   57350   **     SQLITE_IOERR
   57351   **     SQLITE_FULL
   57352   **     SQLITE_INTERRUPT
   57353   **
   57354   ** Then the internal cache might have been left in an inconsistent
   57355   ** state.  We need to rollback the statement transaction, if there is
   57356   ** one, or the complete transaction if there is no statement transaction.
   57357   */
   57358 
   57359   if( p->db->mallocFailed ){
   57360     p->rc = SQLITE_NOMEM;
   57361   }
   57362   closeAllCursors(p);
   57363   if( p->magic!=VDBE_MAGIC_RUN ){
   57364     return SQLITE_OK;
   57365   }
   57366   checkActiveVdbeCnt(db);
   57367 
   57368   /* No commit or rollback needed if the program never started */
   57369   if( p->pc>=0 ){
   57370     int mrc;   /* Primary error code from p->rc */
   57371     int eStatementOp = 0;
   57372     int isSpecialError;            /* Set to true if a 'special' error */
   57373 
   57374     /* Lock all btrees used by the statement */
   57375     sqlite3VdbeMutexArrayEnter(p);
   57376 
   57377     /* Check for one of the special errors */
   57378     mrc = p->rc & 0xff;
   57379     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
   57380     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
   57381                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
   57382     if( isSpecialError ){
   57383       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
   57384       ** no rollback is necessary. Otherwise, at least a savepoint
   57385       ** transaction must be rolled back to restore the database to a
   57386       ** consistent state.
   57387       **
   57388       ** Even if the statement is read-only, it is important to perform
   57389       ** a statement or transaction rollback operation. If the error
   57390       ** occured while writing to the journal, sub-journal or database
   57391       ** file as part of an effort to free up cache space (see function
   57392       ** pagerStress() in pager.c), the rollback is required to restore
   57393       ** the pager to a consistent state.
   57394       */
   57395       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
   57396         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
   57397           eStatementOp = SAVEPOINT_ROLLBACK;
   57398         }else{
   57399           /* We are forced to roll back the active transaction. Before doing
   57400           ** so, abort any other statements this handle currently has active.
   57401           */
   57402           invalidateCursorsOnModifiedBtrees(db);
   57403           sqlite3RollbackAll(db);
   57404           sqlite3CloseSavepoints(db);
   57405           db->autoCommit = 1;
   57406         }
   57407       }
   57408     }
   57409 
   57410     /* Check for immediate foreign key violations. */
   57411     if( p->rc==SQLITE_OK ){
   57412       sqlite3VdbeCheckFk(p, 0);
   57413     }
   57414 
   57415     /* If the auto-commit flag is set and this is the only active writer
   57416     ** VM, then we do either a commit or rollback of the current transaction.
   57417     **
   57418     ** Note: This block also runs if one of the special errors handled
   57419     ** above has occurred.
   57420     */
   57421     if( !sqlite3VtabInSync(db)
   57422      && db->autoCommit
   57423      && db->writeVdbeCnt==(p->readOnly==0)
   57424     ){
   57425       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
   57426         if( sqlite3VdbeCheckFk(p, 1) ){
   57427           sqlite3BtreeMutexArrayLeave(&p->aMutex);
   57428           return SQLITE_ERROR;
   57429         }
   57430         /* The auto-commit flag is true, the vdbe program was successful
   57431         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
   57432         ** key constraints to hold up the transaction. This means a commit
   57433         ** is required.  */
   57434         rc = vdbeCommit(db, p);
   57435         if( rc==SQLITE_BUSY ){
   57436           sqlite3BtreeMutexArrayLeave(&p->aMutex);
   57437           return SQLITE_BUSY;
   57438         }else if( rc!=SQLITE_OK ){
   57439           p->rc = rc;
   57440           sqlite3RollbackAll(db);
   57441         }else{
   57442           db->nDeferredCons = 0;
   57443           sqlite3CommitInternalChanges(db);
   57444         }
   57445       }else{
   57446         sqlite3RollbackAll(db);
   57447       }
   57448       db->nStatement = 0;
   57449     }else if( eStatementOp==0 ){
   57450       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
   57451         eStatementOp = SAVEPOINT_RELEASE;
   57452       }else if( p->errorAction==OE_Abort ){
   57453         eStatementOp = SAVEPOINT_ROLLBACK;
   57454       }else{
   57455         invalidateCursorsOnModifiedBtrees(db);
   57456         sqlite3RollbackAll(db);
   57457         sqlite3CloseSavepoints(db);
   57458         db->autoCommit = 1;
   57459       }
   57460     }
   57461 
   57462     /* If eStatementOp is non-zero, then a statement transaction needs to
   57463     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
   57464     ** do so. If this operation returns an error, and the current statement
   57465     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
   57466     ** current statement error code.
   57467     **
   57468     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
   57469     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
   57470     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
   57471     ** the following code.
   57472     */
   57473     if( eStatementOp ){
   57474       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
   57475       if( rc ){
   57476         assert( eStatementOp==SAVEPOINT_ROLLBACK );
   57477         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
   57478           p->rc = rc;
   57479           sqlite3DbFree(db, p->zErrMsg);
   57480           p->zErrMsg = 0;
   57481         }
   57482         invalidateCursorsOnModifiedBtrees(db);
   57483         sqlite3RollbackAll(db);
   57484         sqlite3CloseSavepoints(db);
   57485         db->autoCommit = 1;
   57486       }
   57487     }
   57488 
   57489     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
   57490     ** has been rolled back, update the database connection change-counter.
   57491     */
   57492     if( p->changeCntOn ){
   57493       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
   57494         sqlite3VdbeSetChanges(db, p->nChange);
   57495       }else{
   57496         sqlite3VdbeSetChanges(db, 0);
   57497       }
   57498       p->nChange = 0;
   57499     }
   57500 
   57501     /* Rollback or commit any schema changes that occurred. */
   57502     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
   57503       sqlite3ResetInternalSchema(db, 0);
   57504       db->flags = (db->flags | SQLITE_InternChanges);
   57505     }
   57506 
   57507     /* Release the locks */
   57508     sqlite3BtreeMutexArrayLeave(&p->aMutex);
   57509   }
   57510 
   57511   /* We have successfully halted and closed the VM.  Record this fact. */
   57512   if( p->pc>=0 ){
   57513     db->activeVdbeCnt--;
   57514     if( !p->readOnly ){
   57515       db->writeVdbeCnt--;
   57516     }
   57517     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
   57518   }
   57519   p->magic = VDBE_MAGIC_HALT;
   57520   checkActiveVdbeCnt(db);
   57521   if( p->db->mallocFailed ){
   57522     p->rc = SQLITE_NOMEM;
   57523   }
   57524 
   57525   /* If the auto-commit flag is set to true, then any locks that were held
   57526   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   57527   ** to invoke any required unlock-notify callbacks.
   57528   */
   57529   if( db->autoCommit ){
   57530     sqlite3ConnectionUnlocked(db);
   57531   }
   57532 
   57533   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
   57534   return SQLITE_OK;
   57535 }
   57536 
   57537 
   57538 /*
   57539 ** Each VDBE holds the result of the most recent sqlite3_step() call
   57540 ** in p->rc.  This routine sets that result back to SQLITE_OK.
   57541 */
   57542 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
   57543   p->rc = SQLITE_OK;
   57544 }
   57545 
   57546 /*
   57547 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
   57548 ** Write any error messages into *pzErrMsg.  Return the result code.
   57549 **
   57550 ** After this routine is run, the VDBE should be ready to be executed
   57551 ** again.
   57552 **
   57553 ** To look at it another way, this routine resets the state of the
   57554 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
   57555 ** VDBE_MAGIC_INIT.
   57556 */
   57557 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   57558   sqlite3 *db;
   57559   db = p->db;
   57560 
   57561   /* If the VM did not run to completion or if it encountered an
   57562   ** error, then it might not have been halted properly.  So halt
   57563   ** it now.
   57564   */
   57565   sqlite3VdbeHalt(p);
   57566 
   57567   /* If the VDBE has be run even partially, then transfer the error code
   57568   ** and error message from the VDBE into the main database structure.  But
   57569   ** if the VDBE has just been set to run but has not actually executed any
   57570   ** instructions yet, leave the main database error information unchanged.
   57571   */
   57572   if( p->pc>=0 ){
   57573     if( p->zErrMsg ){
   57574       sqlite3BeginBenignMalloc();
   57575       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
   57576       sqlite3EndBenignMalloc();
   57577       db->errCode = p->rc;
   57578       sqlite3DbFree(db, p->zErrMsg);
   57579       p->zErrMsg = 0;
   57580     }else if( p->rc ){
   57581       sqlite3Error(db, p->rc, 0);
   57582     }else{
   57583       sqlite3Error(db, SQLITE_OK, 0);
   57584     }
   57585     if( p->runOnlyOnce ) p->expired = 1;
   57586   }else if( p->rc && p->expired ){
   57587     /* The expired flag was set on the VDBE before the first call
   57588     ** to sqlite3_step(). For consistency (since sqlite3_step() was
   57589     ** called), set the database error in this case as well.
   57590     */
   57591     sqlite3Error(db, p->rc, 0);
   57592     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
   57593     sqlite3DbFree(db, p->zErrMsg);
   57594     p->zErrMsg = 0;
   57595   }
   57596 
   57597   /* Reclaim all memory used by the VDBE
   57598   */
   57599   Cleanup(p);
   57600 
   57601   /* Save profiling information from this VDBE run.
   57602   */
   57603 #ifdef VDBE_PROFILE
   57604   {
   57605     FILE *out = fopen("vdbe_profile.out", "a");
   57606     if( out ){
   57607       int i;
   57608       fprintf(out, "---- ");
   57609       for(i=0; i<p->nOp; i++){
   57610         fprintf(out, "%02x", p->aOp[i].opcode);
   57611       }
   57612       fprintf(out, "\n");
   57613       for(i=0; i<p->nOp; i++){
   57614         fprintf(out, "%6d %10lld %8lld ",
   57615            p->aOp[i].cnt,
   57616            p->aOp[i].cycles,
   57617            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
   57618         );
   57619         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
   57620       }
   57621       fclose(out);
   57622     }
   57623   }
   57624 #endif
   57625   p->magic = VDBE_MAGIC_INIT;
   57626   return p->rc & db->errMask;
   57627 }
   57628 
   57629 /*
   57630 ** Clean up and delete a VDBE after execution.  Return an integer which is
   57631 ** the result code.  Write any error message text into *pzErrMsg.
   57632 */
   57633 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
   57634   int rc = SQLITE_OK;
   57635   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
   57636     rc = sqlite3VdbeReset(p);
   57637     assert( (rc & p->db->errMask)==rc );
   57638   }
   57639   sqlite3VdbeDelete(p);
   57640   return rc;
   57641 }
   57642 
   57643 /*
   57644 ** Call the destructor for each auxdata entry in pVdbeFunc for which
   57645 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
   57646 ** are always destroyed.  To destroy all auxdata entries, call this
   57647 ** routine with mask==0.
   57648 */
   57649 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
   57650   int i;
   57651   for(i=0; i<pVdbeFunc->nAux; i++){
   57652     struct AuxData *pAux = &pVdbeFunc->apAux[i];
   57653     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
   57654       if( pAux->xDelete ){
   57655         pAux->xDelete(pAux->pAux);
   57656       }
   57657       pAux->pAux = 0;
   57658     }
   57659   }
   57660 }
   57661 
   57662 /*
   57663 ** Free all memory associated with the Vdbe passed as the second argument.
   57664 ** The difference between this function and sqlite3VdbeDelete() is that
   57665 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
   57666 ** the database connection.
   57667 */
   57668 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
   57669   SubProgram *pSub, *pNext;
   57670   assert( p->db==0 || p->db==db );
   57671   releaseMemArray(p->aVar, p->nVar);
   57672   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
   57673   for(pSub=p->pProgram; pSub; pSub=pNext){
   57674     pNext = pSub->pNext;
   57675     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
   57676     sqlite3DbFree(db, pSub);
   57677   }
   57678   vdbeFreeOpArray(db, p->aOp, p->nOp);
   57679   sqlite3DbFree(db, p->aLabel);
   57680   sqlite3DbFree(db, p->aColName);
   57681   sqlite3DbFree(db, p->zSql);
   57682   sqlite3DbFree(db, p->pFree);
   57683   sqlite3DbFree(db, p);
   57684 }
   57685 
   57686 /*
   57687 ** Delete an entire VDBE.
   57688 */
   57689 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
   57690   sqlite3 *db;
   57691 
   57692   if( NEVER(p==0) ) return;
   57693   db = p->db;
   57694   if( p->pPrev ){
   57695     p->pPrev->pNext = p->pNext;
   57696   }else{
   57697     assert( db->pVdbe==p );
   57698     db->pVdbe = p->pNext;
   57699   }
   57700   if( p->pNext ){
   57701     p->pNext->pPrev = p->pPrev;
   57702   }
   57703   p->magic = VDBE_MAGIC_DEAD;
   57704   p->db = 0;
   57705   sqlite3VdbeDeleteObject(db, p);
   57706 }
   57707 
   57708 /*
   57709 ** Make sure the cursor p is ready to read or write the row to which it
   57710 ** was last positioned.  Return an error code if an OOM fault or I/O error
   57711 ** prevents us from positioning the cursor to its correct position.
   57712 **
   57713 ** If a MoveTo operation is pending on the given cursor, then do that
   57714 ** MoveTo now.  If no move is pending, check to see if the row has been
   57715 ** deleted out from under the cursor and if it has, mark the row as
   57716 ** a NULL row.
   57717 **
   57718 ** If the cursor is already pointing to the correct row and that row has
   57719 ** not been deleted out from under the cursor, then this routine is a no-op.
   57720 */
   57721 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
   57722   if( p->deferredMoveto ){
   57723     int res, rc;
   57724 #ifdef SQLITE_TEST
   57725     extern int sqlite3_search_count;
   57726 #endif
   57727     assert( p->isTable );
   57728     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
   57729     if( rc ) return rc;
   57730     p->lastRowid = p->movetoTarget;
   57731     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
   57732     p->rowidIsValid = 1;
   57733 #ifdef SQLITE_TEST
   57734     sqlite3_search_count++;
   57735 #endif
   57736     p->deferredMoveto = 0;
   57737     p->cacheStatus = CACHE_STALE;
   57738   }else if( ALWAYS(p->pCursor) ){
   57739     int hasMoved;
   57740     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
   57741     if( rc ) return rc;
   57742     if( hasMoved ){
   57743       p->cacheStatus = CACHE_STALE;
   57744       p->nullRow = 1;
   57745     }
   57746   }
   57747   return SQLITE_OK;
   57748 }
   57749 
   57750 /*
   57751 ** The following functions:
   57752 **
   57753 ** sqlite3VdbeSerialType()
   57754 ** sqlite3VdbeSerialTypeLen()
   57755 ** sqlite3VdbeSerialLen()
   57756 ** sqlite3VdbeSerialPut()
   57757 ** sqlite3VdbeSerialGet()
   57758 **
   57759 ** encapsulate the code that serializes values for storage in SQLite
   57760 ** data and index records. Each serialized value consists of a
   57761 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
   57762 ** integer, stored as a varint.
   57763 **
   57764 ** In an SQLite index record, the serial type is stored directly before
   57765 ** the blob of data that it corresponds to. In a table record, all serial
   57766 ** types are stored at the start of the record, and the blobs of data at
   57767 ** the end. Hence these functions allow the caller to handle the
   57768 ** serial-type and data blob seperately.
   57769 **
   57770 ** The following table describes the various storage classes for data:
   57771 **
   57772 **   serial type        bytes of data      type
   57773 **   --------------     ---------------    ---------------
   57774 **      0                     0            NULL
   57775 **      1                     1            signed integer
   57776 **      2                     2            signed integer
   57777 **      3                     3            signed integer
   57778 **      4                     4            signed integer
   57779 **      5                     6            signed integer
   57780 **      6                     8            signed integer
   57781 **      7                     8            IEEE float
   57782 **      8                     0            Integer constant 0
   57783 **      9                     0            Integer constant 1
   57784 **     10,11                               reserved for expansion
   57785 **    N>=12 and even       (N-12)/2        BLOB
   57786 **    N>=13 and odd        (N-13)/2        text
   57787 **
   57788 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
   57789 ** of SQLite will not understand those serial types.
   57790 */
   57791 
   57792 /*
   57793 ** Return the serial-type for the value stored in pMem.
   57794 */
   57795 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
   57796   int flags = pMem->flags;
   57797   int n;
   57798 
   57799   if( flags&MEM_Null ){
   57800     return 0;
   57801   }
   57802   if( flags&MEM_Int ){
   57803     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
   57804 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
   57805     i64 i = pMem->u.i;
   57806     u64 u;
   57807     if( file_format>=4 && (i&1)==i ){
   57808       return 8+(u32)i;
   57809     }
   57810     u = i<0 ? -i : i;
   57811     if( u<=127 ) return 1;
   57812     if( u<=32767 ) return 2;
   57813     if( u<=8388607 ) return 3;
   57814     if( u<=2147483647 ) return 4;
   57815     if( u<=MAX_6BYTE ) return 5;
   57816     return 6;
   57817   }
   57818   if( flags&MEM_Real ){
   57819     return 7;
   57820   }
   57821   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
   57822   n = pMem->n;
   57823   if( flags & MEM_Zero ){
   57824     n += pMem->u.nZero;
   57825   }
   57826   assert( n>=0 );
   57827   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
   57828 }
   57829 
   57830 /*
   57831 ** Return the length of the data corresponding to the supplied serial-type.
   57832 */
   57833 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   57834   if( serial_type>=12 ){
   57835     return (serial_type-12)/2;
   57836   }else{
   57837     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
   57838     return aSize[serial_type];
   57839   }
   57840 }
   57841 
   57842 /*
   57843 ** If we are on an architecture with mixed-endian floating
   57844 ** points (ex: ARM7) then swap the lower 4 bytes with the
   57845 ** upper 4 bytes.  Return the result.
   57846 **
   57847 ** For most architectures, this is a no-op.
   57848 **
   57849 ** (later):  It is reported to me that the mixed-endian problem
   57850 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
   57851 ** that early versions of GCC stored the two words of a 64-bit
   57852 ** float in the wrong order.  And that error has been propagated
   57853 ** ever since.  The blame is not necessarily with GCC, though.
   57854 ** GCC might have just copying the problem from a prior compiler.
   57855 ** I am also told that newer versions of GCC that follow a different
   57856 ** ABI get the byte order right.
   57857 **
   57858 ** Developers using SQLite on an ARM7 should compile and run their
   57859 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
   57860 ** enabled, some asserts below will ensure that the byte order of
   57861 ** floating point values is correct.
   57862 **
   57863 ** (2007-08-30)  Frank van Vugt has studied this problem closely
   57864 ** and has send his findings to the SQLite developers.  Frank
   57865 ** writes that some Linux kernels offer floating point hardware
   57866 ** emulation that uses only 32-bit mantissas instead of a full
   57867 ** 48-bits as required by the IEEE standard.  (This is the
   57868 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
   57869 ** byte swapping becomes very complicated.  To avoid problems,
   57870 ** the necessary byte swapping is carried out using a 64-bit integer
   57871 ** rather than a 64-bit float.  Frank assures us that the code here
   57872 ** works for him.  We, the developers, have no way to independently
   57873 ** verify this, but Frank seems to know what he is talking about
   57874 ** so we trust him.
   57875 */
   57876 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
   57877 static u64 floatSwap(u64 in){
   57878   union {
   57879     u64 r;
   57880     u32 i[2];
   57881   } u;
   57882   u32 t;
   57883 
   57884   u.r = in;
   57885   t = u.i[0];
   57886   u.i[0] = u.i[1];
   57887   u.i[1] = t;
   57888   return u.r;
   57889 }
   57890 # define swapMixedEndianFloat(X)  X = floatSwap(X)
   57891 #else
   57892 # define swapMixedEndianFloat(X)
   57893 #endif
   57894 
   57895 /*
   57896 ** Write the serialized data blob for the value stored in pMem into
   57897 ** buf. It is assumed that the caller has allocated sufficient space.
   57898 ** Return the number of bytes written.
   57899 **
   57900 ** nBuf is the amount of space left in buf[].  nBuf must always be
   57901 ** large enough to hold the entire field.  Except, if the field is
   57902 ** a blob with a zero-filled tail, then buf[] might be just the right
   57903 ** size to hold everything except for the zero-filled tail.  If buf[]
   57904 ** is only big enough to hold the non-zero prefix, then only write that
   57905 ** prefix into buf[].  But if buf[] is large enough to hold both the
   57906 ** prefix and the tail then write the prefix and set the tail to all
   57907 ** zeros.
   57908 **
   57909 ** Return the number of bytes actually written into buf[].  The number
   57910 ** of bytes in the zero-filled tail is included in the return value only
   57911 ** if those bytes were zeroed in buf[].
   57912 */
   57913 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
   57914   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
   57915   u32 len;
   57916 
   57917   /* Integer and Real */
   57918   if( serial_type<=7 && serial_type>0 ){
   57919     u64 v;
   57920     u32 i;
   57921     if( serial_type==7 ){
   57922       assert( sizeof(v)==sizeof(pMem->r) );
   57923       memcpy(&v, &pMem->r, sizeof(v));
   57924       swapMixedEndianFloat(v);
   57925     }else{
   57926       v = pMem->u.i;
   57927     }
   57928     len = i = sqlite3VdbeSerialTypeLen(serial_type);
   57929     assert( len<=(u32)nBuf );
   57930     while( i-- ){
   57931       buf[i] = (u8)(v&0xFF);
   57932       v >>= 8;
   57933     }
   57934     return len;
   57935   }
   57936 
   57937   /* String or blob */
   57938   if( serial_type>=12 ){
   57939     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
   57940              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
   57941     assert( pMem->n<=nBuf );
   57942     len = pMem->n;
   57943     memcpy(buf, pMem->z, len);
   57944     if( pMem->flags & MEM_Zero ){
   57945       len += pMem->u.nZero;
   57946       assert( nBuf>=0 );
   57947       if( len > (u32)nBuf ){
   57948         len = (u32)nBuf;
   57949       }
   57950       memset(&buf[pMem->n], 0, len-pMem->n);
   57951     }
   57952     return len;
   57953   }
   57954 
   57955   /* NULL or constants 0 or 1 */
   57956   return 0;
   57957 }
   57958 
   57959 /*
   57960 ** Deserialize the data blob pointed to by buf as serial type serial_type
   57961 ** and store the result in pMem.  Return the number of bytes read.
   57962 */
   57963 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
   57964   const unsigned char *buf,     /* Buffer to deserialize from */
   57965   u32 serial_type,              /* Serial type to deserialize */
   57966   Mem *pMem                     /* Memory cell to write value into */
   57967 ){
   57968   switch( serial_type ){
   57969     case 10:   /* Reserved for future use */
   57970     case 11:   /* Reserved for future use */
   57971     case 0: {  /* NULL */
   57972       pMem->flags = MEM_Null;
   57973       break;
   57974     }
   57975     case 1: { /* 1-byte signed integer */
   57976       pMem->u.i = (signed char)buf[0];
   57977       pMem->flags = MEM_Int;
   57978       return 1;
   57979     }
   57980     case 2: { /* 2-byte signed integer */
   57981       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
   57982       pMem->flags = MEM_Int;
   57983       return 2;
   57984     }
   57985     case 3: { /* 3-byte signed integer */
   57986       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
   57987       pMem->flags = MEM_Int;
   57988       return 3;
   57989     }
   57990     case 4: { /* 4-byte signed integer */
   57991       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   57992       pMem->flags = MEM_Int;
   57993       return 4;
   57994     }
   57995     case 5: { /* 6-byte signed integer */
   57996       u64 x = (((signed char)buf[0])<<8) | buf[1];
   57997       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
   57998       x = (x<<32) | y;
   57999       pMem->u.i = *(i64*)&x;
   58000       pMem->flags = MEM_Int;
   58001       return 6;
   58002     }
   58003     case 6:   /* 8-byte signed integer */
   58004     case 7: { /* IEEE floating point */
   58005       u64 x;
   58006       u32 y;
   58007 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
   58008       /* Verify that integers and floating point values use the same
   58009       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
   58010       ** defined that 64-bit floating point values really are mixed
   58011       ** endian.
   58012       */
   58013       static const u64 t1 = ((u64)0x3ff00000)<<32;
   58014       static const double r1 = 1.0;
   58015       u64 t2 = t1;
   58016       swapMixedEndianFloat(t2);
   58017       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
   58018 #endif
   58019 
   58020       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
   58021       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
   58022       x = (x<<32) | y;
   58023       if( serial_type==6 ){
   58024         pMem->u.i = *(i64*)&x;
   58025         pMem->flags = MEM_Int;
   58026       }else{
   58027         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
   58028         swapMixedEndianFloat(x);
   58029         memcpy(&pMem->r, &x, sizeof(x));
   58030         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
   58031       }
   58032       return 8;
   58033     }
   58034     case 8:    /* Integer 0 */
   58035     case 9: {  /* Integer 1 */
   58036       pMem->u.i = serial_type-8;
   58037       pMem->flags = MEM_Int;
   58038       return 0;
   58039     }
   58040     default: {
   58041       u32 len = (serial_type-12)/2;
   58042       pMem->z = (char *)buf;
   58043       pMem->n = len;
   58044       pMem->xDel = 0;
   58045       if( serial_type&0x01 ){
   58046         pMem->flags = MEM_Str | MEM_Ephem;
   58047       }else{
   58048         pMem->flags = MEM_Blob | MEM_Ephem;
   58049       }
   58050       return len;
   58051     }
   58052   }
   58053   return 0;
   58054 }
   58055 
   58056 
   58057 /*
   58058 ** Given the nKey-byte encoding of a record in pKey[], parse the
   58059 ** record into a UnpackedRecord structure.  Return a pointer to
   58060 ** that structure.
   58061 **
   58062 ** The calling function might provide szSpace bytes of memory
   58063 ** space at pSpace.  This space can be used to hold the returned
   58064 ** VDbeParsedRecord structure if it is large enough.  If it is
   58065 ** not big enough, space is obtained from sqlite3_malloc().
   58066 **
   58067 ** The returned structure should be closed by a call to
   58068 ** sqlite3VdbeDeleteUnpackedRecord().
   58069 */
   58070 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
   58071   KeyInfo *pKeyInfo,     /* Information about the record format */
   58072   int nKey,              /* Size of the binary record */
   58073   const void *pKey,      /* The binary record */
   58074   char *pSpace,          /* Unaligned space available to hold the object */
   58075   int szSpace            /* Size of pSpace[] in bytes */
   58076 ){
   58077   const unsigned char *aKey = (const unsigned char *)pKey;
   58078   UnpackedRecord *p;  /* The unpacked record that we will return */
   58079   int nByte;          /* Memory space needed to hold p, in bytes */
   58080   int d;
   58081   u32 idx;
   58082   u16 u;              /* Unsigned loop counter */
   58083   u32 szHdr;
   58084   Mem *pMem;
   58085   int nOff;           /* Increase pSpace by this much to 8-byte align it */
   58086 
   58087   /*
   58088   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
   58089   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
   58090   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
   58091   */
   58092   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
   58093   pSpace += nOff;
   58094   szSpace -= nOff;
   58095   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
   58096   if( nByte>szSpace ){
   58097     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
   58098     if( p==0 ) return 0;
   58099     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
   58100   }else{
   58101     p = (UnpackedRecord*)pSpace;
   58102     p->flags = UNPACKED_NEED_DESTROY;
   58103   }
   58104   p->pKeyInfo = pKeyInfo;
   58105   p->nField = pKeyInfo->nField + 1;
   58106   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
   58107   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
   58108   idx = getVarint32(aKey, szHdr);
   58109   d = szHdr;
   58110   u = 0;
   58111   while( idx<szHdr && u<p->nField && d<=nKey ){
   58112     u32 serial_type;
   58113 
   58114     idx += getVarint32(&aKey[idx], serial_type);
   58115     pMem->enc = pKeyInfo->enc;
   58116     pMem->db = pKeyInfo->db;
   58117     pMem->flags = 0;
   58118     pMem->zMalloc = 0;
   58119     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
   58120     pMem++;
   58121     u++;
   58122   }
   58123   assert( u<=pKeyInfo->nField + 1 );
   58124   p->nField = u;
   58125   return (void*)p;
   58126 }
   58127 
   58128 /*
   58129 ** This routine destroys a UnpackedRecord object.
   58130 */
   58131 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
   58132   int i;
   58133   Mem *pMem;
   58134 
   58135   assert( p!=0 );
   58136   assert( p->flags & UNPACKED_NEED_DESTROY );
   58137   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
   58138     /* The unpacked record is always constructed by the
   58139     ** sqlite3VdbeUnpackRecord() function above, which makes all
   58140     ** strings and blobs static.  And none of the elements are
   58141     ** ever transformed, so there is never anything to delete.
   58142     */
   58143     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
   58144   }
   58145   if( p->flags & UNPACKED_NEED_FREE ){
   58146     sqlite3DbFree(p->pKeyInfo->db, p);
   58147   }
   58148 }
   58149 
   58150 /*
   58151 ** This function compares the two table rows or index records
   58152 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
   58153 ** or positive integer if key1 is less than, equal to or
   58154 ** greater than key2.  The {nKey1, pKey1} key must be a blob
   58155 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
   58156 ** key must be a parsed key such as obtained from
   58157 ** sqlite3VdbeParseRecord.
   58158 **
   58159 ** Key1 and Key2 do not have to contain the same number of fields.
   58160 ** The key with fewer fields is usually compares less than the
   58161 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
   58162 ** and the common prefixes are equal, then key1 is less than key2.
   58163 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
   58164 ** equal, then the keys are considered to be equal and
   58165 ** the parts beyond the common prefix are ignored.
   58166 **
   58167 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
   58168 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
   58169 ** an index key, and thus ends with a rowid value.  The last byte
   58170 ** of the header will therefore be the serial type of the rowid:
   58171 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
   58172 ** The serial type of the final rowid will always be a single byte.
   58173 ** By ignoring this last byte of the header, we force the comparison
   58174 ** to ignore the rowid at the end of key1.
   58175 */
   58176 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
   58177   int nKey1, const void *pKey1, /* Left key */
   58178   UnpackedRecord *pPKey2        /* Right key */
   58179 ){
   58180   int d1;            /* Offset into aKey[] of next data element */
   58181   u32 idx1;          /* Offset into aKey[] of next header element */
   58182   u32 szHdr1;        /* Number of bytes in header */
   58183   int i = 0;
   58184   int nField;
   58185   int rc = 0;
   58186   const unsigned char *aKey1 = (const unsigned char *)pKey1;
   58187   KeyInfo *pKeyInfo;
   58188   Mem mem1;
   58189 
   58190   pKeyInfo = pPKey2->pKeyInfo;
   58191   mem1.enc = pKeyInfo->enc;
   58192   mem1.db = pKeyInfo->db;
   58193   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
   58194   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
   58195 
   58196   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   58197   ** We could initialize it, as shown here, to silence those complaints.
   58198   ** But in fact, mem1.u.i will never actually be used initialized, and doing
   58199   ** the unnecessary initialization has a measurable negative performance
   58200   ** impact, since this routine is a very high runner.  And so, we choose
   58201   ** to ignore the compiler warnings and leave this variable uninitialized.
   58202   */
   58203   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
   58204 
   58205   idx1 = getVarint32(aKey1, szHdr1);
   58206   d1 = szHdr1;
   58207   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
   58208     szHdr1--;
   58209   }
   58210   nField = pKeyInfo->nField;
   58211   while( idx1<szHdr1 && i<pPKey2->nField ){
   58212     u32 serial_type1;
   58213 
   58214     /* Read the serial types for the next element in each key. */
   58215     idx1 += getVarint32( aKey1+idx1, serial_type1 );
   58216     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
   58217 
   58218     /* Extract the values to be compared.
   58219     */
   58220     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
   58221 
   58222     /* Do the comparison
   58223     */
   58224     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
   58225                            i<nField ? pKeyInfo->aColl[i] : 0);
   58226     if( rc!=0 ){
   58227       assert( mem1.zMalloc==0 );  /* See comment below */
   58228 
   58229       /* Invert the result if we are using DESC sort order. */
   58230       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
   58231         rc = -rc;
   58232       }
   58233 
   58234       /* If the PREFIX_SEARCH flag is set and all fields except the final
   58235       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
   58236       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
   58237       ** This is used by the OP_IsUnique opcode.
   58238       */
   58239       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
   58240         assert( idx1==szHdr1 && rc );
   58241         assert( mem1.flags & MEM_Int );
   58242         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
   58243         pPKey2->rowid = mem1.u.i;
   58244       }
   58245 
   58246       return rc;
   58247     }
   58248     i++;
   58249   }
   58250 
   58251   /* No memory allocation is ever used on mem1.  Prove this using
   58252   ** the following assert().  If the assert() fails, it indicates a
   58253   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
   58254   */
   58255   assert( mem1.zMalloc==0 );
   58256 
   58257   /* rc==0 here means that one of the keys ran out of fields and
   58258   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
   58259   ** flag is set, then break the tie by treating key2 as larger.
   58260   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
   58261   ** are considered to be equal.  Otherwise, the longer key is the
   58262   ** larger.  As it happens, the pPKey2 will always be the longer
   58263   ** if there is a difference.
   58264   */
   58265   assert( rc==0 );
   58266   if( pPKey2->flags & UNPACKED_INCRKEY ){
   58267     rc = -1;
   58268   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
   58269     /* Leave rc==0 */
   58270   }else if( idx1<szHdr1 ){
   58271     rc = 1;
   58272   }
   58273   return rc;
   58274 }
   58275 
   58276 
   58277 /*
   58278 ** pCur points at an index entry created using the OP_MakeRecord opcode.
   58279 ** Read the rowid (the last field in the record) and store it in *rowid.
   58280 ** Return SQLITE_OK if everything works, or an error code otherwise.
   58281 **
   58282 ** pCur might be pointing to text obtained from a corrupt database file.
   58283 ** So the content cannot be trusted.  Do appropriate checks on the content.
   58284 */
   58285 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   58286   i64 nCellKey = 0;
   58287   int rc;
   58288   u32 szHdr;        /* Size of the header */
   58289   u32 typeRowid;    /* Serial type of the rowid */
   58290   u32 lenRowid;     /* Size of the rowid */
   58291   Mem m, v;
   58292 
   58293   UNUSED_PARAMETER(db);
   58294 
   58295   /* Get the size of the index entry.  Only indices entries of less
   58296   ** than 2GiB are support - anything large must be database corruption.
   58297   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
   58298   ** this code can safely assume that nCellKey is 32-bits
   58299   */
   58300   assert( sqlite3BtreeCursorIsValid(pCur) );
   58301   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
   58302   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
   58303   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
   58304 
   58305   /* Read in the complete content of the index entry */
   58306   memset(&m, 0, sizeof(m));
   58307   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
   58308   if( rc ){
   58309     return rc;
   58310   }
   58311 
   58312   /* The index entry must begin with a header size */
   58313   (void)getVarint32((u8*)m.z, szHdr);
   58314   testcase( szHdr==3 );
   58315   testcase( szHdr==m.n );
   58316   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
   58317     goto idx_rowid_corruption;
   58318   }
   58319 
   58320   /* The last field of the index should be an integer - the ROWID.
   58321   ** Verify that the last entry really is an integer. */
   58322   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
   58323   testcase( typeRowid==1 );
   58324   testcase( typeRowid==2 );
   58325   testcase( typeRowid==3 );
   58326   testcase( typeRowid==4 );
   58327   testcase( typeRowid==5 );
   58328   testcase( typeRowid==6 );
   58329   testcase( typeRowid==8 );
   58330   testcase( typeRowid==9 );
   58331   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
   58332     goto idx_rowid_corruption;
   58333   }
   58334   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
   58335   testcase( (u32)m.n==szHdr+lenRowid );
   58336   if( unlikely((u32)m.n<szHdr+lenRowid) ){
   58337     goto idx_rowid_corruption;
   58338   }
   58339 
   58340   /* Fetch the integer off the end of the index record */
   58341   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
   58342   *rowid = v.u.i;
   58343   sqlite3VdbeMemRelease(&m);
   58344   return SQLITE_OK;
   58345 
   58346   /* Jump here if database corruption is detected after m has been
   58347   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
   58348 idx_rowid_corruption:
   58349   testcase( m.zMalloc!=0 );
   58350   sqlite3VdbeMemRelease(&m);
   58351   return SQLITE_CORRUPT_BKPT;
   58352 }
   58353 
   58354 /*
   58355 ** Compare the key of the index entry that cursor pC is pointing to against
   58356 ** the key string in pUnpacked.  Write into *pRes a number
   58357 ** that is negative, zero, or positive if pC is less than, equal to,
   58358 ** or greater than pUnpacked.  Return SQLITE_OK on success.
   58359 **
   58360 ** pUnpacked is either created without a rowid or is truncated so that it
   58361 ** omits the rowid at the end.  The rowid at the end of the index entry
   58362 ** is ignored as well.  Hence, this routine only compares the prefixes
   58363 ** of the keys prior to the final rowid, not the entire key.
   58364 */
   58365 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
   58366   VdbeCursor *pC,             /* The cursor to compare against */
   58367   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
   58368   int *res                    /* Write the comparison result here */
   58369 ){
   58370   i64 nCellKey = 0;
   58371   int rc;
   58372   BtCursor *pCur = pC->pCursor;
   58373   Mem m;
   58374 
   58375   assert( sqlite3BtreeCursorIsValid(pCur) );
   58376   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
   58377   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
   58378   /* nCellKey will always be between 0 and 0xffffffff because of the say
   58379   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
   58380   if( nCellKey<=0 || nCellKey>0x7fffffff ){
   58381     *res = 0;
   58382     return SQLITE_CORRUPT_BKPT;
   58383   }
   58384   memset(&m, 0, sizeof(m));
   58385   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
   58386   if( rc ){
   58387     return rc;
   58388   }
   58389   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
   58390   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
   58391   sqlite3VdbeMemRelease(&m);
   58392   return SQLITE_OK;
   58393 }
   58394 
   58395 /*
   58396 ** This routine sets the value to be returned by subsequent calls to
   58397 ** sqlite3_changes() on the database handle 'db'.
   58398 */
   58399 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
   58400   assert( sqlite3_mutex_held(db->mutex) );
   58401   db->nChange = nChange;
   58402   db->nTotalChange += nChange;
   58403 }
   58404 
   58405 /*
   58406 ** Set a flag in the vdbe to update the change counter when it is finalised
   58407 ** or reset.
   58408 */
   58409 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
   58410   v->changeCntOn = 1;
   58411 }
   58412 
   58413 /*
   58414 ** Mark every prepared statement associated with a database connection
   58415 ** as expired.
   58416 **
   58417 ** An expired statement means that recompilation of the statement is
   58418 ** recommend.  Statements expire when things happen that make their
   58419 ** programs obsolete.  Removing user-defined functions or collating
   58420 ** sequences, or changing an authorization function are the types of
   58421 ** things that make prepared statements obsolete.
   58422 */
   58423 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
   58424   Vdbe *p;
   58425   for(p = db->pVdbe; p; p=p->pNext){
   58426     p->expired = 1;
   58427   }
   58428 }
   58429 
   58430 /*
   58431 ** Return the database associated with the Vdbe.
   58432 */
   58433 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
   58434   return v->db;
   58435 }
   58436 
   58437 /*
   58438 ** Return a pointer to an sqlite3_value structure containing the value bound
   58439 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
   58440 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
   58441 ** constants) to the value before returning it.
   58442 **
   58443 ** The returned value must be freed by the caller using sqlite3ValueFree().
   58444 */
   58445 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
   58446   assert( iVar>0 );
   58447   if( v ){
   58448     Mem *pMem = &v->aVar[iVar-1];
   58449     if( 0==(pMem->flags & MEM_Null) ){
   58450       sqlite3_value *pRet = sqlite3ValueNew(v->db);
   58451       if( pRet ){
   58452         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
   58453         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
   58454         sqlite3VdbeMemStoreType((Mem *)pRet);
   58455       }
   58456       return pRet;
   58457     }
   58458   }
   58459   return 0;
   58460 }
   58461 
   58462 /*
   58463 ** Configure SQL variable iVar so that binding a new value to it signals
   58464 ** to sqlite3_reoptimize() that re-preparing the statement may result
   58465 ** in a better query plan.
   58466 */
   58467 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
   58468   assert( iVar>0 );
   58469   if( iVar>32 ){
   58470     v->expmask = 0xffffffff;
   58471   }else{
   58472     v->expmask |= ((u32)1 << (iVar-1));
   58473   }
   58474 }
   58475 
   58476 /************** End of vdbeaux.c *********************************************/
   58477 /************** Begin file vdbeapi.c *****************************************/
   58478 /*
   58479 ** 2004 May 26
   58480 **
   58481 ** The author disclaims copyright to this source code.  In place of
   58482 ** a legal notice, here is a blessing:
   58483 **
   58484 **    May you do good and not evil.
   58485 **    May you find forgiveness for yourself and forgive others.
   58486 **    May you share freely, never taking more than you give.
   58487 **
   58488 *************************************************************************
   58489 **
   58490 ** This file contains code use to implement APIs that are part of the
   58491 ** VDBE.
   58492 */
   58493 
   58494 #ifndef SQLITE_OMIT_DEPRECATED
   58495 /*
   58496 ** Return TRUE (non-zero) of the statement supplied as an argument needs
   58497 ** to be recompiled.  A statement needs to be recompiled whenever the
   58498 ** execution environment changes in a way that would alter the program
   58499 ** that sqlite3_prepare() generates.  For example, if new functions or
   58500 ** collating sequences are registered or if an authorizer function is
   58501 ** added or changed.
   58502 */
   58503 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
   58504   Vdbe *p = (Vdbe*)pStmt;
   58505   return p==0 || p->expired;
   58506 }
   58507 #endif
   58508 
   58509 /*
   58510 ** Check on a Vdbe to make sure it has not been finalized.  Log
   58511 ** an error and return true if it has been finalized (or is otherwise
   58512 ** invalid).  Return false if it is ok.
   58513 */
   58514 static int vdbeSafety(Vdbe *p){
   58515   if( p->db==0 ){
   58516     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
   58517     return 1;
   58518   }else{
   58519     return 0;
   58520   }
   58521 }
   58522 static int vdbeSafetyNotNull(Vdbe *p){
   58523   if( p==0 ){
   58524     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
   58525     return 1;
   58526   }else{
   58527     return vdbeSafety(p);
   58528   }
   58529 }
   58530 
   58531 /*
   58532 ** The following routine destroys a virtual machine that is created by
   58533 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
   58534 ** success/failure code that describes the result of executing the virtual
   58535 ** machine.
   58536 **
   58537 ** This routine sets the error code and string returned by
   58538 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   58539 */
   58540 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
   58541   int rc;
   58542   if( pStmt==0 ){
   58543     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
   58544     ** pointer is a harmless no-op. */
   58545     rc = SQLITE_OK;
   58546   }else{
   58547     Vdbe *v = (Vdbe*)pStmt;
   58548     sqlite3 *db = v->db;
   58549 #if SQLITE_THREADSAFE
   58550     sqlite3_mutex *mutex;
   58551 #endif
   58552     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
   58553 #if SQLITE_THREADSAFE
   58554     mutex = v->db->mutex;
   58555 #endif
   58556     sqlite3_mutex_enter(mutex);
   58557     rc = sqlite3VdbeFinalize(v);
   58558     rc = sqlite3ApiExit(db, rc);
   58559     sqlite3_mutex_leave(mutex);
   58560   }
   58561   return rc;
   58562 }
   58563 
   58564 /*
   58565 ** Terminate the current execution of an SQL statement and reset it
   58566 ** back to its starting state so that it can be reused. A success code from
   58567 ** the prior execution is returned.
   58568 **
   58569 ** This routine sets the error code and string returned by
   58570 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
   58571 */
   58572 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
   58573   int rc;
   58574   if( pStmt==0 ){
   58575     rc = SQLITE_OK;
   58576   }else{
   58577     Vdbe *v = (Vdbe*)pStmt;
   58578     sqlite3_mutex_enter(v->db->mutex);
   58579     rc = sqlite3VdbeReset(v);
   58580     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
   58581     assert( (rc & (v->db->errMask))==rc );
   58582     rc = sqlite3ApiExit(v->db, rc);
   58583     sqlite3_mutex_leave(v->db->mutex);
   58584   }
   58585   return rc;
   58586 }
   58587 
   58588 /*
   58589 ** Set all the parameters in the compiled SQL statement to NULL.
   58590 */
   58591 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
   58592   int i;
   58593   int rc = SQLITE_OK;
   58594   Vdbe *p = (Vdbe*)pStmt;
   58595 #if SQLITE_THREADSAFE
   58596   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
   58597 #endif
   58598   sqlite3_mutex_enter(mutex);
   58599   for(i=0; i<p->nVar; i++){
   58600     sqlite3VdbeMemRelease(&p->aVar[i]);
   58601     p->aVar[i].flags = MEM_Null;
   58602   }
   58603   if( p->isPrepareV2 && p->expmask ){
   58604     p->expired = 1;
   58605   }
   58606   sqlite3_mutex_leave(mutex);
   58607   return rc;
   58608 }
   58609 
   58610 
   58611 /**************************** sqlite3_value_  *******************************
   58612 ** The following routines extract information from a Mem or sqlite3_value
   58613 ** structure.
   58614 */
   58615 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
   58616   Mem *p = (Mem*)pVal;
   58617   if( p->flags & (MEM_Blob|MEM_Str) ){
   58618     sqlite3VdbeMemExpandBlob(p);
   58619     p->flags &= ~MEM_Str;
   58620     p->flags |= MEM_Blob;
   58621     return p->n ? p->z : 0;
   58622   }else{
   58623     return sqlite3_value_text(pVal);
   58624   }
   58625 }
   58626 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
   58627   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
   58628 }
   58629 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
   58630   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
   58631 }
   58632 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
   58633   return sqlite3VdbeRealValue((Mem*)pVal);
   58634 }
   58635 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
   58636   return (int)sqlite3VdbeIntValue((Mem*)pVal);
   58637 }
   58638 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
   58639   return sqlite3VdbeIntValue((Mem*)pVal);
   58640 }
   58641 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
   58642   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
   58643 }
   58644 #ifndef SQLITE_OMIT_UTF16
   58645 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
   58646   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
   58647 }
   58648 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
   58649   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
   58650 }
   58651 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
   58652   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
   58653 }
   58654 #endif /* SQLITE_OMIT_UTF16 */
   58655 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
   58656   return pVal->type;
   58657 }
   58658 
   58659 /**************************** sqlite3_result_  *******************************
   58660 ** The following routines are used by user-defined functions to specify
   58661 ** the function result.
   58662 **
   58663 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
   58664 ** result as a string or blob but if the string or blob is too large, it
   58665 ** then sets the error code to SQLITE_TOOBIG
   58666 */
   58667 static void setResultStrOrError(
   58668   sqlite3_context *pCtx,  /* Function context */
   58669   const char *z,          /* String pointer */
   58670   int n,                  /* Bytes in string, or negative */
   58671   u8 enc,                 /* Encoding of z.  0 for BLOBs */
   58672   void (*xDel)(void*)     /* Destructor function */
   58673 ){
   58674   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
   58675     sqlite3_result_error_toobig(pCtx);
   58676   }
   58677 }
   58678 SQLITE_API void sqlite3_result_blob(
   58679   sqlite3_context *pCtx,
   58680   const void *z,
   58681   int n,
   58682   void (*xDel)(void *)
   58683 ){
   58684   assert( n>=0 );
   58685   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58686   setResultStrOrError(pCtx, z, n, 0, xDel);
   58687 }
   58688 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
   58689   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58690   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
   58691 }
   58692 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
   58693   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58694   pCtx->isError = SQLITE_ERROR;
   58695   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
   58696 }
   58697 #ifndef SQLITE_OMIT_UTF16
   58698 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
   58699   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58700   pCtx->isError = SQLITE_ERROR;
   58701   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
   58702 }
   58703 #endif
   58704 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
   58705   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58706   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
   58707 }
   58708 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
   58709   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58710   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
   58711 }
   58712 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
   58713   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58714   sqlite3VdbeMemSetNull(&pCtx->s);
   58715 }
   58716 SQLITE_API void sqlite3_result_text(
   58717   sqlite3_context *pCtx,
   58718   const char *z,
   58719   int n,
   58720   void (*xDel)(void *)
   58721 ){
   58722   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58723   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
   58724 }
   58725 #ifndef SQLITE_OMIT_UTF16
   58726 SQLITE_API void sqlite3_result_text16(
   58727   sqlite3_context *pCtx,
   58728   const void *z,
   58729   int n,
   58730   void (*xDel)(void *)
   58731 ){
   58732   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58733   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
   58734 }
   58735 SQLITE_API void sqlite3_result_text16be(
   58736   sqlite3_context *pCtx,
   58737   const void *z,
   58738   int n,
   58739   void (*xDel)(void *)
   58740 ){
   58741   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58742   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
   58743 }
   58744 SQLITE_API void sqlite3_result_text16le(
   58745   sqlite3_context *pCtx,
   58746   const void *z,
   58747   int n,
   58748   void (*xDel)(void *)
   58749 ){
   58750   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58751   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
   58752 }
   58753 #endif /* SQLITE_OMIT_UTF16 */
   58754 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
   58755   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58756   sqlite3VdbeMemCopy(&pCtx->s, pValue);
   58757 }
   58758 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
   58759   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58760   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
   58761 }
   58762 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   58763   pCtx->isError = errCode;
   58764   if( pCtx->s.flags & MEM_Null ){
   58765     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
   58766                          SQLITE_UTF8, SQLITE_STATIC);
   58767   }
   58768 }
   58769 
   58770 /* Force an SQLITE_TOOBIG error. */
   58771 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   58772   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58773   pCtx->isError = SQLITE_TOOBIG;
   58774   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
   58775                        SQLITE_UTF8, SQLITE_STATIC);
   58776 }
   58777 
   58778 /* An SQLITE_NOMEM error. */
   58779 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   58780   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   58781   sqlite3VdbeMemSetNull(&pCtx->s);
   58782   pCtx->isError = SQLITE_NOMEM;
   58783   pCtx->s.db->mallocFailed = 1;
   58784 }
   58785 
   58786 /*
   58787 ** This function is called after a transaction has been committed. It
   58788 ** invokes callbacks registered with sqlite3_wal_hook() as required.
   58789 */
   58790 static int doWalCallbacks(sqlite3 *db){
   58791   int rc = SQLITE_OK;
   58792 #ifndef SQLITE_OMIT_WAL
   58793   int i;
   58794   for(i=0; i<db->nDb; i++){
   58795     Btree *pBt = db->aDb[i].pBt;
   58796     if( pBt ){
   58797       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
   58798       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
   58799         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
   58800       }
   58801     }
   58802   }
   58803 #endif
   58804   return rc;
   58805 }
   58806 
   58807 /*
   58808 ** Execute the statement pStmt, either until a row of data is ready, the
   58809 ** statement is completely executed or an error occurs.
   58810 **
   58811 ** This routine implements the bulk of the logic behind the sqlite_step()
   58812 ** API.  The only thing omitted is the automatic recompile if a
   58813 ** schema change has occurred.  That detail is handled by the
   58814 ** outer sqlite3_step() wrapper procedure.
   58815 */
   58816 static int sqlite3Step(Vdbe *p){
   58817   sqlite3 *db;
   58818   int rc;
   58819 
   58820   assert(p);
   58821   if( p->magic!=VDBE_MAGIC_RUN ){
   58822     /* We used to require that sqlite3_reset() be called before retrying
   58823     ** sqlite3_step() after any error.  But after 3.6.23, we changed this
   58824     ** so that sqlite3_reset() would be called automatically instead of
   58825     ** throwing the error.
   58826     */
   58827     sqlite3_reset((sqlite3_stmt*)p);
   58828   }
   58829 
   58830   /* Check that malloc() has not failed. If it has, return early. */
   58831   db = p->db;
   58832   if( db->mallocFailed ){
   58833     p->rc = SQLITE_NOMEM;
   58834     return SQLITE_NOMEM;
   58835   }
   58836 
   58837   if( p->pc<=0 && p->expired ){
   58838     p->rc = SQLITE_SCHEMA;
   58839     rc = SQLITE_ERROR;
   58840     goto end_of_step;
   58841   }
   58842   if( p->pc<0 ){
   58843     /* If there are no other statements currently running, then
   58844     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
   58845     ** from interrupting a statement that has not yet started.
   58846     */
   58847     if( db->activeVdbeCnt==0 ){
   58848       db->u1.isInterrupted = 0;
   58849     }
   58850 
   58851     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
   58852 
   58853 #ifndef SQLITE_OMIT_TRACE
   58854     if( db->xProfile && !db->init.busy ){
   58855       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
   58856     }
   58857 #endif
   58858 
   58859     db->activeVdbeCnt++;
   58860     if( p->readOnly==0 ) db->writeVdbeCnt++;
   58861     p->pc = 0;
   58862   }
   58863 #ifndef SQLITE_OMIT_EXPLAIN
   58864   if( p->explain ){
   58865     rc = sqlite3VdbeList(p);
   58866   }else
   58867 #endif /* SQLITE_OMIT_EXPLAIN */
   58868   {
   58869     rc = sqlite3VdbeExec(p);
   58870   }
   58871 
   58872 #ifndef SQLITE_OMIT_TRACE
   58873   /* Invoke the profile callback if there is one
   58874   */
   58875   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
   58876     sqlite3_int64 iNow;
   58877     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
   58878     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
   58879   }
   58880 #endif
   58881 
   58882   if( rc==SQLITE_DONE ){
   58883     assert( p->rc==SQLITE_OK );
   58884     p->rc = doWalCallbacks(db);
   58885     if( p->rc!=SQLITE_OK ){
   58886       rc = SQLITE_ERROR;
   58887     }
   58888   }
   58889 
   58890   db->errCode = rc;
   58891   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
   58892     p->rc = SQLITE_NOMEM;
   58893   }
   58894 end_of_step:
   58895   /* At this point local variable rc holds the value that should be
   58896   ** returned if this statement was compiled using the legacy
   58897   ** sqlite3_prepare() interface. According to the docs, this can only
   58898   ** be one of the values in the first assert() below. Variable p->rc
   58899   ** contains the value that would be returned if sqlite3_finalize()
   58900   ** were called on statement p.
   58901   */
   58902   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
   58903        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
   58904   );
   58905   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
   58906   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
   58907     /* If this statement was prepared using sqlite3_prepare_v2(), and an
   58908     ** error has occured, then return the error code in p->rc to the
   58909     ** caller. Set the error code in the database handle to the same value.
   58910     */
   58911     rc = db->errCode = p->rc;
   58912   }
   58913   return (rc&db->errMask);
   58914 }
   58915 
   58916 /*
   58917 ** This is the top-level implementation of sqlite3_step().  Call
   58918 ** sqlite3Step() to do most of the work.  If a schema error occurs,
   58919 ** call sqlite3Reprepare() and try again.
   58920 */
   58921 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
   58922   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
   58923   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
   58924   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
   58925   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
   58926   sqlite3 *db;             /* The database connection */
   58927 
   58928   if( vdbeSafetyNotNull(v) ){
   58929     return SQLITE_MISUSE_BKPT;
   58930   }
   58931   db = v->db;
   58932   sqlite3_mutex_enter(db->mutex);
   58933   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
   58934          && cnt++ < 5
   58935          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
   58936     sqlite3_reset(pStmt);
   58937     v->expired = 0;
   58938   }
   58939   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
   58940     /* This case occurs after failing to recompile an sql statement.
   58941     ** The error message from the SQL compiler has already been loaded
   58942     ** into the database handle. This block copies the error message
   58943     ** from the database handle into the statement and sets the statement
   58944     ** program counter to 0 to ensure that when the statement is
   58945     ** finalized or reset the parser error message is available via
   58946     ** sqlite3_errmsg() and sqlite3_errcode().
   58947     */
   58948     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
   58949     sqlite3DbFree(db, v->zErrMsg);
   58950     if( !db->mallocFailed ){
   58951       v->zErrMsg = sqlite3DbStrDup(db, zErr);
   58952       v->rc = rc2;
   58953     } else {
   58954       v->zErrMsg = 0;
   58955       v->rc = rc = SQLITE_NOMEM;
   58956     }
   58957   }
   58958   rc = sqlite3ApiExit(db, rc);
   58959   sqlite3_mutex_leave(db->mutex);
   58960   return rc;
   58961 }
   58962 
   58963 /*
   58964 ** Extract the user data from a sqlite3_context structure and return a
   58965 ** pointer to it.
   58966 */
   58967 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
   58968   assert( p && p->pFunc );
   58969   return p->pFunc->pUserData;
   58970 }
   58971 
   58972 /*
   58973 ** Extract the user data from a sqlite3_context structure and return a
   58974 ** pointer to it.
   58975 **
   58976 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
   58977 ** returns a copy of the pointer to the database connection (the 1st
   58978 ** parameter) of the sqlite3_create_function() and
   58979 ** sqlite3_create_function16() routines that originally registered the
   58980 ** application defined function.
   58981 */
   58982 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
   58983   assert( p && p->pFunc );
   58984   return p->s.db;
   58985 }
   58986 
   58987 /*
   58988 ** The following is the implementation of an SQL function that always
   58989 ** fails with an error message stating that the function is used in the
   58990 ** wrong context.  The sqlite3_overload_function() API might construct
   58991 ** SQL function that use this routine so that the functions will exist
   58992 ** for name resolution but are actually overloaded by the xFindFunction
   58993 ** method of virtual tables.
   58994 */
   58995 SQLITE_PRIVATE void sqlite3InvalidFunction(
   58996   sqlite3_context *context,  /* The function calling context */
   58997   int NotUsed,               /* Number of arguments to the function */
   58998   sqlite3_value **NotUsed2   /* Value of each argument */
   58999 ){
   59000   const char *zName = context->pFunc->zName;
   59001   char *zErr;
   59002   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   59003   zErr = sqlite3_mprintf(
   59004       "unable to use function %s in the requested context", zName);
   59005   sqlite3_result_error(context, zErr, -1);
   59006   sqlite3_free(zErr);
   59007 }
   59008 
   59009 /*
   59010 ** Allocate or return the aggregate context for a user function.  A new
   59011 ** context is allocated on the first call.  Subsequent calls return the
   59012 ** same context that was returned on prior calls.
   59013 */
   59014 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
   59015   Mem *pMem;
   59016   assert( p && p->pFunc && p->pFunc->xStep );
   59017   assert( sqlite3_mutex_held(p->s.db->mutex) );
   59018   pMem = p->pMem;
   59019   testcase( nByte<0 );
   59020   if( (pMem->flags & MEM_Agg)==0 ){
   59021     if( nByte<=0 ){
   59022       sqlite3VdbeMemReleaseExternal(pMem);
   59023       pMem->flags = MEM_Null;
   59024       pMem->z = 0;
   59025     }else{
   59026       sqlite3VdbeMemGrow(pMem, nByte, 0);
   59027       pMem->flags = MEM_Agg;
   59028       pMem->u.pDef = p->pFunc;
   59029       if( pMem->z ){
   59030         memset(pMem->z, 0, nByte);
   59031       }
   59032     }
   59033   }
   59034   return (void*)pMem->z;
   59035 }
   59036 
   59037 /*
   59038 ** Return the auxilary data pointer, if any, for the iArg'th argument to
   59039 ** the user-function defined by pCtx.
   59040 */
   59041 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
   59042   VdbeFunc *pVdbeFunc;
   59043 
   59044   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   59045   pVdbeFunc = pCtx->pVdbeFunc;
   59046   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
   59047     return 0;
   59048   }
   59049   return pVdbeFunc->apAux[iArg].pAux;
   59050 }
   59051 
   59052 /*
   59053 ** Set the auxilary data pointer and delete function, for the iArg'th
   59054 ** argument to the user-function defined by pCtx. Any previous value is
   59055 ** deleted by calling the delete function specified when it was set.
   59056 */
   59057 SQLITE_API void sqlite3_set_auxdata(
   59058   sqlite3_context *pCtx,
   59059   int iArg,
   59060   void *pAux,
   59061   void (*xDelete)(void*)
   59062 ){
   59063   struct AuxData *pAuxData;
   59064   VdbeFunc *pVdbeFunc;
   59065   if( iArg<0 ) goto failed;
   59066 
   59067   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
   59068   pVdbeFunc = pCtx->pVdbeFunc;
   59069   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
   59070     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
   59071     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
   59072     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
   59073     if( !pVdbeFunc ){
   59074       goto failed;
   59075     }
   59076     pCtx->pVdbeFunc = pVdbeFunc;
   59077     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
   59078     pVdbeFunc->nAux = iArg+1;
   59079     pVdbeFunc->pFunc = pCtx->pFunc;
   59080   }
   59081 
   59082   pAuxData = &pVdbeFunc->apAux[iArg];
   59083   if( pAuxData->pAux && pAuxData->xDelete ){
   59084     pAuxData->xDelete(pAuxData->pAux);
   59085   }
   59086   pAuxData->pAux = pAux;
   59087   pAuxData->xDelete = xDelete;
   59088   return;
   59089 
   59090 failed:
   59091   if( xDelete ){
   59092     xDelete(pAux);
   59093   }
   59094 }
   59095 
   59096 #ifndef SQLITE_OMIT_DEPRECATED
   59097 /*
   59098 ** Return the number of times the Step function of a aggregate has been
   59099 ** called.
   59100 **
   59101 ** This function is deprecated.  Do not use it for new code.  It is
   59102 ** provide only to avoid breaking legacy code.  New aggregate function
   59103 ** implementations should keep their own counts within their aggregate
   59104 ** context.
   59105 */
   59106 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
   59107   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
   59108   return p->pMem->n;
   59109 }
   59110 #endif
   59111 
   59112 /*
   59113 ** Return the number of columns in the result set for the statement pStmt.
   59114 */
   59115 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
   59116   Vdbe *pVm = (Vdbe *)pStmt;
   59117   return pVm ? pVm->nResColumn : 0;
   59118 }
   59119 
   59120 /*
   59121 ** Return the number of values available from the current row of the
   59122 ** currently executing statement pStmt.
   59123 */
   59124 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
   59125   Vdbe *pVm = (Vdbe *)pStmt;
   59126   if( pVm==0 || pVm->pResultSet==0 ) return 0;
   59127   return pVm->nResColumn;
   59128 }
   59129 
   59130 
   59131 /*
   59132 ** Check to see if column iCol of the given statement is valid.  If
   59133 ** it is, return a pointer to the Mem for the value of that column.
   59134 ** If iCol is not valid, return a pointer to a Mem which has a value
   59135 ** of NULL.
   59136 */
   59137 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
   59138   Vdbe *pVm;
   59139   int vals;
   59140   Mem *pOut;
   59141 
   59142   pVm = (Vdbe *)pStmt;
   59143   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
   59144     sqlite3_mutex_enter(pVm->db->mutex);
   59145     vals = sqlite3_data_count(pStmt);
   59146     pOut = &pVm->pResultSet[i];
   59147   }else{
   59148     /* If the value passed as the second argument is out of range, return
   59149     ** a pointer to the following static Mem object which contains the
   59150     ** value SQL NULL. Even though the Mem structure contains an element
   59151     ** of type i64, on certain architecture (x86) with certain compiler
   59152     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
   59153     ** instead of an 8-byte one. This all works fine, except that when
   59154     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
   59155     ** that a Mem structure is located on an 8-byte boundary. To prevent
   59156     ** this assert() from failing, when building with SQLITE_DEBUG defined
   59157     ** using gcc, force nullMem to be 8-byte aligned using the magical
   59158     ** __attribute__((aligned(8))) macro.  */
   59159     static const Mem nullMem
   59160 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
   59161       __attribute__((aligned(8)))
   59162 #endif
   59163       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
   59164 
   59165     if( pVm && ALWAYS(pVm->db) ){
   59166       sqlite3_mutex_enter(pVm->db->mutex);
   59167       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
   59168     }
   59169     pOut = (Mem*)&nullMem;
   59170   }
   59171   return pOut;
   59172 }
   59173 
   59174 /*
   59175 ** This function is called after invoking an sqlite3_value_XXX function on a
   59176 ** column value (i.e. a value returned by evaluating an SQL expression in the
   59177 ** select list of a SELECT statement) that may cause a malloc() failure. If
   59178 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
   59179 ** code of statement pStmt set to SQLITE_NOMEM.
   59180 **
   59181 ** Specifically, this is called from within:
   59182 **
   59183 **     sqlite3_column_int()
   59184 **     sqlite3_column_int64()
   59185 **     sqlite3_column_text()
   59186 **     sqlite3_column_text16()
   59187 **     sqlite3_column_real()
   59188 **     sqlite3_column_bytes()
   59189 **     sqlite3_column_bytes16()
   59190 **     sqiite3_column_blob()
   59191 */
   59192 static void columnMallocFailure(sqlite3_stmt *pStmt)
   59193 {
   59194   /* If malloc() failed during an encoding conversion within an
   59195   ** sqlite3_column_XXX API, then set the return code of the statement to
   59196   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
   59197   ** and _finalize() will return NOMEM.
   59198   */
   59199   Vdbe *p = (Vdbe *)pStmt;
   59200   if( p ){
   59201     p->rc = sqlite3ApiExit(p->db, p->rc);
   59202     sqlite3_mutex_leave(p->db->mutex);
   59203   }
   59204 }
   59205 
   59206 /**************************** sqlite3_column_  *******************************
   59207 ** The following routines are used to access elements of the current row
   59208 ** in the result set.
   59209 */
   59210 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   59211   const void *val;
   59212   val = sqlite3_value_blob( columnMem(pStmt,i) );
   59213   /* Even though there is no encoding conversion, value_blob() might
   59214   ** need to call malloc() to expand the result of a zeroblob()
   59215   ** expression.
   59216   */
   59217   columnMallocFailure(pStmt);
   59218   return val;
   59219 }
   59220 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
   59221   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
   59222   columnMallocFailure(pStmt);
   59223   return val;
   59224 }
   59225 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
   59226   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
   59227   columnMallocFailure(pStmt);
   59228   return val;
   59229 }
   59230 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
   59231   double val = sqlite3_value_double( columnMem(pStmt,i) );
   59232   columnMallocFailure(pStmt);
   59233   return val;
   59234 }
   59235 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
   59236   int val = sqlite3_value_int( columnMem(pStmt,i) );
   59237   columnMallocFailure(pStmt);
   59238   return val;
   59239 }
   59240 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
   59241   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
   59242   columnMallocFailure(pStmt);
   59243   return val;
   59244 }
   59245 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
   59246   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
   59247   columnMallocFailure(pStmt);
   59248   return val;
   59249 }
   59250 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
   59251   Mem *pOut = columnMem(pStmt, i);
   59252   if( pOut->flags&MEM_Static ){
   59253     pOut->flags &= ~MEM_Static;
   59254     pOut->flags |= MEM_Ephem;
   59255   }
   59256   columnMallocFailure(pStmt);
   59257   return (sqlite3_value *)pOut;
   59258 }
   59259 #ifndef SQLITE_OMIT_UTF16
   59260 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
   59261   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
   59262   columnMallocFailure(pStmt);
   59263   return val;
   59264 }
   59265 #endif /* SQLITE_OMIT_UTF16 */
   59266 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
   59267   int iType = sqlite3_value_type( columnMem(pStmt,i) );
   59268   columnMallocFailure(pStmt);
   59269   return iType;
   59270 }
   59271 
   59272 /* The following function is experimental and subject to change or
   59273 ** removal */
   59274 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
   59275 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
   59276 **}
   59277 */
   59278 
   59279 /*
   59280 ** Convert the N-th element of pStmt->pColName[] into a string using
   59281 ** xFunc() then return that string.  If N is out of range, return 0.
   59282 **
   59283 ** There are up to 5 names for each column.  useType determines which
   59284 ** name is returned.  Here are the names:
   59285 **
   59286 **    0      The column name as it should be displayed for output
   59287 **    1      The datatype name for the column
   59288 **    2      The name of the database that the column derives from
   59289 **    3      The name of the table that the column derives from
   59290 **    4      The name of the table column that the result column derives from
   59291 **
   59292 ** If the result is not a simple column reference (if it is an expression
   59293 ** or a constant) then useTypes 2, 3, and 4 return NULL.
   59294 */
   59295 static const void *columnName(
   59296   sqlite3_stmt *pStmt,
   59297   int N,
   59298   const void *(*xFunc)(Mem*),
   59299   int useType
   59300 ){
   59301   const void *ret = 0;
   59302   Vdbe *p = (Vdbe *)pStmt;
   59303   int n;
   59304   sqlite3 *db = p->db;
   59305 
   59306   assert( db!=0 );
   59307   n = sqlite3_column_count(pStmt);
   59308   if( N<n && N>=0 ){
   59309     N += useType*n;
   59310     sqlite3_mutex_enter(db->mutex);
   59311     assert( db->mallocFailed==0 );
   59312     ret = xFunc(&p->aColName[N]);
   59313      /* A malloc may have failed inside of the xFunc() call. If this
   59314     ** is the case, clear the mallocFailed flag and return NULL.
   59315     */
   59316     if( db->mallocFailed ){
   59317       db->mallocFailed = 0;
   59318       ret = 0;
   59319     }
   59320     sqlite3_mutex_leave(db->mutex);
   59321   }
   59322   return ret;
   59323 }
   59324 
   59325 /*
   59326 ** Return the name of the Nth column of the result set returned by SQL
   59327 ** statement pStmt.
   59328 */
   59329 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
   59330   return columnName(
   59331       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
   59332 }
   59333 #ifndef SQLITE_OMIT_UTF16
   59334 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
   59335   return columnName(
   59336       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
   59337 }
   59338 #endif
   59339 
   59340 /*
   59341 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
   59342 ** not define OMIT_DECLTYPE.
   59343 */
   59344 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
   59345 # error "Must not define both SQLITE_OMIT_DECLTYPE \
   59346          and SQLITE_ENABLE_COLUMN_METADATA"
   59347 #endif
   59348 
   59349 #ifndef SQLITE_OMIT_DECLTYPE
   59350 /*
   59351 ** Return the column declaration type (if applicable) of the 'i'th column
   59352 ** of the result set of SQL statement pStmt.
   59353 */
   59354 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
   59355   return columnName(
   59356       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
   59357 }
   59358 #ifndef SQLITE_OMIT_UTF16
   59359 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
   59360   return columnName(
   59361       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
   59362 }
   59363 #endif /* SQLITE_OMIT_UTF16 */
   59364 #endif /* SQLITE_OMIT_DECLTYPE */
   59365 
   59366 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   59367 /*
   59368 ** Return the name of the database from which a result column derives.
   59369 ** NULL is returned if the result column is an expression or constant or
   59370 ** anything else which is not an unabiguous reference to a database column.
   59371 */
   59372 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
   59373   return columnName(
   59374       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
   59375 }
   59376 #ifndef SQLITE_OMIT_UTF16
   59377 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
   59378   return columnName(
   59379       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
   59380 }
   59381 #endif /* SQLITE_OMIT_UTF16 */
   59382 
   59383 /*
   59384 ** Return the name of the table from which a result column derives.
   59385 ** NULL is returned if the result column is an expression or constant or
   59386 ** anything else which is not an unabiguous reference to a database column.
   59387 */
   59388 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
   59389   return columnName(
   59390       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
   59391 }
   59392 #ifndef SQLITE_OMIT_UTF16
   59393 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
   59394   return columnName(
   59395       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
   59396 }
   59397 #endif /* SQLITE_OMIT_UTF16 */
   59398 
   59399 /*
   59400 ** Return the name of the table column from which a result column derives.
   59401 ** NULL is returned if the result column is an expression or constant or
   59402 ** anything else which is not an unabiguous reference to a database column.
   59403 */
   59404 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
   59405   return columnName(
   59406       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
   59407 }
   59408 #ifndef SQLITE_OMIT_UTF16
   59409 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
   59410   return columnName(
   59411       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
   59412 }
   59413 #endif /* SQLITE_OMIT_UTF16 */
   59414 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
   59415 
   59416 
   59417 /******************************* sqlite3_bind_  ***************************
   59418 **
   59419 ** Routines used to attach values to wildcards in a compiled SQL statement.
   59420 */
   59421 /*
   59422 ** Unbind the value bound to variable i in virtual machine p. This is the
   59423 ** the same as binding a NULL value to the column. If the "i" parameter is
   59424 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
   59425 **
   59426 ** A successful evaluation of this routine acquires the mutex on p.
   59427 ** the mutex is released if any kind of error occurs.
   59428 **
   59429 ** The error code stored in database p->db is overwritten with the return
   59430 ** value in any case.
   59431 */
   59432 static int vdbeUnbind(Vdbe *p, int i){
   59433   Mem *pVar;
   59434   if( vdbeSafetyNotNull(p) ){
   59435     return SQLITE_MISUSE_BKPT;
   59436   }
   59437   sqlite3_mutex_enter(p->db->mutex);
   59438   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
   59439     sqlite3Error(p->db, SQLITE_MISUSE, 0);
   59440     sqlite3_mutex_leave(p->db->mutex);
   59441     sqlite3_log(SQLITE_MISUSE,
   59442         "bind on a busy prepared statement: [%s]", p->zSql);
   59443     return SQLITE_MISUSE_BKPT;
   59444   }
   59445   if( i<1 || i>p->nVar ){
   59446     sqlite3Error(p->db, SQLITE_RANGE, 0);
   59447     sqlite3_mutex_leave(p->db->mutex);
   59448     return SQLITE_RANGE;
   59449   }
   59450   i--;
   59451   pVar = &p->aVar[i];
   59452   sqlite3VdbeMemRelease(pVar);
   59453   pVar->flags = MEM_Null;
   59454   sqlite3Error(p->db, SQLITE_OK, 0);
   59455 
   59456   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   59457   ** binding a new value to this variable invalidates the current query plan.
   59458   **
   59459   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
   59460   ** parameter in the WHERE clause might influence the choice of query plan
   59461   ** for a statement, then the statement will be automatically recompiled,
   59462   ** as if there had been a schema change, on the first sqlite3_step() call
   59463   ** following any change to the bindings of that parameter.
   59464   */
   59465   if( p->isPrepareV2 &&
   59466      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
   59467   ){
   59468     p->expired = 1;
   59469   }
   59470   return SQLITE_OK;
   59471 }
   59472 
   59473 /*
   59474 ** Bind a text or BLOB value.
   59475 */
   59476 static int bindText(
   59477   sqlite3_stmt *pStmt,   /* The statement to bind against */
   59478   int i,                 /* Index of the parameter to bind */
   59479   const void *zData,     /* Pointer to the data to be bound */
   59480   int nData,             /* Number of bytes of data to be bound */
   59481   void (*xDel)(void*),   /* Destructor for the data */
   59482   u8 encoding            /* Encoding for the data */
   59483 ){
   59484   Vdbe *p = (Vdbe *)pStmt;
   59485   Mem *pVar;
   59486   int rc;
   59487 
   59488   rc = vdbeUnbind(p, i);
   59489   if( rc==SQLITE_OK ){
   59490     if( zData!=0 ){
   59491       pVar = &p->aVar[i-1];
   59492       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
   59493       if( rc==SQLITE_OK && encoding!=0 ){
   59494         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
   59495       }
   59496       sqlite3Error(p->db, rc, 0);
   59497       rc = sqlite3ApiExit(p->db, rc);
   59498     }
   59499     sqlite3_mutex_leave(p->db->mutex);
   59500   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
   59501     xDel((void*)zData);
   59502   }
   59503   return rc;
   59504 }
   59505 
   59506 
   59507 /*
   59508 ** Bind a blob value to an SQL statement variable.
   59509 */
   59510 SQLITE_API int sqlite3_bind_blob(
   59511   sqlite3_stmt *pStmt,
   59512   int i,
   59513   const void *zData,
   59514   int nData,
   59515   void (*xDel)(void*)
   59516 ){
   59517   return bindText(pStmt, i, zData, nData, xDel, 0);
   59518 }
   59519 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
   59520   int rc;
   59521   Vdbe *p = (Vdbe *)pStmt;
   59522   rc = vdbeUnbind(p, i);
   59523   if( rc==SQLITE_OK ){
   59524     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
   59525     sqlite3_mutex_leave(p->db->mutex);
   59526   }
   59527   return rc;
   59528 }
   59529 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
   59530   return sqlite3_bind_int64(p, i, (i64)iValue);
   59531 }
   59532 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
   59533   int rc;
   59534   Vdbe *p = (Vdbe *)pStmt;
   59535   rc = vdbeUnbind(p, i);
   59536   if( rc==SQLITE_OK ){
   59537     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
   59538     sqlite3_mutex_leave(p->db->mutex);
   59539   }
   59540   return rc;
   59541 }
   59542 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
   59543   int rc;
   59544   Vdbe *p = (Vdbe*)pStmt;
   59545   rc = vdbeUnbind(p, i);
   59546   if( rc==SQLITE_OK ){
   59547     sqlite3_mutex_leave(p->db->mutex);
   59548   }
   59549   return rc;
   59550 }
   59551 SQLITE_API int sqlite3_bind_text(
   59552   sqlite3_stmt *pStmt,
   59553   int i,
   59554   const char *zData,
   59555   int nData,
   59556   void (*xDel)(void*)
   59557 ){
   59558   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
   59559 }
   59560 #ifndef SQLITE_OMIT_UTF16
   59561 SQLITE_API int sqlite3_bind_text16(
   59562   sqlite3_stmt *pStmt,
   59563   int i,
   59564   const void *zData,
   59565   int nData,
   59566   void (*xDel)(void*)
   59567 ){
   59568   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
   59569 }
   59570 #endif /* SQLITE_OMIT_UTF16 */
   59571 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
   59572   int rc;
   59573   switch( pValue->type ){
   59574     case SQLITE_INTEGER: {
   59575       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
   59576       break;
   59577     }
   59578     case SQLITE_FLOAT: {
   59579       rc = sqlite3_bind_double(pStmt, i, pValue->r);
   59580       break;
   59581     }
   59582     case SQLITE_BLOB: {
   59583       if( pValue->flags & MEM_Zero ){
   59584         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
   59585       }else{
   59586         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
   59587       }
   59588       break;
   59589     }
   59590     case SQLITE_TEXT: {
   59591       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
   59592                               pValue->enc);
   59593       break;
   59594     }
   59595     default: {
   59596       rc = sqlite3_bind_null(pStmt, i);
   59597       break;
   59598     }
   59599   }
   59600   return rc;
   59601 }
   59602 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
   59603   int rc;
   59604   Vdbe *p = (Vdbe *)pStmt;
   59605   rc = vdbeUnbind(p, i);
   59606   if( rc==SQLITE_OK ){
   59607     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
   59608     sqlite3_mutex_leave(p->db->mutex);
   59609   }
   59610   return rc;
   59611 }
   59612 
   59613 /*
   59614 ** Return the number of wildcards that can be potentially bound to.
   59615 ** This routine is added to support DBD::SQLite.
   59616 */
   59617 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   59618   Vdbe *p = (Vdbe*)pStmt;
   59619   return p ? p->nVar : 0;
   59620 }
   59621 
   59622 /*
   59623 ** Create a mapping from variable numbers to variable names
   59624 ** in the Vdbe.azVar[] array, if such a mapping does not already
   59625 ** exist.
   59626 */
   59627 static void createVarMap(Vdbe *p){
   59628   if( !p->okVar ){
   59629     int j;
   59630     Op *pOp;
   59631     sqlite3_mutex_enter(p->db->mutex);
   59632     /* The race condition here is harmless.  If two threads call this
   59633     ** routine on the same Vdbe at the same time, they both might end
   59634     ** up initializing the Vdbe.azVar[] array.  That is a little extra
   59635     ** work but it results in the same answer.
   59636     */
   59637     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
   59638       if( pOp->opcode==OP_Variable ){
   59639         assert( pOp->p1>0 && pOp->p1<=p->nVar );
   59640         p->azVar[pOp->p1-1] = pOp->p4.z;
   59641       }
   59642     }
   59643     p->okVar = 1;
   59644     sqlite3_mutex_leave(p->db->mutex);
   59645   }
   59646 }
   59647 
   59648 /*
   59649 ** Return the name of a wildcard parameter.  Return NULL if the index
   59650 ** is out of range or if the wildcard is unnamed.
   59651 **
   59652 ** The result is always UTF-8.
   59653 */
   59654 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
   59655   Vdbe *p = (Vdbe*)pStmt;
   59656   if( p==0 || i<1 || i>p->nVar ){
   59657     return 0;
   59658   }
   59659   createVarMap(p);
   59660   return p->azVar[i-1];
   59661 }
   59662 
   59663 /*
   59664 ** Given a wildcard parameter name, return the index of the variable
   59665 ** with that name.  If there is no variable with the given name,
   59666 ** return 0.
   59667 */
   59668 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
   59669   int i;
   59670   if( p==0 ){
   59671     return 0;
   59672   }
   59673   createVarMap(p);
   59674   if( zName ){
   59675     for(i=0; i<p->nVar; i++){
   59676       const char *z = p->azVar[i];
   59677       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
   59678         return i+1;
   59679       }
   59680     }
   59681   }
   59682   return 0;
   59683 }
   59684 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
   59685   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
   59686 }
   59687 
   59688 /*
   59689 ** Transfer all bindings from the first statement over to the second.
   59690 */
   59691 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   59692   Vdbe *pFrom = (Vdbe*)pFromStmt;
   59693   Vdbe *pTo = (Vdbe*)pToStmt;
   59694   int i;
   59695   assert( pTo->db==pFrom->db );
   59696   assert( pTo->nVar==pFrom->nVar );
   59697   sqlite3_mutex_enter(pTo->db->mutex);
   59698   for(i=0; i<pFrom->nVar; i++){
   59699     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
   59700   }
   59701   sqlite3_mutex_leave(pTo->db->mutex);
   59702   return SQLITE_OK;
   59703 }
   59704 
   59705 #ifndef SQLITE_OMIT_DEPRECATED
   59706 /*
   59707 ** Deprecated external interface.  Internal/core SQLite code
   59708 ** should call sqlite3TransferBindings.
   59709 **
   59710 ** Is is misuse to call this routine with statements from different
   59711 ** database connections.  But as this is a deprecated interface, we
   59712 ** will not bother to check for that condition.
   59713 **
   59714 ** If the two statements contain a different number of bindings, then
   59715 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
   59716 ** SQLITE_OK is returned.
   59717 */
   59718 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
   59719   Vdbe *pFrom = (Vdbe*)pFromStmt;
   59720   Vdbe *pTo = (Vdbe*)pToStmt;
   59721   if( pFrom->nVar!=pTo->nVar ){
   59722     return SQLITE_ERROR;
   59723   }
   59724   if( pTo->isPrepareV2 && pTo->expmask ){
   59725     pTo->expired = 1;
   59726   }
   59727   if( pFrom->isPrepareV2 && pFrom->expmask ){
   59728     pFrom->expired = 1;
   59729   }
   59730   return sqlite3TransferBindings(pFromStmt, pToStmt);
   59731 }
   59732 #endif
   59733 
   59734 /*
   59735 ** Return the sqlite3* database handle to which the prepared statement given
   59736 ** in the argument belongs.  This is the same database handle that was
   59737 ** the first argument to the sqlite3_prepare() that was used to create
   59738 ** the statement in the first place.
   59739 */
   59740 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
   59741   return pStmt ? ((Vdbe*)pStmt)->db : 0;
   59742 }
   59743 
   59744 /*
   59745 ** Return true if the prepared statement is guaranteed to not modify the
   59746 ** database.
   59747 */
   59748 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
   59749   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
   59750 }
   59751 
   59752 /*
   59753 ** Return a pointer to the next prepared statement after pStmt associated
   59754 ** with database connection pDb.  If pStmt is NULL, return the first
   59755 ** prepared statement for the database connection.  Return NULL if there
   59756 ** are no more.
   59757 */
   59758 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
   59759   sqlite3_stmt *pNext;
   59760   sqlite3_mutex_enter(pDb->mutex);
   59761   if( pStmt==0 ){
   59762     pNext = (sqlite3_stmt*)pDb->pVdbe;
   59763   }else{
   59764     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
   59765   }
   59766   sqlite3_mutex_leave(pDb->mutex);
   59767   return pNext;
   59768 }
   59769 
   59770 /*
   59771 ** Return the value of a status counter for a prepared statement
   59772 */
   59773 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   59774   Vdbe *pVdbe = (Vdbe*)pStmt;
   59775   int v = pVdbe->aCounter[op-1];
   59776   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
   59777   return v;
   59778 }
   59779 
   59780 /************** End of vdbeapi.c *********************************************/
   59781 /************** Begin file vdbetrace.c ***************************************/
   59782 /*
   59783 ** 2009 November 25
   59784 **
   59785 ** The author disclaims copyright to this source code.  In place of
   59786 ** a legal notice, here is a blessing:
   59787 **
   59788 **    May you do good and not evil.
   59789 **    May you find forgiveness for yourself and forgive others.
   59790 **    May you share freely, never taking more than you give.
   59791 **
   59792 *************************************************************************
   59793 **
   59794 ** This file contains code used to insert the values of host parameters
   59795 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
   59796 */
   59797 
   59798 #ifndef SQLITE_OMIT_TRACE
   59799 
   59800 /*
   59801 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
   59802 ** bytes in this text up to but excluding the first character in
   59803 ** a host parameter.  If the text contains no host parameters, return
   59804 ** the total number of bytes in the text.
   59805 */
   59806 static int findNextHostParameter(const char *zSql, int *pnToken){
   59807   int tokenType;
   59808   int nTotal = 0;
   59809   int n;
   59810 
   59811   *pnToken = 0;
   59812   while( zSql[0] ){
   59813     n = sqlite3GetToken((u8*)zSql, &tokenType);
   59814     assert( n>0 && tokenType!=TK_ILLEGAL );
   59815     if( tokenType==TK_VARIABLE ){
   59816       *pnToken = n;
   59817       break;
   59818     }
   59819     nTotal += n;
   59820     zSql += n;
   59821   }
   59822   return nTotal;
   59823 }
   59824 
   59825 /*
   59826 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
   59827 ** holds a copy of zRawSql but with host parameters expanded to their
   59828 ** current bindings.
   59829 **
   59830 ** The calling function is responsible for making sure the memory returned
   59831 ** is eventually freed.
   59832 **
   59833 ** ALGORITHM:  Scan the input string looking for host parameters in any of
   59834 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
   59835 ** string literals, quoted identifier names, and comments.  For text forms,
   59836 ** the host parameter index is found by scanning the perpared
   59837 ** statement for the corresponding OP_Variable opcode.  Once the host
   59838 ** parameter index is known, locate the value in p->aVar[].  Then render
   59839 ** the value as a literal in place of the host parameter name.
   59840 */
   59841 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   59842   Vdbe *p,                 /* The prepared statement being evaluated */
   59843   const char *zRawSql      /* Raw text of the SQL statement */
   59844 ){
   59845   sqlite3 *db;             /* The database connection */
   59846   int idx = 0;             /* Index of a host parameter */
   59847   int nextIndex = 1;       /* Index of next ? host parameter */
   59848   int n;                   /* Length of a token prefix */
   59849   int nToken;              /* Length of the parameter token */
   59850   int i;                   /* Loop counter */
   59851   Mem *pVar;               /* Value of a host parameter */
   59852   StrAccum out;            /* Accumulate the output here */
   59853   char zBase[100];         /* Initial working space */
   59854 
   59855   db = p->db;
   59856   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
   59857                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   59858   out.db = db;
   59859   while( zRawSql[0] ){
   59860     n = findNextHostParameter(zRawSql, &nToken);
   59861     assert( n>0 );
   59862     sqlite3StrAccumAppend(&out, zRawSql, n);
   59863     zRawSql += n;
   59864     assert( zRawSql[0] || nToken==0 );
   59865     if( nToken==0 ) break;
   59866     if( zRawSql[0]=='?' ){
   59867       if( nToken>1 ){
   59868         assert( sqlite3Isdigit(zRawSql[1]) );
   59869         sqlite3GetInt32(&zRawSql[1], &idx);
   59870       }else{
   59871         idx = nextIndex;
   59872       }
   59873     }else{
   59874       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
   59875       testcase( zRawSql[0]==':' );
   59876       testcase( zRawSql[0]=='$' );
   59877       testcase( zRawSql[0]=='@' );
   59878       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
   59879       assert( idx>0 );
   59880     }
   59881     zRawSql += nToken;
   59882     nextIndex = idx + 1;
   59883     assert( idx>0 && idx<=p->nVar );
   59884     pVar = &p->aVar[idx-1];
   59885     if( pVar->flags & MEM_Null ){
   59886       sqlite3StrAccumAppend(&out, "NULL", 4);
   59887     }else if( pVar->flags & MEM_Int ){
   59888       sqlite3XPrintf(&out, "%lld", pVar->u.i);
   59889     }else if( pVar->flags & MEM_Real ){
   59890       sqlite3XPrintf(&out, "%!.15g", pVar->r);
   59891     }else if( pVar->flags & MEM_Str ){
   59892 #ifndef SQLITE_OMIT_UTF16
   59893       u8 enc = ENC(db);
   59894       if( enc!=SQLITE_UTF8 ){
   59895         Mem utf8;
   59896         memset(&utf8, 0, sizeof(utf8));
   59897         utf8.db = db;
   59898         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
   59899         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
   59900         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
   59901         sqlite3VdbeMemRelease(&utf8);
   59902       }else
   59903 #endif
   59904       {
   59905         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
   59906       }
   59907     }else if( pVar->flags & MEM_Zero ){
   59908       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
   59909     }else{
   59910       assert( pVar->flags & MEM_Blob );
   59911       sqlite3StrAccumAppend(&out, "x'", 2);
   59912       for(i=0; i<pVar->n; i++){
   59913         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
   59914       }
   59915       sqlite3StrAccumAppend(&out, "'", 1);
   59916     }
   59917   }
   59918   return sqlite3StrAccumFinish(&out);
   59919 }
   59920 
   59921 #endif /* #ifndef SQLITE_OMIT_TRACE */
   59922 
   59923 /************** End of vdbetrace.c *******************************************/
   59924 /************** Begin file vdbe.c ********************************************/
   59925 /*
   59926 ** 2001 September 15
   59927 **
   59928 ** The author disclaims copyright to this source code.  In place of
   59929 ** a legal notice, here is a blessing:
   59930 **
   59931 **    May you do good and not evil.
   59932 **    May you find forgiveness for yourself and forgive others.
   59933 **    May you share freely, never taking more than you give.
   59934 **
   59935 *************************************************************************
   59936 ** The code in this file implements execution method of the
   59937 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
   59938 ** handles housekeeping details such as creating and deleting
   59939 ** VDBE instances.  This file is solely interested in executing
   59940 ** the VDBE program.
   59941 **
   59942 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
   59943 ** to a VDBE.
   59944 **
   59945 ** The SQL parser generates a program which is then executed by
   59946 ** the VDBE to do the work of the SQL statement.  VDBE programs are
   59947 ** similar in form to assembly language.  The program consists of
   59948 ** a linear sequence of operations.  Each operation has an opcode
   59949 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
   59950 ** is a null-terminated string.  Operand P5 is an unsigned character.
   59951 ** Few opcodes use all 5 operands.
   59952 **
   59953 ** Computation results are stored on a set of registers numbered beginning
   59954 ** with 1 and going up to Vdbe.nMem.  Each register can store
   59955 ** either an integer, a null-terminated string, a floating point
   59956 ** number, or the SQL "NULL" value.  An implicit conversion from one
   59957 ** type to the other occurs as necessary.
   59958 **
   59959 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
   59960 ** function which does the work of interpreting a VDBE program.
   59961 ** But other routines are also provided to help in building up
   59962 ** a program instruction by instruction.
   59963 **
   59964 ** Various scripts scan this source file in order to generate HTML
   59965 ** documentation, headers files, or other derived files.  The formatting
   59966 ** of the code in this file is, therefore, important.  See other comments
   59967 ** in this file for details.  If in doubt, do not deviate from existing
   59968 ** commenting and indentation practices when changing or adding code.
   59969 */
   59970 
   59971 /*
   59972 ** Invoke this macro on memory cells just prior to changing the
   59973 ** value of the cell.  This macro verifies that shallow copies are
   59974 ** not misused.
   59975 */
   59976 #ifdef SQLITE_DEBUG
   59977 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
   59978 #else
   59979 # define memAboutToChange(P,M)
   59980 #endif
   59981 
   59982 /*
   59983 ** The following global variable is incremented every time a cursor
   59984 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
   59985 ** procedures use this information to make sure that indices are
   59986 ** working correctly.  This variable has no function other than to
   59987 ** help verify the correct operation of the library.
   59988 */
   59989 #ifdef SQLITE_TEST
   59990 SQLITE_API int sqlite3_search_count = 0;
   59991 #endif
   59992 
   59993 /*
   59994 ** When this global variable is positive, it gets decremented once before
   59995 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
   59996 ** field of the sqlite3 structure is set in order to simulate and interrupt.
   59997 **
   59998 ** This facility is used for testing purposes only.  It does not function
   59999 ** in an ordinary build.
   60000 */
   60001 #ifdef SQLITE_TEST
   60002 SQLITE_API int sqlite3_interrupt_count = 0;
   60003 #endif
   60004 
   60005 /*
   60006 ** The next global variable is incremented each type the OP_Sort opcode
   60007 ** is executed.  The test procedures use this information to make sure that
   60008 ** sorting is occurring or not occurring at appropriate times.   This variable
   60009 ** has no function other than to help verify the correct operation of the
   60010 ** library.
   60011 */
   60012 #ifdef SQLITE_TEST
   60013 SQLITE_API int sqlite3_sort_count = 0;
   60014 #endif
   60015 
   60016 /*
   60017 ** The next global variable records the size of the largest MEM_Blob
   60018 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
   60019 ** use this information to make sure that the zero-blob functionality
   60020 ** is working correctly.   This variable has no function other than to
   60021 ** help verify the correct operation of the library.
   60022 */
   60023 #ifdef SQLITE_TEST
   60024 SQLITE_API int sqlite3_max_blobsize = 0;
   60025 static void updateMaxBlobsize(Mem *p){
   60026   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
   60027     sqlite3_max_blobsize = p->n;
   60028   }
   60029 }
   60030 #endif
   60031 
   60032 /*
   60033 ** The next global variable is incremented each type the OP_Found opcode
   60034 ** is executed. This is used to test whether or not the foreign key
   60035 ** operation implemented using OP_FkIsZero is working. This variable
   60036 ** has no function other than to help verify the correct operation of the
   60037 ** library.
   60038 */
   60039 #ifdef SQLITE_TEST
   60040 SQLITE_API int sqlite3_found_count = 0;
   60041 #endif
   60042 
   60043 /*
   60044 ** Test a register to see if it exceeds the current maximum blob size.
   60045 ** If it does, record the new maximum blob size.
   60046 */
   60047 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   60048 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   60049 #else
   60050 # define UPDATE_MAX_BLOBSIZE(P)
   60051 #endif
   60052 
   60053 /*
   60054 ** Convert the given register into a string if it isn't one
   60055 ** already. Return non-zero if a malloc() fails.
   60056 */
   60057 #define Stringify(P, enc) \
   60058    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   60059      { goto no_mem; }
   60060 
   60061 /*
   60062 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
   60063 ** a pointer to a dynamically allocated string where some other entity
   60064 ** is responsible for deallocating that string.  Because the register
   60065 ** does not control the string, it might be deleted without the register
   60066 ** knowing it.
   60067 **
   60068 ** This routine converts an ephemeral string into a dynamically allocated
   60069 ** string that the register itself controls.  In other words, it
   60070 ** converts an MEM_Ephem string into an MEM_Dyn string.
   60071 */
   60072 #define Deephemeralize(P) \
   60073    if( ((P)->flags&MEM_Ephem)!=0 \
   60074        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   60075 
   60076 /*
   60077 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
   60078 ** P if required.
   60079 */
   60080 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
   60081 
   60082 /*
   60083 ** Argument pMem points at a register that will be passed to a
   60084 ** user-defined function or returned to the user as the result of a query.
   60085 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
   60086 ** routines.
   60087 */
   60088 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
   60089   int flags = pMem->flags;
   60090   if( flags & MEM_Null ){
   60091     pMem->type = SQLITE_NULL;
   60092   }
   60093   else if( flags & MEM_Int ){
   60094     pMem->type = SQLITE_INTEGER;
   60095   }
   60096   else if( flags & MEM_Real ){
   60097     pMem->type = SQLITE_FLOAT;
   60098   }
   60099   else if( flags & MEM_Str ){
   60100     pMem->type = SQLITE_TEXT;
   60101   }else{
   60102     pMem->type = SQLITE_BLOB;
   60103   }
   60104 }
   60105 
   60106 /*
   60107 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
   60108 ** if we run out of memory.
   60109 */
   60110 static VdbeCursor *allocateCursor(
   60111   Vdbe *p,              /* The virtual machine */
   60112   int iCur,             /* Index of the new VdbeCursor */
   60113   int nField,           /* Number of fields in the table or index */
   60114   int iDb,              /* When database the cursor belongs to, or -1 */
   60115   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
   60116 ){
   60117   /* Find the memory cell that will be used to store the blob of memory
   60118   ** required for this VdbeCursor structure. It is convenient to use a
   60119   ** vdbe memory cell to manage the memory allocation required for a
   60120   ** VdbeCursor structure for the following reasons:
   60121   **
   60122   **   * Sometimes cursor numbers are used for a couple of different
   60123   **     purposes in a vdbe program. The different uses might require
   60124   **     different sized allocations. Memory cells provide growable
   60125   **     allocations.
   60126   **
   60127   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
   60128   **     be freed lazily via the sqlite3_release_memory() API. This
   60129   **     minimizes the number of malloc calls made by the system.
   60130   **
   60131   ** Memory cells for cursors are allocated at the top of the address
   60132   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
   60133   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
   60134   */
   60135   Mem *pMem = &p->aMem[p->nMem-iCur];
   60136 
   60137   int nByte;
   60138   VdbeCursor *pCx = 0;
   60139   nByte =
   60140       ROUND8(sizeof(VdbeCursor)) +
   60141       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
   60142       2*nField*sizeof(u32);
   60143 
   60144   assert( iCur<p->nCursor );
   60145   if( p->apCsr[iCur] ){
   60146     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
   60147     p->apCsr[iCur] = 0;
   60148   }
   60149   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
   60150     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
   60151     memset(pCx, 0, sizeof(VdbeCursor));
   60152     pCx->iDb = iDb;
   60153     pCx->nField = nField;
   60154     if( nField ){
   60155       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
   60156     }
   60157     if( isBtreeCursor ){
   60158       pCx->pCursor = (BtCursor*)
   60159           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
   60160       sqlite3BtreeCursorZero(pCx->pCursor);
   60161     }
   60162   }
   60163   return pCx;
   60164 }
   60165 
   60166 /*
   60167 ** Try to convert a value into a numeric representation if we can
   60168 ** do so without loss of information.  In other words, if the string
   60169 ** looks like a number, convert it into a number.  If it does not
   60170 ** look like a number, leave it alone.
   60171 */
   60172 static void applyNumericAffinity(Mem *pRec){
   60173   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
   60174     double rValue;
   60175     i64 iValue;
   60176     u8 enc = pRec->enc;
   60177     if( (pRec->flags&MEM_Str)==0 ) return;
   60178     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
   60179     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
   60180       pRec->u.i = iValue;
   60181       pRec->flags |= MEM_Int;
   60182     }else{
   60183       pRec->r = rValue;
   60184       pRec->flags |= MEM_Real;
   60185     }
   60186   }
   60187 }
   60188 
   60189 /*
   60190 ** Processing is determine by the affinity parameter:
   60191 **
   60192 ** SQLITE_AFF_INTEGER:
   60193 ** SQLITE_AFF_REAL:
   60194 ** SQLITE_AFF_NUMERIC:
   60195 **    Try to convert pRec to an integer representation or a
   60196 **    floating-point representation if an integer representation
   60197 **    is not possible.  Note that the integer representation is
   60198 **    always preferred, even if the affinity is REAL, because
   60199 **    an integer representation is more space efficient on disk.
   60200 **
   60201 ** SQLITE_AFF_TEXT:
   60202 **    Convert pRec to a text representation.
   60203 **
   60204 ** SQLITE_AFF_NONE:
   60205 **    No-op.  pRec is unchanged.
   60206 */
   60207 static void applyAffinity(
   60208   Mem *pRec,          /* The value to apply affinity to */
   60209   char affinity,      /* The affinity to be applied */
   60210   u8 enc              /* Use this text encoding */
   60211 ){
   60212   if( affinity==SQLITE_AFF_TEXT ){
   60213     /* Only attempt the conversion to TEXT if there is an integer or real
   60214     ** representation (blob and NULL do not get converted) but no string
   60215     ** representation.
   60216     */
   60217     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
   60218       sqlite3VdbeMemStringify(pRec, enc);
   60219     }
   60220     pRec->flags &= ~(MEM_Real|MEM_Int);
   60221   }else if( affinity!=SQLITE_AFF_NONE ){
   60222     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
   60223              || affinity==SQLITE_AFF_NUMERIC );
   60224     applyNumericAffinity(pRec);
   60225     if( pRec->flags & MEM_Real ){
   60226       sqlite3VdbeIntegerAffinity(pRec);
   60227     }
   60228   }
   60229 }
   60230 
   60231 /*
   60232 ** Try to convert the type of a function argument or a result column
   60233 ** into a numeric representation.  Use either INTEGER or REAL whichever
   60234 ** is appropriate.  But only do the conversion if it is possible without
   60235 ** loss of information and return the revised type of the argument.
   60236 */
   60237 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
   60238   Mem *pMem = (Mem*)pVal;
   60239   if( pMem->type==SQLITE_TEXT ){
   60240     applyNumericAffinity(pMem);
   60241     sqlite3VdbeMemStoreType(pMem);
   60242   }
   60243   return pMem->type;
   60244 }
   60245 
   60246 /*
   60247 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
   60248 ** not the internal Mem* type.
   60249 */
   60250 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
   60251   sqlite3_value *pVal,
   60252   u8 affinity,
   60253   u8 enc
   60254 ){
   60255   applyAffinity((Mem *)pVal, affinity, enc);
   60256 }
   60257 
   60258 #ifdef SQLITE_DEBUG
   60259 /*
   60260 ** Write a nice string representation of the contents of cell pMem
   60261 ** into buffer zBuf, length nBuf.
   60262 */
   60263 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
   60264   char *zCsr = zBuf;
   60265   int f = pMem->flags;
   60266 
   60267   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
   60268 
   60269   if( f&MEM_Blob ){
   60270     int i;
   60271     char c;
   60272     if( f & MEM_Dyn ){
   60273       c = 'z';
   60274       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   60275     }else if( f & MEM_Static ){
   60276       c = 't';
   60277       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   60278     }else if( f & MEM_Ephem ){
   60279       c = 'e';
   60280       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   60281     }else{
   60282       c = 's';
   60283     }
   60284 
   60285     sqlite3_snprintf(100, zCsr, "%c", c);
   60286     zCsr += sqlite3Strlen30(zCsr);
   60287     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
   60288     zCsr += sqlite3Strlen30(zCsr);
   60289     for(i=0; i<16 && i<pMem->n; i++){
   60290       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
   60291       zCsr += sqlite3Strlen30(zCsr);
   60292     }
   60293     for(i=0; i<16 && i<pMem->n; i++){
   60294       char z = pMem->z[i];
   60295       if( z<32 || z>126 ) *zCsr++ = '.';
   60296       else *zCsr++ = z;
   60297     }
   60298 
   60299     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
   60300     zCsr += sqlite3Strlen30(zCsr);
   60301     if( f & MEM_Zero ){
   60302       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
   60303       zCsr += sqlite3Strlen30(zCsr);
   60304     }
   60305     *zCsr = '\0';
   60306   }else if( f & MEM_Str ){
   60307     int j, k;
   60308     zBuf[0] = ' ';
   60309     if( f & MEM_Dyn ){
   60310       zBuf[1] = 'z';
   60311       assert( (f & (MEM_Static|MEM_Ephem))==0 );
   60312     }else if( f & MEM_Static ){
   60313       zBuf[1] = 't';
   60314       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
   60315     }else if( f & MEM_Ephem ){
   60316       zBuf[1] = 'e';
   60317       assert( (f & (MEM_Static|MEM_Dyn))==0 );
   60318     }else{
   60319       zBuf[1] = 's';
   60320     }
   60321     k = 2;
   60322     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
   60323     k += sqlite3Strlen30(&zBuf[k]);
   60324     zBuf[k++] = '[';
   60325     for(j=0; j<15 && j<pMem->n; j++){
   60326       u8 c = pMem->z[j];
   60327       if( c>=0x20 && c<0x7f ){
   60328         zBuf[k++] = c;
   60329       }else{
   60330         zBuf[k++] = '.';
   60331       }
   60332     }
   60333     zBuf[k++] = ']';
   60334     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
   60335     k += sqlite3Strlen30(&zBuf[k]);
   60336     zBuf[k++] = 0;
   60337   }
   60338 }
   60339 #endif
   60340 
   60341 #ifdef SQLITE_DEBUG
   60342 /*
   60343 ** Print the value of a register for tracing purposes:
   60344 */
   60345 static void memTracePrint(FILE *out, Mem *p){
   60346   if( p->flags & MEM_Null ){
   60347     fprintf(out, " NULL");
   60348   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
   60349     fprintf(out, " si:%lld", p->u.i);
   60350   }else if( p->flags & MEM_Int ){
   60351     fprintf(out, " i:%lld", p->u.i);
   60352 #ifndef SQLITE_OMIT_FLOATING_POINT
   60353   }else if( p->flags & MEM_Real ){
   60354     fprintf(out, " r:%g", p->r);
   60355 #endif
   60356   }else if( p->flags & MEM_RowSet ){
   60357     fprintf(out, " (rowset)");
   60358   }else{
   60359     char zBuf[200];
   60360     sqlite3VdbeMemPrettyPrint(p, zBuf);
   60361     fprintf(out, " ");
   60362     fprintf(out, "%s", zBuf);
   60363   }
   60364 }
   60365 static void registerTrace(FILE *out, int iReg, Mem *p){
   60366   fprintf(out, "REG[%d] = ", iReg);
   60367   memTracePrint(out, p);
   60368   fprintf(out, "\n");
   60369 }
   60370 #endif
   60371 
   60372 #ifdef SQLITE_DEBUG
   60373 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
   60374 #else
   60375 #  define REGISTER_TRACE(R,M)
   60376 #endif
   60377 
   60378 
   60379 #ifdef VDBE_PROFILE
   60380 
   60381 /*
   60382 ** hwtime.h contains inline assembler code for implementing
   60383 ** high-performance timing routines.
   60384 */
   60385 /************** Include hwtime.h in the middle of vdbe.c *********************/
   60386 /************** Begin file hwtime.h ******************************************/
   60387 /*
   60388 ** 2008 May 27
   60389 **
   60390 ** The author disclaims copyright to this source code.  In place of
   60391 ** a legal notice, here is a blessing:
   60392 **
   60393 **    May you do good and not evil.
   60394 **    May you find forgiveness for yourself and forgive others.
   60395 **    May you share freely, never taking more than you give.
   60396 **
   60397 ******************************************************************************
   60398 **
   60399 ** This file contains inline asm code for retrieving "high-performance"
   60400 ** counters for x86 class CPUs.
   60401 */
   60402 #ifndef _HWTIME_H_
   60403 #define _HWTIME_H_
   60404 
   60405 /*
   60406 ** The following routine only works on pentium-class (or newer) processors.
   60407 ** It uses the RDTSC opcode to read the cycle count value out of the
   60408 ** processor and returns that value.  This can be used for high-res
   60409 ** profiling.
   60410 */
   60411 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
   60412       (defined(i386) || defined(__i386__) || defined(_M_IX86))
   60413 
   60414   #if defined(__GNUC__)
   60415 
   60416   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   60417      unsigned int lo, hi;
   60418      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
   60419      return (sqlite_uint64)hi << 32 | lo;
   60420   }
   60421 
   60422   #elif defined(_MSC_VER)
   60423 
   60424   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
   60425      __asm {
   60426         rdtsc
   60427         ret       ; return value at EDX:EAX
   60428      }
   60429   }
   60430 
   60431   #endif
   60432 
   60433 #elif (defined(__GNUC__) && defined(__x86_64__))
   60434 
   60435   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   60436       unsigned long val;
   60437       __asm__ __volatile__ ("rdtsc" : "=A" (val));
   60438       return val;
   60439   }
   60440 
   60441 #elif (defined(__GNUC__) && defined(__ppc__))
   60442 
   60443   __inline__ sqlite_uint64 sqlite3Hwtime(void){
   60444       unsigned long long retval;
   60445       unsigned long junk;
   60446       __asm__ __volatile__ ("\n\
   60447           1:      mftbu   %1\n\
   60448                   mftb    %L0\n\
   60449                   mftbu   %0\n\
   60450                   cmpw    %0,%1\n\
   60451                   bne     1b"
   60452                   : "=r" (retval), "=r" (junk));
   60453       return retval;
   60454   }
   60455 
   60456 #else
   60457 
   60458   #error Need implementation of sqlite3Hwtime() for your platform.
   60459 
   60460   /*
   60461   ** To compile without implementing sqlite3Hwtime() for your platform,
   60462   ** you can remove the above #error and use the following
   60463   ** stub function.  You will lose timing support for many
   60464   ** of the debugging and testing utilities, but it should at
   60465   ** least compile and run.
   60466   */
   60467 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
   60468 
   60469 #endif
   60470 
   60471 #endif /* !defined(_HWTIME_H_) */
   60472 
   60473 /************** End of hwtime.h **********************************************/
   60474 /************** Continuing where we left off in vdbe.c ***********************/
   60475 
   60476 #endif
   60477 
   60478 /*
   60479 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
   60480 ** sqlite3_interrupt() routine has been called.  If it has been, then
   60481 ** processing of the VDBE program is interrupted.
   60482 **
   60483 ** This macro added to every instruction that does a jump in order to
   60484 ** implement a loop.  This test used to be on every single instruction,
   60485 ** but that meant we more testing that we needed.  By only testing the
   60486 ** flag on jump instructions, we get a (small) speed improvement.
   60487 */
   60488 #define CHECK_FOR_INTERRUPT \
   60489    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
   60490 
   60491 
   60492 #ifndef NDEBUG
   60493 /*
   60494 ** This function is only called from within an assert() expression. It
   60495 ** checks that the sqlite3.nTransaction variable is correctly set to
   60496 ** the number of non-transaction savepoints currently in the
   60497 ** linked list starting at sqlite3.pSavepoint.
   60498 **
   60499 ** Usage:
   60500 **
   60501 **     assert( checkSavepointCount(db) );
   60502 */
   60503 static int checkSavepointCount(sqlite3 *db){
   60504   int n = 0;
   60505   Savepoint *p;
   60506   for(p=db->pSavepoint; p; p=p->pNext) n++;
   60507   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
   60508   return 1;
   60509 }
   60510 #endif
   60511 
   60512 /*
   60513 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
   60514 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
   60515 ** in memory obtained from sqlite3DbMalloc).
   60516 */
   60517 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
   60518   sqlite3 *db = p->db;
   60519   sqlite3DbFree(db, p->zErrMsg);
   60520   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   60521   sqlite3_free(pVtab->zErrMsg);
   60522   pVtab->zErrMsg = 0;
   60523 }
   60524 
   60525 
   60526 /*
   60527 ** Execute as much of a VDBE program as we can then return.
   60528 **
   60529 ** sqlite3VdbeMakeReady() must be called before this routine in order to
   60530 ** close the program with a final OP_Halt and to set up the callbacks
   60531 ** and the error message pointer.
   60532 **
   60533 ** Whenever a row or result data is available, this routine will either
   60534 ** invoke the result callback (if there is one) or return with
   60535 ** SQLITE_ROW.
   60536 **
   60537 ** If an attempt is made to open a locked database, then this routine
   60538 ** will either invoke the busy callback (if there is one) or it will
   60539 ** return SQLITE_BUSY.
   60540 **
   60541 ** If an error occurs, an error message is written to memory obtained
   60542 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
   60543 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
   60544 **
   60545 ** If the callback ever returns non-zero, then the program exits
   60546 ** immediately.  There will be no error message but the p->rc field is
   60547 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
   60548 **
   60549 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
   60550 ** routine to return SQLITE_ERROR.
   60551 **
   60552 ** Other fatal errors return SQLITE_ERROR.
   60553 **
   60554 ** After this routine has finished, sqlite3VdbeFinalize() should be
   60555 ** used to clean up the mess that was left behind.
   60556 */
   60557 SQLITE_PRIVATE int sqlite3VdbeExec(
   60558   Vdbe *p                    /* The VDBE */
   60559 ){
   60560   int pc=0;                  /* The program counter */
   60561   Op *aOp = p->aOp;          /* Copy of p->aOp */
   60562   Op *pOp;                   /* Current operation */
   60563   int rc = SQLITE_OK;        /* Value to return */
   60564   sqlite3 *db = p->db;       /* The database */
   60565   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
   60566   u8 encoding = ENC(db);     /* The database encoding */
   60567 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   60568   int checkProgress;         /* True if progress callbacks are enabled */
   60569   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
   60570 #endif
   60571   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   60572   Mem *pIn1 = 0;             /* 1st input operand */
   60573   Mem *pIn2 = 0;             /* 2nd input operand */
   60574   Mem *pIn3 = 0;             /* 3rd input operand */
   60575   Mem *pOut = 0;             /* Output operand */
   60576   int iCompare = 0;          /* Result of last OP_Compare operation */
   60577   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   60578 #ifdef VDBE_PROFILE
   60579   u64 start;                 /* CPU clock count at start of opcode */
   60580   int origPc;                /* Program counter at start of opcode */
   60581 #endif
   60582   /********************************************************************
   60583   ** Automatically generated code
   60584   **
   60585   ** The following union is automatically generated by the
   60586   ** vdbe-compress.tcl script.  The purpose of this union is to
   60587   ** reduce the amount of stack space required by this function.
   60588   ** See comments in the vdbe-compress.tcl script for details.
   60589   */
   60590   union vdbeExecUnion {
   60591     struct OP_Yield_stack_vars {
   60592       int pcDest;
   60593     } aa;
   60594     struct OP_Variable_stack_vars {
   60595       Mem *pVar;       /* Value being transferred */
   60596     } ab;
   60597     struct OP_Move_stack_vars {
   60598       char *zMalloc;   /* Holding variable for allocated memory */
   60599       int n;           /* Number of registers left to copy */
   60600       int p1;          /* Register to copy from */
   60601       int p2;          /* Register to copy to */
   60602     } ac;
   60603     struct OP_ResultRow_stack_vars {
   60604       Mem *pMem;
   60605       int i;
   60606     } ad;
   60607     struct OP_Concat_stack_vars {
   60608       i64 nByte;
   60609     } ae;
   60610     struct OP_Remainder_stack_vars {
   60611       int flags;      /* Combined MEM_* flags from both inputs */
   60612       i64 iA;         /* Integer value of left operand */
   60613       i64 iB;         /* Integer value of right operand */
   60614       double rA;      /* Real value of left operand */
   60615       double rB;      /* Real value of right operand */
   60616     } af;
   60617     struct OP_Function_stack_vars {
   60618       int i;
   60619       Mem *pArg;
   60620       sqlite3_context ctx;
   60621       sqlite3_value **apVal;
   60622       int n;
   60623     } ag;
   60624     struct OP_ShiftRight_stack_vars {
   60625       i64 a;
   60626       i64 b;
   60627     } ah;
   60628     struct OP_Ge_stack_vars {
   60629       int res;            /* Result of the comparison of pIn1 against pIn3 */
   60630       char affinity;      /* Affinity to use for comparison */
   60631       u16 flags1;         /* Copy of initial value of pIn1->flags */
   60632       u16 flags3;         /* Copy of initial value of pIn3->flags */
   60633     } ai;
   60634     struct OP_Compare_stack_vars {
   60635       int n;
   60636       int i;
   60637       int p1;
   60638       int p2;
   60639       const KeyInfo *pKeyInfo;
   60640       int idx;
   60641       CollSeq *pColl;    /* Collating sequence to use on this term */
   60642       int bRev;          /* True for DESCENDING sort order */
   60643     } aj;
   60644     struct OP_Or_stack_vars {
   60645       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   60646       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   60647     } ak;
   60648     struct OP_IfNot_stack_vars {
   60649       int c;
   60650     } al;
   60651     struct OP_Column_stack_vars {
   60652       u32 payloadSize;   /* Number of bytes in the record */
   60653       i64 payloadSize64; /* Number of bytes in the record */
   60654       int p1;            /* P1 value of the opcode */
   60655       int p2;            /* column number to retrieve */
   60656       VdbeCursor *pC;    /* The VDBE cursor */
   60657       char *zRec;        /* Pointer to complete record-data */
   60658       BtCursor *pCrsr;   /* The BTree cursor */
   60659       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   60660       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   60661       int nField;        /* number of fields in the record */
   60662       int len;           /* The length of the serialized data for the column */
   60663       int i;             /* Loop counter */
   60664       char *zData;       /* Part of the record being decoded */
   60665       Mem *pDest;        /* Where to write the extracted value */
   60666       Mem sMem;          /* For storing the record being decoded */
   60667       u8 *zIdx;          /* Index into header */
   60668       u8 *zEndHdr;       /* Pointer to first byte after the header */
   60669       u32 offset;        /* Offset into the data */
   60670       u32 szField;       /* Number of bytes in the content of a field */
   60671       int szHdr;         /* Size of the header size field at start of record */
   60672       int avail;         /* Number of bytes of available data */
   60673       Mem *pReg;         /* PseudoTable input register */
   60674     } am;
   60675     struct OP_Affinity_stack_vars {
   60676       const char *zAffinity;   /* The affinity to be applied */
   60677       char cAff;               /* A single character of affinity */
   60678     } an;
   60679     struct OP_MakeRecord_stack_vars {
   60680       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   60681       Mem *pRec;             /* The new record */
   60682       u64 nData;             /* Number of bytes of data space */
   60683       int nHdr;              /* Number of bytes of header space */
   60684       i64 nByte;             /* Data space required for this record */
   60685       int nZero;             /* Number of zero bytes at the end of the record */
   60686       int nVarint;           /* Number of bytes in a varint */
   60687       u32 serial_type;       /* Type field */
   60688       Mem *pData0;           /* First field to be combined into the record */
   60689       Mem *pLast;            /* Last field of the record */
   60690       int nField;            /* Number of fields in the record */
   60691       char *zAffinity;       /* The affinity string for the record */
   60692       int file_format;       /* File format to use for encoding */
   60693       int i;                 /* Space used in zNewRecord[] */
   60694       int len;               /* Length of a field */
   60695     } ao;
   60696     struct OP_Count_stack_vars {
   60697       i64 nEntry;
   60698       BtCursor *pCrsr;
   60699     } ap;
   60700     struct OP_Savepoint_stack_vars {
   60701       int p1;                         /* Value of P1 operand */
   60702       char *zName;                    /* Name of savepoint */
   60703       int nName;
   60704       Savepoint *pNew;
   60705       Savepoint *pSavepoint;
   60706       Savepoint *pTmp;
   60707       int iSavepoint;
   60708       int ii;
   60709     } aq;
   60710     struct OP_AutoCommit_stack_vars {
   60711       int desiredAutoCommit;
   60712       int iRollback;
   60713       int turnOnAC;
   60714     } ar;
   60715     struct OP_Transaction_stack_vars {
   60716       Btree *pBt;
   60717     } as;
   60718     struct OP_ReadCookie_stack_vars {
   60719       int iMeta;
   60720       int iDb;
   60721       int iCookie;
   60722     } at;
   60723     struct OP_SetCookie_stack_vars {
   60724       Db *pDb;
   60725     } au;
   60726     struct OP_VerifyCookie_stack_vars {
   60727       int iMeta;
   60728       Btree *pBt;
   60729     } av;
   60730     struct OP_OpenWrite_stack_vars {
   60731       int nField;
   60732       KeyInfo *pKeyInfo;
   60733       int p2;
   60734       int iDb;
   60735       int wrFlag;
   60736       Btree *pX;
   60737       VdbeCursor *pCur;
   60738       Db *pDb;
   60739     } aw;
   60740     struct OP_OpenEphemeral_stack_vars {
   60741       VdbeCursor *pCx;
   60742     } ax;
   60743     struct OP_OpenPseudo_stack_vars {
   60744       VdbeCursor *pCx;
   60745     } ay;
   60746     struct OP_SeekGt_stack_vars {
   60747       int res;
   60748       int oc;
   60749       VdbeCursor *pC;
   60750       UnpackedRecord r;
   60751       int nField;
   60752       i64 iKey;      /* The rowid we are to seek to */
   60753     } az;
   60754     struct OP_Seek_stack_vars {
   60755       VdbeCursor *pC;
   60756     } ba;
   60757     struct OP_Found_stack_vars {
   60758       int alreadyExists;
   60759       VdbeCursor *pC;
   60760       int res;
   60761       UnpackedRecord *pIdxKey;
   60762       UnpackedRecord r;
   60763       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   60764     } bb;
   60765     struct OP_IsUnique_stack_vars {
   60766       u16 ii;
   60767       VdbeCursor *pCx;
   60768       BtCursor *pCrsr;
   60769       u16 nField;
   60770       Mem *aMx;
   60771       UnpackedRecord r;                  /* B-Tree index search key */
   60772       i64 R;                             /* Rowid stored in register P3 */
   60773     } bc;
   60774     struct OP_NotExists_stack_vars {
   60775       VdbeCursor *pC;
   60776       BtCursor *pCrsr;
   60777       int res;
   60778       u64 iKey;
   60779     } bd;
   60780     struct OP_NewRowid_stack_vars {
   60781       i64 v;                 /* The new rowid */
   60782       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   60783       int res;               /* Result of an sqlite3BtreeLast() */
   60784       int cnt;               /* Counter to limit the number of searches */
   60785       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   60786       VdbeFrame *pFrame;     /* Root frame of VDBE */
   60787     } be;
   60788     struct OP_InsertInt_stack_vars {
   60789       Mem *pData;       /* MEM cell holding data for the record to be inserted */
   60790       Mem *pKey;        /* MEM cell holding key  for the record */
   60791       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   60792       VdbeCursor *pC;   /* Cursor to table into which insert is written */
   60793       int nZero;        /* Number of zero-bytes to append */
   60794       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   60795       const char *zDb;  /* database name - used by the update hook */
   60796       const char *zTbl; /* Table name - used by the opdate hook */
   60797       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   60798     } bf;
   60799     struct OP_Delete_stack_vars {
   60800       i64 iKey;
   60801       VdbeCursor *pC;
   60802     } bg;
   60803     struct OP_RowData_stack_vars {
   60804       VdbeCursor *pC;
   60805       BtCursor *pCrsr;
   60806       u32 n;
   60807       i64 n64;
   60808     } bh;
   60809     struct OP_Rowid_stack_vars {
   60810       VdbeCursor *pC;
   60811       i64 v;
   60812       sqlite3_vtab *pVtab;
   60813       const sqlite3_module *pModule;
   60814     } bi;
   60815     struct OP_NullRow_stack_vars {
   60816       VdbeCursor *pC;
   60817     } bj;
   60818     struct OP_Last_stack_vars {
   60819       VdbeCursor *pC;
   60820       BtCursor *pCrsr;
   60821       int res;
   60822     } bk;
   60823     struct OP_Rewind_stack_vars {
   60824       VdbeCursor *pC;
   60825       BtCursor *pCrsr;
   60826       int res;
   60827     } bl;
   60828     struct OP_Next_stack_vars {
   60829       VdbeCursor *pC;
   60830       BtCursor *pCrsr;
   60831       int res;
   60832     } bm;
   60833     struct OP_IdxInsert_stack_vars {
   60834       VdbeCursor *pC;
   60835       BtCursor *pCrsr;
   60836       int nKey;
   60837       const char *zKey;
   60838     } bn;
   60839     struct OP_IdxDelete_stack_vars {
   60840       VdbeCursor *pC;
   60841       BtCursor *pCrsr;
   60842       int res;
   60843       UnpackedRecord r;
   60844     } bo;
   60845     struct OP_IdxRowid_stack_vars {
   60846       BtCursor *pCrsr;
   60847       VdbeCursor *pC;
   60848       i64 rowid;
   60849     } bp;
   60850     struct OP_IdxGE_stack_vars {
   60851       VdbeCursor *pC;
   60852       int res;
   60853       UnpackedRecord r;
   60854     } bq;
   60855     struct OP_Destroy_stack_vars {
   60856       int iMoved;
   60857       int iCnt;
   60858       Vdbe *pVdbe;
   60859       int iDb;
   60860     } br;
   60861     struct OP_Clear_stack_vars {
   60862       int nChange;
   60863     } bs;
   60864     struct OP_CreateTable_stack_vars {
   60865       int pgno;
   60866       int flags;
   60867       Db *pDb;
   60868     } bt;
   60869     struct OP_ParseSchema_stack_vars {
   60870       int iDb;
   60871       const char *zMaster;
   60872       char *zSql;
   60873       InitData initData;
   60874     } bu;
   60875     struct OP_IntegrityCk_stack_vars {
   60876       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   60877       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   60878       int j;          /* Loop counter */
   60879       int nErr;       /* Number of errors reported */
   60880       char *z;        /* Text of the error report */
   60881       Mem *pnErr;     /* Register keeping track of errors remaining */
   60882     } bv;
   60883     struct OP_RowSetRead_stack_vars {
   60884       i64 val;
   60885     } bw;
   60886     struct OP_RowSetTest_stack_vars {
   60887       int iSet;
   60888       int exists;
   60889     } bx;
   60890     struct OP_Program_stack_vars {
   60891       int nMem;               /* Number of memory registers for sub-program */
   60892       int nByte;              /* Bytes of runtime space required for sub-program */
   60893       Mem *pRt;               /* Register to allocate runtime space */
   60894       Mem *pMem;              /* Used to iterate through memory cells */
   60895       Mem *pEnd;              /* Last memory cell in new array */
   60896       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   60897       SubProgram *pProgram;   /* Sub-program to execute */
   60898       void *t;                /* Token identifying trigger */
   60899     } by;
   60900     struct OP_Param_stack_vars {
   60901       VdbeFrame *pFrame;
   60902       Mem *pIn;
   60903     } bz;
   60904     struct OP_MemMax_stack_vars {
   60905       Mem *pIn1;
   60906       VdbeFrame *pFrame;
   60907     } ca;
   60908     struct OP_AggStep_stack_vars {
   60909       int n;
   60910       int i;
   60911       Mem *pMem;
   60912       Mem *pRec;
   60913       sqlite3_context ctx;
   60914       sqlite3_value **apVal;
   60915     } cb;
   60916     struct OP_AggFinal_stack_vars {
   60917       Mem *pMem;
   60918     } cc;
   60919     struct OP_JournalMode_stack_vars {
   60920       Btree *pBt;                     /* Btree to change journal mode of */
   60921       Pager *pPager;                  /* Pager associated with pBt */
   60922       int eNew;                       /* New journal mode */
   60923       int eOld;                       /* The old journal mode */
   60924       const char *zFilename;          /* Name of database file for pPager */
   60925     } cd;
   60926     struct OP_IncrVacuum_stack_vars {
   60927       Btree *pBt;
   60928     } ce;
   60929     struct OP_VBegin_stack_vars {
   60930       VTable *pVTab;
   60931     } cf;
   60932     struct OP_VOpen_stack_vars {
   60933       VdbeCursor *pCur;
   60934       sqlite3_vtab_cursor *pVtabCursor;
   60935       sqlite3_vtab *pVtab;
   60936       sqlite3_module *pModule;
   60937     } cg;
   60938     struct OP_VFilter_stack_vars {
   60939       int nArg;
   60940       int iQuery;
   60941       const sqlite3_module *pModule;
   60942       Mem *pQuery;
   60943       Mem *pArgc;
   60944       sqlite3_vtab_cursor *pVtabCursor;
   60945       sqlite3_vtab *pVtab;
   60946       VdbeCursor *pCur;
   60947       int res;
   60948       int i;
   60949       Mem **apArg;
   60950     } ch;
   60951     struct OP_VColumn_stack_vars {
   60952       sqlite3_vtab *pVtab;
   60953       const sqlite3_module *pModule;
   60954       Mem *pDest;
   60955       sqlite3_context sContext;
   60956     } ci;
   60957     struct OP_VNext_stack_vars {
   60958       sqlite3_vtab *pVtab;
   60959       const sqlite3_module *pModule;
   60960       int res;
   60961       VdbeCursor *pCur;
   60962     } cj;
   60963     struct OP_VRename_stack_vars {
   60964       sqlite3_vtab *pVtab;
   60965       Mem *pName;
   60966     } ck;
   60967     struct OP_VUpdate_stack_vars {
   60968       sqlite3_vtab *pVtab;
   60969       sqlite3_module *pModule;
   60970       int nArg;
   60971       int i;
   60972       sqlite_int64 rowid;
   60973       Mem **apArg;
   60974       Mem *pX;
   60975     } cl;
   60976     struct OP_Trace_stack_vars {
   60977       char *zTrace;
   60978     } cm;
   60979   } u;
   60980   /* End automatically generated code
   60981   ********************************************************************/
   60982 
   60983   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   60984   sqlite3VdbeMutexArrayEnter(p);
   60985   if( p->rc==SQLITE_NOMEM ){
   60986     /* This happens if a malloc() inside a call to sqlite3_column_text() or
   60987     ** sqlite3_column_text16() failed.  */
   60988     goto no_mem;
   60989   }
   60990   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
   60991   p->rc = SQLITE_OK;
   60992   assert( p->explain==0 );
   60993   p->pResultSet = 0;
   60994   db->busyHandler.nBusy = 0;
   60995   CHECK_FOR_INTERRUPT;
   60996   sqlite3VdbeIOTraceSql(p);
   60997 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   60998   checkProgress = db->xProgress!=0;
   60999 #endif
   61000 #ifdef SQLITE_DEBUG
   61001   sqlite3BeginBenignMalloc();
   61002   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
   61003     int i;
   61004     printf("VDBE Program Listing:\n");
   61005     sqlite3VdbePrintSql(p);
   61006     for(i=0; i<p->nOp; i++){
   61007       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
   61008     }
   61009   }
   61010   sqlite3EndBenignMalloc();
   61011 #endif
   61012   for(pc=p->pc; rc==SQLITE_OK; pc++){
   61013     assert( pc>=0 && pc<p->nOp );
   61014     if( db->mallocFailed ) goto no_mem;
   61015 #ifdef VDBE_PROFILE
   61016     origPc = pc;
   61017     start = sqlite3Hwtime();
   61018 #endif
   61019     pOp = &aOp[pc];
   61020 
   61021     /* Only allow tracing if SQLITE_DEBUG is defined.
   61022     */
   61023 #ifdef SQLITE_DEBUG
   61024     if( p->trace ){
   61025       if( pc==0 ){
   61026         printf("VDBE Execution Trace:\n");
   61027         sqlite3VdbePrintSql(p);
   61028       }
   61029       sqlite3VdbePrintOp(p->trace, pc, pOp);
   61030     }
   61031 #endif
   61032 
   61033 
   61034     /* Check to see if we need to simulate an interrupt.  This only happens
   61035     ** if we have a special test build.
   61036     */
   61037 #ifdef SQLITE_TEST
   61038     if( sqlite3_interrupt_count>0 ){
   61039       sqlite3_interrupt_count--;
   61040       if( sqlite3_interrupt_count==0 ){
   61041         sqlite3_interrupt(db);
   61042       }
   61043     }
   61044 #endif
   61045 
   61046 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   61047     /* Call the progress callback if it is configured and the required number
   61048     ** of VDBE ops have been executed (either since this invocation of
   61049     ** sqlite3VdbeExec() or since last time the progress callback was called).
   61050     ** If the progress callback returns non-zero, exit the virtual machine with
   61051     ** a return code SQLITE_ABORT.
   61052     */
   61053     if( checkProgress ){
   61054       if( db->nProgressOps==nProgressOps ){
   61055         int prc;
   61056         prc = db->xProgress(db->pProgressArg);
   61057         if( prc!=0 ){
   61058           rc = SQLITE_INTERRUPT;
   61059           goto vdbe_error_halt;
   61060         }
   61061         nProgressOps = 0;
   61062       }
   61063       nProgressOps++;
   61064     }
   61065 #endif
   61066 
   61067     /* On any opcode with the "out2-prerelase" tag, free any
   61068     ** external allocations out of mem[p2] and set mem[p2] to be
   61069     ** an undefined integer.  Opcodes will either fill in the integer
   61070     ** value or convert mem[p2] to a different type.
   61071     */
   61072     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
   61073     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
   61074       assert( pOp->p2>0 );
   61075       assert( pOp->p2<=p->nMem );
   61076       pOut = &aMem[pOp->p2];
   61077       memAboutToChange(p, pOut);
   61078       sqlite3VdbeMemReleaseExternal(pOut);
   61079       pOut->flags = MEM_Int;
   61080     }
   61081 
   61082     /* Sanity checking on other operands */
   61083 #ifdef SQLITE_DEBUG
   61084     if( (pOp->opflags & OPFLG_IN1)!=0 ){
   61085       assert( pOp->p1>0 );
   61086       assert( pOp->p1<=p->nMem );
   61087       assert( memIsValid(&aMem[pOp->p1]) );
   61088       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   61089     }
   61090     if( (pOp->opflags & OPFLG_IN2)!=0 ){
   61091       assert( pOp->p2>0 );
   61092       assert( pOp->p2<=p->nMem );
   61093       assert( memIsValid(&aMem[pOp->p2]) );
   61094       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   61095     }
   61096     if( (pOp->opflags & OPFLG_IN3)!=0 ){
   61097       assert( pOp->p3>0 );
   61098       assert( pOp->p3<=p->nMem );
   61099       assert( memIsValid(&aMem[pOp->p3]) );
   61100       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   61101     }
   61102     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   61103       assert( pOp->p2>0 );
   61104       assert( pOp->p2<=p->nMem );
   61105       memAboutToChange(p, &aMem[pOp->p2]);
   61106     }
   61107     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
   61108       assert( pOp->p3>0 );
   61109       assert( pOp->p3<=p->nMem );
   61110       memAboutToChange(p, &aMem[pOp->p3]);
   61111     }
   61112 #endif
   61113 
   61114     switch( pOp->opcode ){
   61115 
   61116 /*****************************************************************************
   61117 ** What follows is a massive switch statement where each case implements a
   61118 ** separate instruction in the virtual machine.  If we follow the usual
   61119 ** indentation conventions, each case should be indented by 6 spaces.  But
   61120 ** that is a lot of wasted space on the left margin.  So the code within
   61121 ** the switch statement will break with convention and be flush-left. Another
   61122 ** big comment (similar to this one) will mark the point in the code where
   61123 ** we transition back to normal indentation.
   61124 **
   61125 ** The formatting of each case is important.  The makefile for SQLite
   61126 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
   61127 ** file looking for lines that begin with "case OP_".  The opcodes.h files
   61128 ** will be filled with #defines that give unique integer values to each
   61129 ** opcode and the opcodes.c file is filled with an array of strings where
   61130 ** each string is the symbolic name for the corresponding opcode.  If the
   61131 ** case statement is followed by a comment of the form "/# same as ... #/"
   61132 ** that comment is used to determine the particular value of the opcode.
   61133 **
   61134 ** Other keywords in the comment that follows each case are used to
   61135 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
   61136 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
   61137 ** the mkopcodeh.awk script for additional information.
   61138 **
   61139 ** Documentation about VDBE opcodes is generated by scanning this file
   61140 ** for lines of that contain "Opcode:".  That line and all subsequent
   61141 ** comment lines are used in the generation of the opcode.html documentation
   61142 ** file.
   61143 **
   61144 ** SUMMARY:
   61145 **
   61146 **     Formatting is important to scripts that scan this file.
   61147 **     Do not deviate from the formatting style currently in use.
   61148 **
   61149 *****************************************************************************/
   61150 
   61151 /* Opcode:  Goto * P2 * * *
   61152 **
   61153 ** An unconditional jump to address P2.
   61154 ** The next instruction executed will be
   61155 ** the one at index P2 from the beginning of
   61156 ** the program.
   61157 */
   61158 case OP_Goto: {             /* jump */
   61159   CHECK_FOR_INTERRUPT;
   61160   pc = pOp->p2 - 1;
   61161   break;
   61162 }
   61163 
   61164 /* Opcode:  Gosub P1 P2 * * *
   61165 **
   61166 ** Write the current address onto register P1
   61167 ** and then jump to address P2.
   61168 */
   61169 case OP_Gosub: {            /* jump, in1 */
   61170   pIn1 = &aMem[pOp->p1];
   61171   assert( (pIn1->flags & MEM_Dyn)==0 );
   61172   memAboutToChange(p, pIn1);
   61173   pIn1->flags = MEM_Int;
   61174   pIn1->u.i = pc;
   61175   REGISTER_TRACE(pOp->p1, pIn1);
   61176   pc = pOp->p2 - 1;
   61177   break;
   61178 }
   61179 
   61180 /* Opcode:  Return P1 * * * *
   61181 **
   61182 ** Jump to the next instruction after the address in register P1.
   61183 */
   61184 case OP_Return: {           /* in1 */
   61185   pIn1 = &aMem[pOp->p1];
   61186   assert( pIn1->flags & MEM_Int );
   61187   pc = (int)pIn1->u.i;
   61188   break;
   61189 }
   61190 
   61191 /* Opcode:  Yield P1 * * * *
   61192 **
   61193 ** Swap the program counter with the value in register P1.
   61194 */
   61195 case OP_Yield: {            /* in1 */
   61196 #if 0  /* local variables moved into u.aa */
   61197   int pcDest;
   61198 #endif /* local variables moved into u.aa */
   61199   pIn1 = &aMem[pOp->p1];
   61200   assert( (pIn1->flags & MEM_Dyn)==0 );
   61201   pIn1->flags = MEM_Int;
   61202   u.aa.pcDest = (int)pIn1->u.i;
   61203   pIn1->u.i = pc;
   61204   REGISTER_TRACE(pOp->p1, pIn1);
   61205   pc = u.aa.pcDest;
   61206   break;
   61207 }
   61208 
   61209 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
   61210 **
   61211 ** Check the value in register P3.  If is is NULL then Halt using
   61212 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
   61213 ** value in register P3 is not NULL, then this routine is a no-op.
   61214 */
   61215 case OP_HaltIfNull: {      /* in3 */
   61216   pIn3 = &aMem[pOp->p3];
   61217   if( (pIn3->flags & MEM_Null)==0 ) break;
   61218   /* Fall through into OP_Halt */
   61219 }
   61220 
   61221 /* Opcode:  Halt P1 P2 * P4 *
   61222 **
   61223 ** Exit immediately.  All open cursors, etc are closed
   61224 ** automatically.
   61225 **
   61226 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
   61227 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
   61228 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
   61229 ** whether or not to rollback the current transaction.  Do not rollback
   61230 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
   61231 ** then back out all changes that have occurred during this execution of the
   61232 ** VDBE, but do not rollback the transaction.
   61233 **
   61234 ** If P4 is not null then it is an error message string.
   61235 **
   61236 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
   61237 ** every program.  So a jump past the last instruction of the program
   61238 ** is the same as executing Halt.
   61239 */
   61240 case OP_Halt: {
   61241   if( pOp->p1==SQLITE_OK && p->pFrame ){
   61242     /* Halt the sub-program. Return control to the parent frame. */
   61243     VdbeFrame *pFrame = p->pFrame;
   61244     p->pFrame = pFrame->pParent;
   61245     p->nFrame--;
   61246     sqlite3VdbeSetChanges(db, p->nChange);
   61247     pc = sqlite3VdbeFrameRestore(pFrame);
   61248     if( pOp->p2==OE_Ignore ){
   61249       /* Instruction pc is the OP_Program that invoked the sub-program
   61250       ** currently being halted. If the p2 instruction of this OP_Halt
   61251       ** instruction is set to OE_Ignore, then the sub-program is throwing
   61252       ** an IGNORE exception. In this case jump to the address specified
   61253       ** as the p2 of the calling OP_Program.  */
   61254       pc = p->aOp[pc].p2-1;
   61255     }
   61256     aOp = p->aOp;
   61257     aMem = p->aMem;
   61258     break;
   61259   }
   61260 
   61261   p->rc = pOp->p1;
   61262   p->errorAction = (u8)pOp->p2;
   61263   p->pc = pc;
   61264   if( pOp->p4.z ){
   61265     assert( p->rc!=SQLITE_OK );
   61266     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
   61267     testcase( sqlite3GlobalConfig.xLog!=0 );
   61268     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
   61269   }else if( p->rc ){
   61270     testcase( sqlite3GlobalConfig.xLog!=0 );
   61271     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
   61272   }
   61273   rc = sqlite3VdbeHalt(p);
   61274   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
   61275   if( rc==SQLITE_BUSY ){
   61276     p->rc = rc = SQLITE_BUSY;
   61277   }else{
   61278     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
   61279     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
   61280     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
   61281   }
   61282   goto vdbe_return;
   61283 }
   61284 
   61285 /* Opcode: Integer P1 P2 * * *
   61286 **
   61287 ** The 32-bit integer value P1 is written into register P2.
   61288 */
   61289 case OP_Integer: {         /* out2-prerelease */
   61290   pOut->u.i = pOp->p1;
   61291   break;
   61292 }
   61293 
   61294 /* Opcode: Int64 * P2 * P4 *
   61295 **
   61296 ** P4 is a pointer to a 64-bit integer value.
   61297 ** Write that value into register P2.
   61298 */
   61299 case OP_Int64: {           /* out2-prerelease */
   61300   assert( pOp->p4.pI64!=0 );
   61301   pOut->u.i = *pOp->p4.pI64;
   61302   break;
   61303 }
   61304 
   61305 #ifndef SQLITE_OMIT_FLOATING_POINT
   61306 /* Opcode: Real * P2 * P4 *
   61307 **
   61308 ** P4 is a pointer to a 64-bit floating point value.
   61309 ** Write that value into register P2.
   61310 */
   61311 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
   61312   pOut->flags = MEM_Real;
   61313   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
   61314   pOut->r = *pOp->p4.pReal;
   61315   break;
   61316 }
   61317 #endif
   61318 
   61319 /* Opcode: String8 * P2 * P4 *
   61320 **
   61321 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
   61322 ** into an OP_String before it is executed for the first time.
   61323 */
   61324 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
   61325   assert( pOp->p4.z!=0 );
   61326   pOp->opcode = OP_String;
   61327   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
   61328 
   61329 #ifndef SQLITE_OMIT_UTF16
   61330   if( encoding!=SQLITE_UTF8 ){
   61331     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   61332     if( rc==SQLITE_TOOBIG ) goto too_big;
   61333     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   61334     assert( pOut->zMalloc==pOut->z );
   61335     assert( pOut->flags & MEM_Dyn );
   61336     pOut->zMalloc = 0;
   61337     pOut->flags |= MEM_Static;
   61338     pOut->flags &= ~MEM_Dyn;
   61339     if( pOp->p4type==P4_DYNAMIC ){
   61340       sqlite3DbFree(db, pOp->p4.z);
   61341     }
   61342     pOp->p4type = P4_DYNAMIC;
   61343     pOp->p4.z = pOut->z;
   61344     pOp->p1 = pOut->n;
   61345   }
   61346 #endif
   61347   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   61348     goto too_big;
   61349   }
   61350   /* Fall through to the next case, OP_String */
   61351 }
   61352 
   61353 /* Opcode: String P1 P2 * P4 *
   61354 **
   61355 ** The string value P4 of length P1 (bytes) is stored in register P2.
   61356 */
   61357 case OP_String: {          /* out2-prerelease */
   61358   assert( pOp->p4.z!=0 );
   61359   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   61360   pOut->z = pOp->p4.z;
   61361   pOut->n = pOp->p1;
   61362   pOut->enc = encoding;
   61363   UPDATE_MAX_BLOBSIZE(pOut);
   61364   break;
   61365 }
   61366 
   61367 /* Opcode: Null * P2 * * *
   61368 **
   61369 ** Write a NULL into register P2.
   61370 */
   61371 case OP_Null: {           /* out2-prerelease */
   61372   pOut->flags = MEM_Null;
   61373   break;
   61374 }
   61375 
   61376 
   61377 /* Opcode: Blob P1 P2 * P4
   61378 **
   61379 ** P4 points to a blob of data P1 bytes long.  Store this
   61380 ** blob in register P2.
   61381 */
   61382 case OP_Blob: {                /* out2-prerelease */
   61383   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
   61384   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
   61385   pOut->enc = encoding;
   61386   UPDATE_MAX_BLOBSIZE(pOut);
   61387   break;
   61388 }
   61389 
   61390 /* Opcode: Variable P1 P2 * P4 *
   61391 **
   61392 ** Transfer the values of bound parameter P1 into register P2
   61393 **
   61394 ** If the parameter is named, then its name appears in P4 and P3==1.
   61395 ** The P4 value is used by sqlite3_bind_parameter_name().
   61396 */
   61397 case OP_Variable: {            /* out2-prerelease */
   61398 #if 0  /* local variables moved into u.ab */
   61399   Mem *pVar;       /* Value being transferred */
   61400 #endif /* local variables moved into u.ab */
   61401 
   61402   assert( pOp->p1>0 && pOp->p1<=p->nVar );
   61403   u.ab.pVar = &p->aVar[pOp->p1 - 1];
   61404   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
   61405     goto too_big;
   61406   }
   61407   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
   61408   UPDATE_MAX_BLOBSIZE(pOut);
   61409   break;
   61410 }
   61411 
   61412 /* Opcode: Move P1 P2 P3 * *
   61413 **
   61414 ** Move the values in register P1..P1+P3-1 over into
   61415 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
   61416 ** left holding a NULL.  It is an error for register ranges
   61417 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
   61418 */
   61419 case OP_Move: {
   61420 #if 0  /* local variables moved into u.ac */
   61421   char *zMalloc;   /* Holding variable for allocated memory */
   61422   int n;           /* Number of registers left to copy */
   61423   int p1;          /* Register to copy from */
   61424   int p2;          /* Register to copy to */
   61425 #endif /* local variables moved into u.ac */
   61426 
   61427   u.ac.n = pOp->p3;
   61428   u.ac.p1 = pOp->p1;
   61429   u.ac.p2 = pOp->p2;
   61430   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
   61431   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
   61432 
   61433   pIn1 = &aMem[u.ac.p1];
   61434   pOut = &aMem[u.ac.p2];
   61435   while( u.ac.n-- ){
   61436     assert( pOut<=&aMem[p->nMem] );
   61437     assert( pIn1<=&aMem[p->nMem] );
   61438     assert( memIsValid(pIn1) );
   61439     memAboutToChange(p, pOut);
   61440     u.ac.zMalloc = pOut->zMalloc;
   61441     pOut->zMalloc = 0;
   61442     sqlite3VdbeMemMove(pOut, pIn1);
   61443     pIn1->zMalloc = u.ac.zMalloc;
   61444     REGISTER_TRACE(u.ac.p2++, pOut);
   61445     pIn1++;
   61446     pOut++;
   61447   }
   61448   break;
   61449 }
   61450 
   61451 /* Opcode: Copy P1 P2 * * *
   61452 **
   61453 ** Make a copy of register P1 into register P2.
   61454 **
   61455 ** This instruction makes a deep copy of the value.  A duplicate
   61456 ** is made of any string or blob constant.  See also OP_SCopy.
   61457 */
   61458 case OP_Copy: {             /* in1, out2 */
   61459   pIn1 = &aMem[pOp->p1];
   61460   pOut = &aMem[pOp->p2];
   61461   assert( pOut!=pIn1 );
   61462   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   61463   Deephemeralize(pOut);
   61464   REGISTER_TRACE(pOp->p2, pOut);
   61465   break;
   61466 }
   61467 
   61468 /* Opcode: SCopy P1 P2 * * *
   61469 **
   61470 ** Make a shallow copy of register P1 into register P2.
   61471 **
   61472 ** This instruction makes a shallow copy of the value.  If the value
   61473 ** is a string or blob, then the copy is only a pointer to the
   61474 ** original and hence if the original changes so will the copy.
   61475 ** Worse, if the original is deallocated, the copy becomes invalid.
   61476 ** Thus the program must guarantee that the original will not change
   61477 ** during the lifetime of the copy.  Use OP_Copy to make a complete
   61478 ** copy.
   61479 */
   61480 case OP_SCopy: {            /* in1, out2 */
   61481   pIn1 = &aMem[pOp->p1];
   61482   pOut = &aMem[pOp->p2];
   61483   assert( pOut!=pIn1 );
   61484   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
   61485 #ifdef SQLITE_DEBUG
   61486   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
   61487 #endif
   61488   REGISTER_TRACE(pOp->p2, pOut);
   61489   break;
   61490 }
   61491 
   61492 /* Opcode: ResultRow P1 P2 * * *
   61493 **
   61494 ** The registers P1 through P1+P2-1 contain a single row of
   61495 ** results. This opcode causes the sqlite3_step() call to terminate
   61496 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
   61497 ** structure to provide access to the top P1 values as the result
   61498 ** row.
   61499 */
   61500 case OP_ResultRow: {
   61501 #if 0  /* local variables moved into u.ad */
   61502   Mem *pMem;
   61503   int i;
   61504 #endif /* local variables moved into u.ad */
   61505   assert( p->nResColumn==pOp->p2 );
   61506   assert( pOp->p1>0 );
   61507   assert( pOp->p1+pOp->p2<=p->nMem+1 );
   61508 
   61509   /* If this statement has violated immediate foreign key constraints, do
   61510   ** not return the number of rows modified. And do not RELEASE the statement
   61511   ** transaction. It needs to be rolled back.  */
   61512   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
   61513     assert( db->flags&SQLITE_CountRows );
   61514     assert( p->usesStmtJournal );
   61515     break;
   61516   }
   61517 
   61518   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
   61519   ** DML statements invoke this opcode to return the number of rows
   61520   ** modified to the user. This is the only way that a VM that
   61521   ** opens a statement transaction may invoke this opcode.
   61522   **
   61523   ** In case this is such a statement, close any statement transaction
   61524   ** opened by this VM before returning control to the user. This is to
   61525   ** ensure that statement-transactions are always nested, not overlapping.
   61526   ** If the open statement-transaction is not closed here, then the user
   61527   ** may step another VM that opens its own statement transaction. This
   61528   ** may lead to overlapping statement transactions.
   61529   **
   61530   ** The statement transaction is never a top-level transaction.  Hence
   61531   ** the RELEASE call below can never fail.
   61532   */
   61533   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
   61534   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
   61535   if( NEVER(rc!=SQLITE_OK) ){
   61536     break;
   61537   }
   61538 
   61539   /* Invalidate all ephemeral cursor row caches */
   61540   p->cacheCtr = (p->cacheCtr + 2)|1;
   61541 
   61542   /* Make sure the results of the current row are \000 terminated
   61543   ** and have an assigned type.  The results are de-ephemeralized as
   61544   ** as side effect.
   61545   */
   61546   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
   61547   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
   61548     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
   61549     Deephemeralize(&u.ad.pMem[u.ad.i]);
   61550     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
   61551             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
   61552     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
   61553     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
   61554     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
   61555   }
   61556   if( db->mallocFailed ) goto no_mem;
   61557 
   61558   /* Return SQLITE_ROW
   61559   */
   61560   p->pc = pc + 1;
   61561   rc = SQLITE_ROW;
   61562   goto vdbe_return;
   61563 }
   61564 
   61565 /* Opcode: Concat P1 P2 P3 * *
   61566 **
   61567 ** Add the text in register P1 onto the end of the text in
   61568 ** register P2 and store the result in register P3.
   61569 ** If either the P1 or P2 text are NULL then store NULL in P3.
   61570 **
   61571 **   P3 = P2 || P1
   61572 **
   61573 ** It is illegal for P1 and P3 to be the same register. Sometimes,
   61574 ** if P3 is the same register as P2, the implementation is able
   61575 ** to avoid a memcpy().
   61576 */
   61577 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   61578 #if 0  /* local variables moved into u.ae */
   61579   i64 nByte;
   61580 #endif /* local variables moved into u.ae */
   61581 
   61582   pIn1 = &aMem[pOp->p1];
   61583   pIn2 = &aMem[pOp->p2];
   61584   pOut = &aMem[pOp->p3];
   61585   assert( pIn1!=pOut );
   61586   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   61587     sqlite3VdbeMemSetNull(pOut);
   61588     break;
   61589   }
   61590   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
   61591   Stringify(pIn1, encoding);
   61592   Stringify(pIn2, encoding);
   61593   u.ae.nByte = pIn1->n + pIn2->n;
   61594   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   61595     goto too_big;
   61596   }
   61597   MemSetTypeFlag(pOut, MEM_Str);
   61598   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
   61599     goto no_mem;
   61600   }
   61601   if( pOut!=pIn2 ){
   61602     memcpy(pOut->z, pIn2->z, pIn2->n);
   61603   }
   61604   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
   61605   pOut->z[u.ae.nByte] = 0;
   61606   pOut->z[u.ae.nByte+1] = 0;
   61607   pOut->flags |= MEM_Term;
   61608   pOut->n = (int)u.ae.nByte;
   61609   pOut->enc = encoding;
   61610   UPDATE_MAX_BLOBSIZE(pOut);
   61611   break;
   61612 }
   61613 
   61614 /* Opcode: Add P1 P2 P3 * *
   61615 **
   61616 ** Add the value in register P1 to the value in register P2
   61617 ** and store the result in register P3.
   61618 ** If either input is NULL, the result is NULL.
   61619 */
   61620 /* Opcode: Multiply P1 P2 P3 * *
   61621 **
   61622 **
   61623 ** Multiply the value in register P1 by the value in register P2
   61624 ** and store the result in register P3.
   61625 ** If either input is NULL, the result is NULL.
   61626 */
   61627 /* Opcode: Subtract P1 P2 P3 * *
   61628 **
   61629 ** Subtract the value in register P1 from the value in register P2
   61630 ** and store the result in register P3.
   61631 ** If either input is NULL, the result is NULL.
   61632 */
   61633 /* Opcode: Divide P1 P2 P3 * *
   61634 **
   61635 ** Divide the value in register P1 by the value in register P2
   61636 ** and store the result in register P3 (P3=P2/P1). If the value in
   61637 ** register P1 is zero, then the result is NULL. If either input is
   61638 ** NULL, the result is NULL.
   61639 */
   61640 /* Opcode: Remainder P1 P2 P3 * *
   61641 **
   61642 ** Compute the remainder after integer division of the value in
   61643 ** register P1 by the value in register P2 and store the result in P3.
   61644 ** If the value in register P2 is zero the result is NULL.
   61645 ** If either operand is NULL, the result is NULL.
   61646 */
   61647 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
   61648 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
   61649 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
   61650 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
   61651 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
   61652 #if 0  /* local variables moved into u.af */
   61653   int flags;      /* Combined MEM_* flags from both inputs */
   61654   i64 iA;         /* Integer value of left operand */
   61655   i64 iB;         /* Integer value of right operand */
   61656   double rA;      /* Real value of left operand */
   61657   double rB;      /* Real value of right operand */
   61658 #endif /* local variables moved into u.af */
   61659 
   61660   pIn1 = &aMem[pOp->p1];
   61661   applyNumericAffinity(pIn1);
   61662   pIn2 = &aMem[pOp->p2];
   61663   applyNumericAffinity(pIn2);
   61664   pOut = &aMem[pOp->p3];
   61665   u.af.flags = pIn1->flags | pIn2->flags;
   61666   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
   61667   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
   61668     u.af.iA = pIn1->u.i;
   61669     u.af.iB = pIn2->u.i;
   61670     switch( pOp->opcode ){
   61671       case OP_Add:         u.af.iB += u.af.iA;       break;
   61672       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
   61673       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
   61674       case OP_Divide: {
   61675         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   61676         /* Dividing the largest possible negative 64-bit integer (1<<63) by
   61677         ** -1 returns an integer too large to store in a 64-bit data-type. On
   61678         ** some architectures, the value overflows to (1<<63). On others,
   61679         ** a SIGFPE is issued. The following statement normalizes this
   61680         ** behavior so that all architectures behave as if integer
   61681         ** overflow occurred.
   61682         */
   61683         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
   61684         u.af.iB /= u.af.iA;
   61685         break;
   61686       }
   61687       default: {
   61688         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   61689         if( u.af.iA==-1 ) u.af.iA = 1;
   61690         u.af.iB %= u.af.iA;
   61691         break;
   61692       }
   61693     }
   61694     pOut->u.i = u.af.iB;
   61695     MemSetTypeFlag(pOut, MEM_Int);
   61696   }else{
   61697     u.af.rA = sqlite3VdbeRealValue(pIn1);
   61698     u.af.rB = sqlite3VdbeRealValue(pIn2);
   61699     switch( pOp->opcode ){
   61700       case OP_Add:         u.af.rB += u.af.rA;       break;
   61701       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
   61702       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
   61703       case OP_Divide: {
   61704         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   61705         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
   61706         u.af.rB /= u.af.rA;
   61707         break;
   61708       }
   61709       default: {
   61710         u.af.iA = (i64)u.af.rA;
   61711         u.af.iB = (i64)u.af.rB;
   61712         if( u.af.iA==0 ) goto arithmetic_result_is_null;
   61713         if( u.af.iA==-1 ) u.af.iA = 1;
   61714         u.af.rB = (double)(u.af.iB % u.af.iA);
   61715         break;
   61716       }
   61717     }
   61718 #ifdef SQLITE_OMIT_FLOATING_POINT
   61719     pOut->u.i = u.af.rB;
   61720     MemSetTypeFlag(pOut, MEM_Int);
   61721 #else
   61722     if( sqlite3IsNaN(u.af.rB) ){
   61723       goto arithmetic_result_is_null;
   61724     }
   61725     pOut->r = u.af.rB;
   61726     MemSetTypeFlag(pOut, MEM_Real);
   61727     if( (u.af.flags & MEM_Real)==0 ){
   61728       sqlite3VdbeIntegerAffinity(pOut);
   61729     }
   61730 #endif
   61731   }
   61732   break;
   61733 
   61734 arithmetic_result_is_null:
   61735   sqlite3VdbeMemSetNull(pOut);
   61736   break;
   61737 }
   61738 
   61739 /* Opcode: CollSeq * * P4
   61740 **
   61741 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
   61742 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
   61743 ** be returned. This is used by the built-in min(), max() and nullif()
   61744 ** functions.
   61745 **
   61746 ** The interface used by the implementation of the aforementioned functions
   61747 ** to retrieve the collation sequence set by this opcode is not available
   61748 ** publicly, only to user functions defined in func.c.
   61749 */
   61750 case OP_CollSeq: {
   61751   assert( pOp->p4type==P4_COLLSEQ );
   61752   break;
   61753 }
   61754 
   61755 /* Opcode: Function P1 P2 P3 P4 P5
   61756 **
   61757 ** Invoke a user function (P4 is a pointer to a Function structure that
   61758 ** defines the function) with P5 arguments taken from register P2 and
   61759 ** successors.  The result of the function is stored in register P3.
   61760 ** Register P3 must not be one of the function inputs.
   61761 **
   61762 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
   61763 ** function was determined to be constant at compile time. If the first
   61764 ** argument was constant then bit 0 of P1 is set. This is used to determine
   61765 ** whether meta data associated with a user function argument using the
   61766 ** sqlite3_set_auxdata() API may be safely retained until the next
   61767 ** invocation of this opcode.
   61768 **
   61769 ** See also: AggStep and AggFinal
   61770 */
   61771 case OP_Function: {
   61772 #if 0  /* local variables moved into u.ag */
   61773   int i;
   61774   Mem *pArg;
   61775   sqlite3_context ctx;
   61776   sqlite3_value **apVal;
   61777   int n;
   61778 #endif /* local variables moved into u.ag */
   61779 
   61780   u.ag.n = pOp->p5;
   61781   u.ag.apVal = p->apArg;
   61782   assert( u.ag.apVal || u.ag.n==0 );
   61783   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   61784   pOut = &aMem[pOp->p3];
   61785   memAboutToChange(p, pOut);
   61786 
   61787   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
   61788   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
   61789   u.ag.pArg = &aMem[pOp->p2];
   61790   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
   61791     assert( memIsValid(u.ag.pArg) );
   61792     u.ag.apVal[u.ag.i] = u.ag.pArg;
   61793     Deephemeralize(u.ag.pArg);
   61794     sqlite3VdbeMemStoreType(u.ag.pArg);
   61795     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
   61796   }
   61797 
   61798   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
   61799   if( pOp->p4type==P4_FUNCDEF ){
   61800     u.ag.ctx.pFunc = pOp->p4.pFunc;
   61801     u.ag.ctx.pVdbeFunc = 0;
   61802   }else{
   61803     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
   61804     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
   61805   }
   61806 
   61807   u.ag.ctx.s.flags = MEM_Null;
   61808   u.ag.ctx.s.db = db;
   61809   u.ag.ctx.s.xDel = 0;
   61810   u.ag.ctx.s.zMalloc = 0;
   61811 
   61812   /* The output cell may already have a buffer allocated. Move
   61813   ** the pointer to u.ag.ctx.s so in case the user-function can use
   61814   ** the already allocated buffer instead of allocating a new one.
   61815   */
   61816   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
   61817   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
   61818 
   61819   u.ag.ctx.isError = 0;
   61820   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   61821     assert( pOp>aOp );
   61822     assert( pOp[-1].p4type==P4_COLLSEQ );
   61823     assert( pOp[-1].opcode==OP_CollSeq );
   61824     u.ag.ctx.pColl = pOp[-1].p4.pColl;
   61825   }
   61826   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
   61827   if( db->mallocFailed ){
   61828     /* Even though a malloc() has failed, the implementation of the
   61829     ** user function may have called an sqlite3_result_XXX() function
   61830     ** to return a value. The following call releases any resources
   61831     ** associated with such a value.
   61832     */
   61833     sqlite3VdbeMemRelease(&u.ag.ctx.s);
   61834     goto no_mem;
   61835   }
   61836 
   61837   /* If any auxiliary data functions have been called by this user function,
   61838   ** immediately call the destructor for any non-static values.
   61839   */
   61840   if( u.ag.ctx.pVdbeFunc ){
   61841     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
   61842     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
   61843     pOp->p4type = P4_VDBEFUNC;
   61844   }
   61845 
   61846   /* If the function returned an error, throw an exception */
   61847   if( u.ag.ctx.isError ){
   61848     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
   61849     rc = u.ag.ctx.isError;
   61850   }
   61851 
   61852   /* Copy the result of the function into register P3 */
   61853   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
   61854   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
   61855   if( sqlite3VdbeMemTooBig(pOut) ){
   61856     goto too_big;
   61857   }
   61858   REGISTER_TRACE(pOp->p3, pOut);
   61859   UPDATE_MAX_BLOBSIZE(pOut);
   61860   break;
   61861 }
   61862 
   61863 /* Opcode: BitAnd P1 P2 P3 * *
   61864 **
   61865 ** Take the bit-wise AND of the values in register P1 and P2 and
   61866 ** store the result in register P3.
   61867 ** If either input is NULL, the result is NULL.
   61868 */
   61869 /* Opcode: BitOr P1 P2 P3 * *
   61870 **
   61871 ** Take the bit-wise OR of the values in register P1 and P2 and
   61872 ** store the result in register P3.
   61873 ** If either input is NULL, the result is NULL.
   61874 */
   61875 /* Opcode: ShiftLeft P1 P2 P3 * *
   61876 **
   61877 ** Shift the integer value in register P2 to the left by the
   61878 ** number of bits specified by the integer in register P1.
   61879 ** Store the result in register P3.
   61880 ** If either input is NULL, the result is NULL.
   61881 */
   61882 /* Opcode: ShiftRight P1 P2 P3 * *
   61883 **
   61884 ** Shift the integer value in register P2 to the right by the
   61885 ** number of bits specified by the integer in register P1.
   61886 ** Store the result in register P3.
   61887 ** If either input is NULL, the result is NULL.
   61888 */
   61889 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
   61890 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
   61891 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
   61892 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
   61893 #if 0  /* local variables moved into u.ah */
   61894   i64 a;
   61895   i64 b;
   61896 #endif /* local variables moved into u.ah */
   61897 
   61898   pIn1 = &aMem[pOp->p1];
   61899   pIn2 = &aMem[pOp->p2];
   61900   pOut = &aMem[pOp->p3];
   61901   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
   61902     sqlite3VdbeMemSetNull(pOut);
   61903     break;
   61904   }
   61905   u.ah.a = sqlite3VdbeIntValue(pIn2);
   61906   u.ah.b = sqlite3VdbeIntValue(pIn1);
   61907   switch( pOp->opcode ){
   61908     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
   61909     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
   61910     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
   61911     default:  assert( pOp->opcode==OP_ShiftRight );
   61912                          u.ah.a >>= u.ah.b;    break;
   61913   }
   61914   pOut->u.i = u.ah.a;
   61915   MemSetTypeFlag(pOut, MEM_Int);
   61916   break;
   61917 }
   61918 
   61919 /* Opcode: AddImm  P1 P2 * * *
   61920 **
   61921 ** Add the constant P2 to the value in register P1.
   61922 ** The result is always an integer.
   61923 **
   61924 ** To force any register to be an integer, just add 0.
   61925 */
   61926 case OP_AddImm: {            /* in1 */
   61927   pIn1 = &aMem[pOp->p1];
   61928   memAboutToChange(p, pIn1);
   61929   sqlite3VdbeMemIntegerify(pIn1);
   61930   pIn1->u.i += pOp->p2;
   61931   break;
   61932 }
   61933 
   61934 /* Opcode: MustBeInt P1 P2 * * *
   61935 **
   61936 ** Force the value in register P1 to be an integer.  If the value
   61937 ** in P1 is not an integer and cannot be converted into an integer
   61938 ** without data loss, then jump immediately to P2, or if P2==0
   61939 ** raise an SQLITE_MISMATCH exception.
   61940 */
   61941 case OP_MustBeInt: {            /* jump, in1 */
   61942   pIn1 = &aMem[pOp->p1];
   61943   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
   61944   if( (pIn1->flags & MEM_Int)==0 ){
   61945     if( pOp->p2==0 ){
   61946       rc = SQLITE_MISMATCH;
   61947       goto abort_due_to_error;
   61948     }else{
   61949       pc = pOp->p2 - 1;
   61950     }
   61951   }else{
   61952     MemSetTypeFlag(pIn1, MEM_Int);
   61953   }
   61954   break;
   61955 }
   61956 
   61957 #ifndef SQLITE_OMIT_FLOATING_POINT
   61958 /* Opcode: RealAffinity P1 * * * *
   61959 **
   61960 ** If register P1 holds an integer convert it to a real value.
   61961 **
   61962 ** This opcode is used when extracting information from a column that
   61963 ** has REAL affinity.  Such column values may still be stored as
   61964 ** integers, for space efficiency, but after extraction we want them
   61965 ** to have only a real value.
   61966 */
   61967 case OP_RealAffinity: {                  /* in1 */
   61968   pIn1 = &aMem[pOp->p1];
   61969   if( pIn1->flags & MEM_Int ){
   61970     sqlite3VdbeMemRealify(pIn1);
   61971   }
   61972   break;
   61973 }
   61974 #endif
   61975 
   61976 #ifndef SQLITE_OMIT_CAST
   61977 /* Opcode: ToText P1 * * * *
   61978 **
   61979 ** Force the value in register P1 to be text.
   61980 ** If the value is numeric, convert it to a string using the
   61981 ** equivalent of printf().  Blob values are unchanged and
   61982 ** are afterwards simply interpreted as text.
   61983 **
   61984 ** A NULL value is not changed by this routine.  It remains NULL.
   61985 */
   61986 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
   61987   pIn1 = &aMem[pOp->p1];
   61988   memAboutToChange(p, pIn1);
   61989   if( pIn1->flags & MEM_Null ) break;
   61990   assert( MEM_Str==(MEM_Blob>>3) );
   61991   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
   61992   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   61993   rc = ExpandBlob(pIn1);
   61994   assert( pIn1->flags & MEM_Str || db->mallocFailed );
   61995   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
   61996   UPDATE_MAX_BLOBSIZE(pIn1);
   61997   break;
   61998 }
   61999 
   62000 /* Opcode: ToBlob P1 * * * *
   62001 **
   62002 ** Force the value in register P1 to be a BLOB.
   62003 ** If the value is numeric, convert it to a string first.
   62004 ** Strings are simply reinterpreted as blobs with no change
   62005 ** to the underlying data.
   62006 **
   62007 ** A NULL value is not changed by this routine.  It remains NULL.
   62008 */
   62009 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
   62010   pIn1 = &aMem[pOp->p1];
   62011   if( pIn1->flags & MEM_Null ) break;
   62012   if( (pIn1->flags & MEM_Blob)==0 ){
   62013     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
   62014     assert( pIn1->flags & MEM_Str || db->mallocFailed );
   62015     MemSetTypeFlag(pIn1, MEM_Blob);
   62016   }else{
   62017     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
   62018   }
   62019   UPDATE_MAX_BLOBSIZE(pIn1);
   62020   break;
   62021 }
   62022 
   62023 /* Opcode: ToNumeric P1 * * * *
   62024 **
   62025 ** Force the value in register P1 to be numeric (either an
   62026 ** integer or a floating-point number.)
   62027 ** If the value is text or blob, try to convert it to an using the
   62028 ** equivalent of atoi() or atof() and store 0 if no such conversion
   62029 ** is possible.
   62030 **
   62031 ** A NULL value is not changed by this routine.  It remains NULL.
   62032 */
   62033 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
   62034   pIn1 = &aMem[pOp->p1];
   62035   sqlite3VdbeMemNumerify(pIn1);
   62036   break;
   62037 }
   62038 #endif /* SQLITE_OMIT_CAST */
   62039 
   62040 /* Opcode: ToInt P1 * * * *
   62041 **
   62042 ** Force the value in register P1 to be an integer.  If
   62043 ** The value is currently a real number, drop its fractional part.
   62044 ** If the value is text or blob, try to convert it to an integer using the
   62045 ** equivalent of atoi() and store 0 if no such conversion is possible.
   62046 **
   62047 ** A NULL value is not changed by this routine.  It remains NULL.
   62048 */
   62049 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
   62050   pIn1 = &aMem[pOp->p1];
   62051   if( (pIn1->flags & MEM_Null)==0 ){
   62052     sqlite3VdbeMemIntegerify(pIn1);
   62053   }
   62054   break;
   62055 }
   62056 
   62057 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
   62058 /* Opcode: ToReal P1 * * * *
   62059 **
   62060 ** Force the value in register P1 to be a floating point number.
   62061 ** If The value is currently an integer, convert it.
   62062 ** If the value is text or blob, try to convert it to an integer using the
   62063 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
   62064 **
   62065 ** A NULL value is not changed by this routine.  It remains NULL.
   62066 */
   62067 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
   62068   pIn1 = &aMem[pOp->p1];
   62069   memAboutToChange(p, pIn1);
   62070   if( (pIn1->flags & MEM_Null)==0 ){
   62071     sqlite3VdbeMemRealify(pIn1);
   62072   }
   62073   break;
   62074 }
   62075 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
   62076 
   62077 /* Opcode: Lt P1 P2 P3 P4 P5
   62078 **
   62079 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
   62080 ** jump to address P2.
   62081 **
   62082 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
   62083 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
   62084 ** bit is clear then fall through if either operand is NULL.
   62085 **
   62086 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
   62087 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
   62088 ** to coerce both inputs according to this affinity before the
   62089 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
   62090 ** affinity is used. Note that the affinity conversions are stored
   62091 ** back into the input registers P1 and P3.  So this opcode can cause
   62092 ** persistent changes to registers P1 and P3.
   62093 **
   62094 ** Once any conversions have taken place, and neither value is NULL,
   62095 ** the values are compared. If both values are blobs then memcmp() is
   62096 ** used to determine the results of the comparison.  If both values
   62097 ** are text, then the appropriate collating function specified in
   62098 ** P4 is  used to do the comparison.  If P4 is not specified then
   62099 ** memcmp() is used to compare text string.  If both values are
   62100 ** numeric, then a numeric comparison is used. If the two values
   62101 ** are of different types, then numbers are considered less than
   62102 ** strings and strings are considered less than blobs.
   62103 **
   62104 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
   62105 ** store a boolean result (either 0, or 1, or NULL) in register P2.
   62106 */
   62107 /* Opcode: Ne P1 P2 P3 P4 P5
   62108 **
   62109 ** This works just like the Lt opcode except that the jump is taken if
   62110 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
   62111 ** additional information.
   62112 **
   62113 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   62114 ** true or false and is never NULL.  If both operands are NULL then the result
   62115 ** of comparison is false.  If either operand is NULL then the result is true.
   62116 ** If neither operand is NULL the the result is the same as it would be if
   62117 ** the SQLITE_NULLEQ flag were omitted from P5.
   62118 */
   62119 /* Opcode: Eq P1 P2 P3 P4 P5
   62120 **
   62121 ** This works just like the Lt opcode except that the jump is taken if
   62122 ** the operands in registers P1 and P3 are equal.
   62123 ** See the Lt opcode for additional information.
   62124 **
   62125 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
   62126 ** true or false and is never NULL.  If both operands are NULL then the result
   62127 ** of comparison is true.  If either operand is NULL then the result is false.
   62128 ** If neither operand is NULL the the result is the same as it would be if
   62129 ** the SQLITE_NULLEQ flag were omitted from P5.
   62130 */
   62131 /* Opcode: Le P1 P2 P3 P4 P5
   62132 **
   62133 ** This works just like the Lt opcode except that the jump is taken if
   62134 ** the content of register P3 is less than or equal to the content of
   62135 ** register P1.  See the Lt opcode for additional information.
   62136 */
   62137 /* Opcode: Gt P1 P2 P3 P4 P5
   62138 **
   62139 ** This works just like the Lt opcode except that the jump is taken if
   62140 ** the content of register P3 is greater than the content of
   62141 ** register P1.  See the Lt opcode for additional information.
   62142 */
   62143 /* Opcode: Ge P1 P2 P3 P4 P5
   62144 **
   62145 ** This works just like the Lt opcode except that the jump is taken if
   62146 ** the content of register P3 is greater than or equal to the content of
   62147 ** register P1.  See the Lt opcode for additional information.
   62148 */
   62149 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
   62150 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
   62151 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
   62152 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
   62153 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
   62154 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
   62155 #if 0  /* local variables moved into u.ai */
   62156   int res;            /* Result of the comparison of pIn1 against pIn3 */
   62157   char affinity;      /* Affinity to use for comparison */
   62158   u16 flags1;         /* Copy of initial value of pIn1->flags */
   62159   u16 flags3;         /* Copy of initial value of pIn3->flags */
   62160 #endif /* local variables moved into u.ai */
   62161 
   62162   pIn1 = &aMem[pOp->p1];
   62163   pIn3 = &aMem[pOp->p3];
   62164   u.ai.flags1 = pIn1->flags;
   62165   u.ai.flags3 = pIn3->flags;
   62166   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
   62167     /* One or both operands are NULL */
   62168     if( pOp->p5 & SQLITE_NULLEQ ){
   62169       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
   62170       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
   62171       ** or not both operands are null.
   62172       */
   62173       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
   62174       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
   62175     }else{
   62176       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
   62177       ** then the result is always NULL.
   62178       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
   62179       */
   62180       if( pOp->p5 & SQLITE_STOREP2 ){
   62181         pOut = &aMem[pOp->p2];
   62182         MemSetTypeFlag(pOut, MEM_Null);
   62183         REGISTER_TRACE(pOp->p2, pOut);
   62184       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
   62185         pc = pOp->p2-1;
   62186       }
   62187       break;
   62188     }
   62189   }else{
   62190     /* Neither operand is NULL.  Do a comparison. */
   62191     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
   62192     if( u.ai.affinity ){
   62193       applyAffinity(pIn1, u.ai.affinity, encoding);
   62194       applyAffinity(pIn3, u.ai.affinity, encoding);
   62195       if( db->mallocFailed ) goto no_mem;
   62196     }
   62197 
   62198     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
   62199     ExpandBlob(pIn1);
   62200     ExpandBlob(pIn3);
   62201     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
   62202   }
   62203   switch( pOp->opcode ){
   62204     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
   62205     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
   62206     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
   62207     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
   62208     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
   62209     default:       u.ai.res = u.ai.res>=0;     break;
   62210   }
   62211 
   62212   if( pOp->p5 & SQLITE_STOREP2 ){
   62213     pOut = &aMem[pOp->p2];
   62214     memAboutToChange(p, pOut);
   62215     MemSetTypeFlag(pOut, MEM_Int);
   62216     pOut->u.i = u.ai.res;
   62217     REGISTER_TRACE(pOp->p2, pOut);
   62218   }else if( u.ai.res ){
   62219     pc = pOp->p2-1;
   62220   }
   62221 
   62222   /* Undo any changes made by applyAffinity() to the input registers. */
   62223   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
   62224   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
   62225   break;
   62226 }
   62227 
   62228 /* Opcode: Permutation * * * P4 *
   62229 **
   62230 ** Set the permutation used by the OP_Compare operator to be the array
   62231 ** of integers in P4.
   62232 **
   62233 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
   62234 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
   62235 ** immediately prior to the OP_Compare.
   62236 */
   62237 case OP_Permutation: {
   62238   assert( pOp->p4type==P4_INTARRAY );
   62239   assert( pOp->p4.ai );
   62240   aPermute = pOp->p4.ai;
   62241   break;
   62242 }
   62243 
   62244 /* Opcode: Compare P1 P2 P3 P4 *
   62245 **
   62246 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
   62247 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
   62248 ** the comparison for use by the next OP_Jump instruct.
   62249 **
   62250 ** P4 is a KeyInfo structure that defines collating sequences and sort
   62251 ** orders for the comparison.  The permutation applies to registers
   62252 ** only.  The KeyInfo elements are used sequentially.
   62253 **
   62254 ** The comparison is a sort comparison, so NULLs compare equal,
   62255 ** NULLs are less than numbers, numbers are less than strings,
   62256 ** and strings are less than blobs.
   62257 */
   62258 case OP_Compare: {
   62259 #if 0  /* local variables moved into u.aj */
   62260   int n;
   62261   int i;
   62262   int p1;
   62263   int p2;
   62264   const KeyInfo *pKeyInfo;
   62265   int idx;
   62266   CollSeq *pColl;    /* Collating sequence to use on this term */
   62267   int bRev;          /* True for DESCENDING sort order */
   62268 #endif /* local variables moved into u.aj */
   62269 
   62270   u.aj.n = pOp->p3;
   62271   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
   62272   assert( u.aj.n>0 );
   62273   assert( u.aj.pKeyInfo!=0 );
   62274   u.aj.p1 = pOp->p1;
   62275   u.aj.p2 = pOp->p2;
   62276 #if SQLITE_DEBUG
   62277   if( aPermute ){
   62278     int k, mx = 0;
   62279     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
   62280     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
   62281     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
   62282   }else{
   62283     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
   62284     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
   62285   }
   62286 #endif /* SQLITE_DEBUG */
   62287   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
   62288     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
   62289     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
   62290     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
   62291     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
   62292     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
   62293     assert( u.aj.i<u.aj.pKeyInfo->nField );
   62294     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
   62295     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
   62296     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
   62297     if( iCompare ){
   62298       if( u.aj.bRev ) iCompare = -iCompare;
   62299       break;
   62300     }
   62301   }
   62302   aPermute = 0;
   62303   break;
   62304 }
   62305 
   62306 /* Opcode: Jump P1 P2 P3 * *
   62307 **
   62308 ** Jump to the instruction at address P1, P2, or P3 depending on whether
   62309 ** in the most recent OP_Compare instruction the P1 vector was less than
   62310 ** equal to, or greater than the P2 vector, respectively.
   62311 */
   62312 case OP_Jump: {             /* jump */
   62313   if( iCompare<0 ){
   62314     pc = pOp->p1 - 1;
   62315   }else if( iCompare==0 ){
   62316     pc = pOp->p2 - 1;
   62317   }else{
   62318     pc = pOp->p3 - 1;
   62319   }
   62320   break;
   62321 }
   62322 
   62323 /* Opcode: And P1 P2 P3 * *
   62324 **
   62325 ** Take the logical AND of the values in registers P1 and P2 and
   62326 ** write the result into register P3.
   62327 **
   62328 ** If either P1 or P2 is 0 (false) then the result is 0 even if
   62329 ** the other input is NULL.  A NULL and true or two NULLs give
   62330 ** a NULL output.
   62331 */
   62332 /* Opcode: Or P1 P2 P3 * *
   62333 **
   62334 ** Take the logical OR of the values in register P1 and P2 and
   62335 ** store the answer in register P3.
   62336 **
   62337 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
   62338 ** even if the other input is NULL.  A NULL and false or two NULLs
   62339 ** give a NULL output.
   62340 */
   62341 case OP_And:              /* same as TK_AND, in1, in2, out3 */
   62342 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
   62343 #if 0  /* local variables moved into u.ak */
   62344   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   62345   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
   62346 #endif /* local variables moved into u.ak */
   62347 
   62348   pIn1 = &aMem[pOp->p1];
   62349   if( pIn1->flags & MEM_Null ){
   62350     u.ak.v1 = 2;
   62351   }else{
   62352     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
   62353   }
   62354   pIn2 = &aMem[pOp->p2];
   62355   if( pIn2->flags & MEM_Null ){
   62356     u.ak.v2 = 2;
   62357   }else{
   62358     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
   62359   }
   62360   if( pOp->opcode==OP_And ){
   62361     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
   62362     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
   62363   }else{
   62364     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
   62365     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
   62366   }
   62367   pOut = &aMem[pOp->p3];
   62368   if( u.ak.v1==2 ){
   62369     MemSetTypeFlag(pOut, MEM_Null);
   62370   }else{
   62371     pOut->u.i = u.ak.v1;
   62372     MemSetTypeFlag(pOut, MEM_Int);
   62373   }
   62374   break;
   62375 }
   62376 
   62377 /* Opcode: Not P1 P2 * * *
   62378 **
   62379 ** Interpret the value in register P1 as a boolean value.  Store the
   62380 ** boolean complement in register P2.  If the value in register P1 is
   62381 ** NULL, then a NULL is stored in P2.
   62382 */
   62383 case OP_Not: {                /* same as TK_NOT, in1, out2 */
   62384   pIn1 = &aMem[pOp->p1];
   62385   pOut = &aMem[pOp->p2];
   62386   if( pIn1->flags & MEM_Null ){
   62387     sqlite3VdbeMemSetNull(pOut);
   62388   }else{
   62389     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
   62390   }
   62391   break;
   62392 }
   62393 
   62394 /* Opcode: BitNot P1 P2 * * *
   62395 **
   62396 ** Interpret the content of register P1 as an integer.  Store the
   62397 ** ones-complement of the P1 value into register P2.  If P1 holds
   62398 ** a NULL then store a NULL in P2.
   62399 */
   62400 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
   62401   pIn1 = &aMem[pOp->p1];
   62402   pOut = &aMem[pOp->p2];
   62403   if( pIn1->flags & MEM_Null ){
   62404     sqlite3VdbeMemSetNull(pOut);
   62405   }else{
   62406     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
   62407   }
   62408   break;
   62409 }
   62410 
   62411 /* Opcode: If P1 P2 P3 * *
   62412 **
   62413 ** Jump to P2 if the value in register P1 is true.  The value is
   62414 ** is considered true if it is numeric and non-zero.  If the value
   62415 ** in P1 is NULL then take the jump if P3 is true.
   62416 */
   62417 /* Opcode: IfNot P1 P2 P3 * *
   62418 **
   62419 ** Jump to P2 if the value in register P1 is False.  The value is
   62420 ** is considered true if it has a numeric value of zero.  If the value
   62421 ** in P1 is NULL then take the jump if P3 is true.
   62422 */
   62423 case OP_If:                 /* jump, in1 */
   62424 case OP_IfNot: {            /* jump, in1 */
   62425 #if 0  /* local variables moved into u.al */
   62426   int c;
   62427 #endif /* local variables moved into u.al */
   62428   pIn1 = &aMem[pOp->p1];
   62429   if( pIn1->flags & MEM_Null ){
   62430     u.al.c = pOp->p3;
   62431   }else{
   62432 #ifdef SQLITE_OMIT_FLOATING_POINT
   62433     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
   62434 #else
   62435     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
   62436 #endif
   62437     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
   62438   }
   62439   if( u.al.c ){
   62440     pc = pOp->p2-1;
   62441   }
   62442   break;
   62443 }
   62444 
   62445 /* Opcode: IsNull P1 P2 * * *
   62446 **
   62447 ** Jump to P2 if the value in register P1 is NULL.
   62448 */
   62449 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
   62450   pIn1 = &aMem[pOp->p1];
   62451   if( (pIn1->flags & MEM_Null)!=0 ){
   62452     pc = pOp->p2 - 1;
   62453   }
   62454   break;
   62455 }
   62456 
   62457 /* Opcode: NotNull P1 P2 * * *
   62458 **
   62459 ** Jump to P2 if the value in register P1 is not NULL.
   62460 */
   62461 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   62462   pIn1 = &aMem[pOp->p1];
   62463   if( (pIn1->flags & MEM_Null)==0 ){
   62464     pc = pOp->p2 - 1;
   62465   }
   62466   break;
   62467 }
   62468 
   62469 /* Opcode: Column P1 P2 P3 P4 P5
   62470 **
   62471 ** Interpret the data that cursor P1 points to as a structure built using
   62472 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
   62473 ** information about the format of the data.)  Extract the P2-th column
   62474 ** from this record.  If there are less that (P2+1)
   62475 ** values in the record, extract a NULL.
   62476 **
   62477 ** The value extracted is stored in register P3.
   62478 **
   62479 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
   62480 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
   62481 ** the result.
   62482 **
   62483 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
   62484 ** then the cache of the cursor is reset prior to extracting the column.
   62485 ** The first OP_Column against a pseudo-table after the value of the content
   62486 ** register has changed should have this bit set.
   62487 */
   62488 case OP_Column: {
   62489 #if 0  /* local variables moved into u.am */
   62490   u32 payloadSize;   /* Number of bytes in the record */
   62491   i64 payloadSize64; /* Number of bytes in the record */
   62492   int p1;            /* P1 value of the opcode */
   62493   int p2;            /* column number to retrieve */
   62494   VdbeCursor *pC;    /* The VDBE cursor */
   62495   char *zRec;        /* Pointer to complete record-data */
   62496   BtCursor *pCrsr;   /* The BTree cursor */
   62497   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
   62498   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
   62499   int nField;        /* number of fields in the record */
   62500   int len;           /* The length of the serialized data for the column */
   62501   int i;             /* Loop counter */
   62502   char *zData;       /* Part of the record being decoded */
   62503   Mem *pDest;        /* Where to write the extracted value */
   62504   Mem sMem;          /* For storing the record being decoded */
   62505   u8 *zIdx;          /* Index into header */
   62506   u8 *zEndHdr;       /* Pointer to first byte after the header */
   62507   u32 offset;        /* Offset into the data */
   62508   u32 szField;       /* Number of bytes in the content of a field */
   62509   int szHdr;         /* Size of the header size field at start of record */
   62510   int avail;         /* Number of bytes of available data */
   62511   Mem *pReg;         /* PseudoTable input register */
   62512 #endif /* local variables moved into u.am */
   62513 
   62514 
   62515   u.am.p1 = pOp->p1;
   62516   u.am.p2 = pOp->p2;
   62517   u.am.pC = 0;
   62518   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
   62519   assert( u.am.p1<p->nCursor );
   62520   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   62521   u.am.pDest = &aMem[pOp->p3];
   62522   memAboutToChange(p, u.am.pDest);
   62523   MemSetTypeFlag(u.am.pDest, MEM_Null);
   62524   u.am.zRec = 0;
   62525 
   62526   /* This block sets the variable u.am.payloadSize to be the total number of
   62527   ** bytes in the record.
   62528   **
   62529   ** u.am.zRec is set to be the complete text of the record if it is available.
   62530   ** The complete record text is always available for pseudo-tables
   62531   ** If the record is stored in a cursor, the complete record text
   62532   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
   62533   ** If the data is unavailable,  u.am.zRec is set to NULL.
   62534   **
   62535   ** We also compute the number of columns in the record.  For cursors,
   62536   ** the number of columns is stored in the VdbeCursor.nField element.
   62537   */
   62538   u.am.pC = p->apCsr[u.am.p1];
   62539   assert( u.am.pC!=0 );
   62540 #ifndef SQLITE_OMIT_VIRTUALTABLE
   62541   assert( u.am.pC->pVtabCursor==0 );
   62542 #endif
   62543   u.am.pCrsr = u.am.pC->pCursor;
   62544   if( u.am.pCrsr!=0 ){
   62545     /* The record is stored in a B-Tree */
   62546     rc = sqlite3VdbeCursorMoveto(u.am.pC);
   62547     if( rc ) goto abort_due_to_error;
   62548     if( u.am.pC->nullRow ){
   62549       u.am.payloadSize = 0;
   62550     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
   62551       u.am.payloadSize = u.am.pC->payloadSize;
   62552       u.am.zRec = (char*)u.am.pC->aRow;
   62553     }else if( u.am.pC->isIndex ){
   62554       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
   62555       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
   62556       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
   62557       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
   62558       ** payload size, so it is impossible for u.am.payloadSize64 to be
   62559       ** larger than 32 bits. */
   62560       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
   62561       u.am.payloadSize = (u32)u.am.payloadSize64;
   62562     }else{
   62563       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
   62564       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
   62565       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
   62566     }
   62567   }else if( u.am.pC->pseudoTableReg>0 ){
   62568     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
   62569     assert( u.am.pReg->flags & MEM_Blob );
   62570     assert( memIsValid(u.am.pReg) );
   62571     u.am.payloadSize = u.am.pReg->n;
   62572     u.am.zRec = u.am.pReg->z;
   62573     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
   62574     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
   62575   }else{
   62576     /* Consider the row to be NULL */
   62577     u.am.payloadSize = 0;
   62578   }
   62579 
   62580   /* If u.am.payloadSize is 0, then just store a NULL */
   62581   if( u.am.payloadSize==0 ){
   62582     assert( u.am.pDest->flags&MEM_Null );
   62583     goto op_column_out;
   62584   }
   62585   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
   62586   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   62587     goto too_big;
   62588   }
   62589 
   62590   u.am.nField = u.am.pC->nField;
   62591   assert( u.am.p2<u.am.nField );
   62592 
   62593   /* Read and parse the table header.  Store the results of the parse
   62594   ** into the record header cache fields of the cursor.
   62595   */
   62596   u.am.aType = u.am.pC->aType;
   62597   if( u.am.pC->cacheStatus==p->cacheCtr ){
   62598     u.am.aOffset = u.am.pC->aOffset;
   62599   }else{
   62600     assert(u.am.aType);
   62601     u.am.avail = 0;
   62602     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
   62603     u.am.pC->payloadSize = u.am.payloadSize;
   62604     u.am.pC->cacheStatus = p->cacheCtr;
   62605 
   62606     /* Figure out how many bytes are in the header */
   62607     if( u.am.zRec ){
   62608       u.am.zData = u.am.zRec;
   62609     }else{
   62610       if( u.am.pC->isIndex ){
   62611         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
   62612       }else{
   62613         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
   62614       }
   62615       /* If KeyFetch()/DataFetch() managed to get the entire payload,
   62616       ** save the payload in the u.am.pC->aRow cache.  That will save us from
   62617       ** having to make additional calls to fetch the content portion of
   62618       ** the record.
   62619       */
   62620       assert( u.am.avail>=0 );
   62621       if( u.am.payloadSize <= (u32)u.am.avail ){
   62622         u.am.zRec = u.am.zData;
   62623         u.am.pC->aRow = (u8*)u.am.zData;
   62624       }else{
   62625         u.am.pC->aRow = 0;
   62626       }
   62627     }
   62628     /* The following assert is true in all cases accept when
   62629     ** the database file has been corrupted externally.
   62630     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
   62631     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
   62632 
   62633     /* Make sure a corrupt database has not given us an oversize header.
   62634     ** Do this now to avoid an oversize memory allocation.
   62635     **
   62636     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
   62637     ** types use so much data space that there can only be 4096 and 32 of
   62638     ** them, respectively.  So the maximum header length results from a
   62639     ** 3-byte type for each of the maximum of 32768 columns plus three
   62640     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
   62641     */
   62642     if( u.am.offset > 98307 ){
   62643       rc = SQLITE_CORRUPT_BKPT;
   62644       goto op_column_out;
   62645     }
   62646 
   62647     /* Compute in u.am.len the number of bytes of data we need to read in order
   62648     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
   62649     ** u.am.nField might be significantly less than the true number of columns
   62650     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
   62651     ** We want to minimize u.am.len in order to limit the size of the memory
   62652     ** allocation, especially if a corrupt database file has caused u.am.offset
   62653     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
   62654     ** still exceed Robson memory allocation limits on some configurations.
   62655     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
   62656     ** will likely be much smaller since u.am.nField will likely be less than
   62657     ** 20 or so.  This insures that Robson memory allocation limits are
   62658     ** not exceeded even for corrupt database files.
   62659     */
   62660     u.am.len = u.am.nField*5 + 3;
   62661     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
   62662 
   62663     /* The KeyFetch() or DataFetch() above are fast and will get the entire
   62664     ** record header in most cases.  But they will fail to get the complete
   62665     ** record header if the record header does not fit on a single page
   62666     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
   62667     ** acquire the complete header text.
   62668     */
   62669     if( !u.am.zRec && u.am.avail<u.am.len ){
   62670       u.am.sMem.flags = 0;
   62671       u.am.sMem.db = 0;
   62672       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
   62673       if( rc!=SQLITE_OK ){
   62674         goto op_column_out;
   62675       }
   62676       u.am.zData = u.am.sMem.z;
   62677     }
   62678     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
   62679     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
   62680 
   62681     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
   62682     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
   62683     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
   62684     ** of the record to the start of the data for the u.am.i-th column
   62685     */
   62686     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
   62687       if( u.am.zIdx<u.am.zEndHdr ){
   62688         u.am.aOffset[u.am.i] = u.am.offset;
   62689         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
   62690         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
   62691         u.am.offset += u.am.szField;
   62692         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
   62693           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
   62694           break;
   62695         }
   62696       }else{
   62697         /* If u.am.i is less that u.am.nField, then there are less fields in this
   62698         ** record than SetNumColumns indicated there are columns in the
   62699         ** table. Set the u.am.offset for any extra columns not present in
   62700         ** the record to 0. This tells code below to store a NULL
   62701         ** instead of deserializing a value from the record.
   62702         */
   62703         u.am.aOffset[u.am.i] = 0;
   62704       }
   62705     }
   62706     sqlite3VdbeMemRelease(&u.am.sMem);
   62707     u.am.sMem.flags = MEM_Null;
   62708 
   62709     /* If we have read more header data than was contained in the header,
   62710     ** or if the end of the last field appears to be past the end of the
   62711     ** record, or if the end of the last field appears to be before the end
   62712     ** of the record (when all fields present), then we must be dealing
   62713     ** with a corrupt database.
   62714     */
   62715     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
   62716          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
   62717       rc = SQLITE_CORRUPT_BKPT;
   62718       goto op_column_out;
   62719     }
   62720   }
   62721 
   62722   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
   62723   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
   62724   ** then there are not enough fields in the record to satisfy the
   62725   ** request.  In this case, set the value NULL or to P4 if P4 is
   62726   ** a pointer to a Mem object.
   62727   */
   62728   if( u.am.aOffset[u.am.p2] ){
   62729     assert( rc==SQLITE_OK );
   62730     if( u.am.zRec ){
   62731       sqlite3VdbeMemReleaseExternal(u.am.pDest);
   62732       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
   62733     }else{
   62734       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
   62735       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
   62736       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
   62737       if( rc!=SQLITE_OK ){
   62738         goto op_column_out;
   62739       }
   62740       u.am.zData = u.am.sMem.z;
   62741       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
   62742     }
   62743     u.am.pDest->enc = encoding;
   62744   }else{
   62745     if( pOp->p4type==P4_MEM ){
   62746       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
   62747     }else{
   62748       assert( u.am.pDest->flags&MEM_Null );
   62749     }
   62750   }
   62751 
   62752   /* If we dynamically allocated space to hold the data (in the
   62753   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
   62754   ** dynamically allocated space over to the u.am.pDest structure.
   62755   ** This prevents a memory copy.
   62756   */
   62757   if( u.am.sMem.zMalloc ){
   62758     assert( u.am.sMem.z==u.am.sMem.zMalloc );
   62759     assert( !(u.am.pDest->flags & MEM_Dyn) );
   62760     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
   62761     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
   62762     u.am.pDest->flags |= MEM_Term;
   62763     u.am.pDest->z = u.am.sMem.z;
   62764     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
   62765   }
   62766 
   62767   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
   62768 
   62769 op_column_out:
   62770   UPDATE_MAX_BLOBSIZE(u.am.pDest);
   62771   REGISTER_TRACE(pOp->p3, u.am.pDest);
   62772   break;
   62773 }
   62774 
   62775 /* Opcode: Affinity P1 P2 * P4 *
   62776 **
   62777 ** Apply affinities to a range of P2 registers starting with P1.
   62778 **
   62779 ** P4 is a string that is P2 characters long. The nth character of the
   62780 ** string indicates the column affinity that should be used for the nth
   62781 ** memory cell in the range.
   62782 */
   62783 case OP_Affinity: {
   62784 #if 0  /* local variables moved into u.an */
   62785   const char *zAffinity;   /* The affinity to be applied */
   62786   char cAff;               /* A single character of affinity */
   62787 #endif /* local variables moved into u.an */
   62788 
   62789   u.an.zAffinity = pOp->p4.z;
   62790   assert( u.an.zAffinity!=0 );
   62791   assert( u.an.zAffinity[pOp->p2]==0 );
   62792   pIn1 = &aMem[pOp->p1];
   62793   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
   62794     assert( pIn1 <= &p->aMem[p->nMem] );
   62795     assert( memIsValid(pIn1) );
   62796     ExpandBlob(pIn1);
   62797     applyAffinity(pIn1, u.an.cAff, encoding);
   62798     pIn1++;
   62799   }
   62800   break;
   62801 }
   62802 
   62803 /* Opcode: MakeRecord P1 P2 P3 P4 *
   62804 **
   62805 ** Convert P2 registers beginning with P1 into the [record format]
   62806 ** use as a data record in a database table or as a key
   62807 ** in an index.  The OP_Column opcode can decode the record later.
   62808 **
   62809 ** P4 may be a string that is P2 characters long.  The nth character of the
   62810 ** string indicates the column affinity that should be used for the nth
   62811 ** field of the index key.
   62812 **
   62813 ** The mapping from character to affinity is given by the SQLITE_AFF_
   62814 ** macros defined in sqliteInt.h.
   62815 **
   62816 ** If P4 is NULL then all index fields have the affinity NONE.
   62817 */
   62818 case OP_MakeRecord: {
   62819 #if 0  /* local variables moved into u.ao */
   62820   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
   62821   Mem *pRec;             /* The new record */
   62822   u64 nData;             /* Number of bytes of data space */
   62823   int nHdr;              /* Number of bytes of header space */
   62824   i64 nByte;             /* Data space required for this record */
   62825   int nZero;             /* Number of zero bytes at the end of the record */
   62826   int nVarint;           /* Number of bytes in a varint */
   62827   u32 serial_type;       /* Type field */
   62828   Mem *pData0;           /* First field to be combined into the record */
   62829   Mem *pLast;            /* Last field of the record */
   62830   int nField;            /* Number of fields in the record */
   62831   char *zAffinity;       /* The affinity string for the record */
   62832   int file_format;       /* File format to use for encoding */
   62833   int i;                 /* Space used in zNewRecord[] */
   62834   int len;               /* Length of a field */
   62835 #endif /* local variables moved into u.ao */
   62836 
   62837   /* Assuming the record contains N fields, the record format looks
   62838   ** like this:
   62839   **
   62840   ** ------------------------------------------------------------------------
   62841   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   62842   ** ------------------------------------------------------------------------
   62843   **
   62844   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   62845   ** and so froth.
   62846   **
   62847   ** Each type field is a varint representing the serial type of the
   62848   ** corresponding data element (see sqlite3VdbeSerialType()). The
   62849   ** hdr-size field is also a varint which is the offset from the beginning
   62850   ** of the record to data0.
   62851   */
   62852   u.ao.nData = 0;         /* Number of bytes of data space */
   62853   u.ao.nHdr = 0;          /* Number of bytes of header space */
   62854   u.ao.nByte = 0;         /* Data space required for this record */
   62855   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
   62856   u.ao.nField = pOp->p1;
   62857   u.ao.zAffinity = pOp->p4.z;
   62858   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
   62859   u.ao.pData0 = &aMem[u.ao.nField];
   62860   u.ao.nField = pOp->p2;
   62861   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
   62862   u.ao.file_format = p->minWriteFileFormat;
   62863 
   62864   /* Identify the output register */
   62865   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
   62866   pOut = &aMem[pOp->p3];
   62867   memAboutToChange(p, pOut);
   62868 
   62869   /* Loop through the elements that will make up the record to figure
   62870   ** out how much space is required for the new record.
   62871   */
   62872   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
   62873     assert( memIsValid(u.ao.pRec) );
   62874     if( u.ao.zAffinity ){
   62875       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
   62876     }
   62877     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
   62878       sqlite3VdbeMemExpandBlob(u.ao.pRec);
   62879     }
   62880     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
   62881     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
   62882     u.ao.nData += u.ao.len;
   62883     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
   62884     if( u.ao.pRec->flags & MEM_Zero ){
   62885       /* Only pure zero-filled BLOBs can be input to this Opcode.
   62886       ** We do not allow blobs with a prefix and a zero-filled tail. */
   62887       u.ao.nZero += u.ao.pRec->u.nZero;
   62888     }else if( u.ao.len ){
   62889       u.ao.nZero = 0;
   62890     }
   62891   }
   62892 
   62893   /* Add the initial header varint and total the size */
   62894   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
   62895   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
   62896     u.ao.nHdr++;
   62897   }
   62898   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
   62899   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   62900     goto too_big;
   62901   }
   62902 
   62903   /* Make sure the output register has a buffer large enough to store
   62904   ** the new record. The output register (pOp->p3) is not allowed to
   62905   ** be one of the input registers (because the following call to
   62906   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
   62907   */
   62908   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
   62909     goto no_mem;
   62910   }
   62911   u.ao.zNewRecord = (u8 *)pOut->z;
   62912 
   62913   /* Write the record */
   62914   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
   62915   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
   62916     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
   62917     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
   62918   }
   62919   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
   62920     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
   62921   }
   62922   assert( u.ao.i==u.ao.nByte );
   62923 
   62924   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   62925   pOut->n = (int)u.ao.nByte;
   62926   pOut->flags = MEM_Blob | MEM_Dyn;
   62927   pOut->xDel = 0;
   62928   if( u.ao.nZero ){
   62929     pOut->u.nZero = u.ao.nZero;
   62930     pOut->flags |= MEM_Zero;
   62931   }
   62932   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
   62933   REGISTER_TRACE(pOp->p3, pOut);
   62934   UPDATE_MAX_BLOBSIZE(pOut);
   62935   break;
   62936 }
   62937 
   62938 /* Opcode: Count P1 P2 * * *
   62939 **
   62940 ** Store the number of entries (an integer value) in the table or index
   62941 ** opened by cursor P1 in register P2
   62942 */
   62943 #ifndef SQLITE_OMIT_BTREECOUNT
   62944 case OP_Count: {         /* out2-prerelease */
   62945 #if 0  /* local variables moved into u.ap */
   62946   i64 nEntry;
   62947   BtCursor *pCrsr;
   62948 #endif /* local variables moved into u.ap */
   62949 
   62950   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
   62951   if( u.ap.pCrsr ){
   62952     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
   62953   }else{
   62954     u.ap.nEntry = 0;
   62955   }
   62956   pOut->u.i = u.ap.nEntry;
   62957   break;
   62958 }
   62959 #endif
   62960 
   62961 /* Opcode: Savepoint P1 * * P4 *
   62962 **
   62963 ** Open, release or rollback the savepoint named by parameter P4, depending
   62964 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
   62965 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
   62966 */
   62967 case OP_Savepoint: {
   62968 #if 0  /* local variables moved into u.aq */
   62969   int p1;                         /* Value of P1 operand */
   62970   char *zName;                    /* Name of savepoint */
   62971   int nName;
   62972   Savepoint *pNew;
   62973   Savepoint *pSavepoint;
   62974   Savepoint *pTmp;
   62975   int iSavepoint;
   62976   int ii;
   62977 #endif /* local variables moved into u.aq */
   62978 
   62979   u.aq.p1 = pOp->p1;
   62980   u.aq.zName = pOp->p4.z;
   62981 
   62982   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
   62983   ** transaction, then there cannot be any savepoints.
   62984   */
   62985   assert( db->pSavepoint==0 || db->autoCommit==0 );
   62986   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
   62987   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
   62988   assert( checkSavepointCount(db) );
   62989 
   62990   if( u.aq.p1==SAVEPOINT_BEGIN ){
   62991     if( db->writeVdbeCnt>0 ){
   62992       /* A new savepoint cannot be created if there are active write
   62993       ** statements (i.e. open read/write incremental blob handles).
   62994       */
   62995       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
   62996         "SQL statements in progress");
   62997       rc = SQLITE_BUSY;
   62998     }else{
   62999       u.aq.nName = sqlite3Strlen30(u.aq.zName);
   63000 
   63001       /* Create a new savepoint structure. */
   63002       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
   63003       if( u.aq.pNew ){
   63004         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
   63005         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
   63006 
   63007         /* If there is no open transaction, then mark this as a special
   63008         ** "transaction savepoint". */
   63009         if( db->autoCommit ){
   63010           db->autoCommit = 0;
   63011           db->isTransactionSavepoint = 1;
   63012         }else{
   63013           db->nSavepoint++;
   63014         }
   63015 
   63016         /* Link the new savepoint into the database handle's list. */
   63017         u.aq.pNew->pNext = db->pSavepoint;
   63018         db->pSavepoint = u.aq.pNew;
   63019         u.aq.pNew->nDeferredCons = db->nDeferredCons;
   63020       }
   63021     }
   63022   }else{
   63023     u.aq.iSavepoint = 0;
   63024 
   63025     /* Find the named savepoint. If there is no such savepoint, then an
   63026     ** an error is returned to the user.  */
   63027     for(
   63028       u.aq.pSavepoint = db->pSavepoint;
   63029       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
   63030       u.aq.pSavepoint = u.aq.pSavepoint->pNext
   63031     ){
   63032       u.aq.iSavepoint++;
   63033     }
   63034     if( !u.aq.pSavepoint ){
   63035       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
   63036       rc = SQLITE_ERROR;
   63037     }else if(
   63038         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
   63039     ){
   63040       /* It is not possible to release (commit) a savepoint if there are
   63041       ** active write statements. It is not possible to rollback a savepoint
   63042       ** if there are any active statements at all.
   63043       */
   63044       sqlite3SetString(&p->zErrMsg, db,
   63045         "cannot %s savepoint - SQL statements in progress",
   63046         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
   63047       );
   63048       rc = SQLITE_BUSY;
   63049     }else{
   63050 
   63051       /* Determine whether or not this is a transaction savepoint. If so,
   63052       ** and this is a RELEASE command, then the current transaction
   63053       ** is committed.
   63054       */
   63055       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
   63056       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
   63057         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   63058           goto vdbe_return;
   63059         }
   63060         db->autoCommit = 1;
   63061         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   63062           p->pc = pc;
   63063           db->autoCommit = 0;
   63064           p->rc = rc = SQLITE_BUSY;
   63065           goto vdbe_return;
   63066         }
   63067         db->isTransactionSavepoint = 0;
   63068         rc = p->rc;
   63069       }else{
   63070         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
   63071         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
   63072           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
   63073           if( rc!=SQLITE_OK ){
   63074             goto abort_due_to_error;
   63075           }
   63076         }
   63077         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
   63078           sqlite3ExpirePreparedStatements(db);
   63079           sqlite3ResetInternalSchema(db, 0);
   63080           db->flags = (db->flags | SQLITE_InternChanges);
   63081         }
   63082       }
   63083 
   63084       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
   63085       ** savepoints nested inside of the savepoint being operated on. */
   63086       while( db->pSavepoint!=u.aq.pSavepoint ){
   63087         u.aq.pTmp = db->pSavepoint;
   63088         db->pSavepoint = u.aq.pTmp->pNext;
   63089         sqlite3DbFree(db, u.aq.pTmp);
   63090         db->nSavepoint--;
   63091       }
   63092 
   63093       /* If it is a RELEASE, then destroy the savepoint being operated on
   63094       ** too. If it is a ROLLBACK TO, then set the number of deferred
   63095       ** constraint violations present in the database to the value stored
   63096       ** when the savepoint was created.  */
   63097       if( u.aq.p1==SAVEPOINT_RELEASE ){
   63098         assert( u.aq.pSavepoint==db->pSavepoint );
   63099         db->pSavepoint = u.aq.pSavepoint->pNext;
   63100         sqlite3DbFree(db, u.aq.pSavepoint);
   63101         if( !isTransaction ){
   63102           db->nSavepoint--;
   63103         }
   63104       }else{
   63105         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
   63106       }
   63107     }
   63108   }
   63109 
   63110   break;
   63111 }
   63112 
   63113 /* Opcode: AutoCommit P1 P2 * * *
   63114 **
   63115 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
   63116 ** back any currently active btree transactions. If there are any active
   63117 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
   63118 ** there are active writing VMs or active VMs that use shared cache.
   63119 **
   63120 ** This instruction causes the VM to halt.
   63121 */
   63122 case OP_AutoCommit: {
   63123 #if 0  /* local variables moved into u.ar */
   63124   int desiredAutoCommit;
   63125   int iRollback;
   63126   int turnOnAC;
   63127 #endif /* local variables moved into u.ar */
   63128 
   63129   u.ar.desiredAutoCommit = pOp->p1;
   63130   u.ar.iRollback = pOp->p2;
   63131   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
   63132   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
   63133   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
   63134   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
   63135 
   63136   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
   63137     /* If this instruction implements a ROLLBACK and other VMs are
   63138     ** still running, and a transaction is active, return an error indicating
   63139     ** that the other VMs must complete first.
   63140     */
   63141     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
   63142         "SQL statements in progress");
   63143     rc = SQLITE_BUSY;
   63144   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
   63145     /* If this instruction implements a COMMIT and other VMs are writing
   63146     ** return an error indicating that the other VMs must complete first.
   63147     */
   63148     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
   63149         "SQL statements in progress");
   63150     rc = SQLITE_BUSY;
   63151   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
   63152     if( u.ar.iRollback ){
   63153       assert( u.ar.desiredAutoCommit==1 );
   63154       sqlite3RollbackAll(db);
   63155       db->autoCommit = 1;
   63156     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
   63157       goto vdbe_return;
   63158     }else{
   63159       db->autoCommit = (u8)u.ar.desiredAutoCommit;
   63160       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
   63161         p->pc = pc;
   63162         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
   63163         p->rc = rc = SQLITE_BUSY;
   63164         goto vdbe_return;
   63165       }
   63166     }
   63167     assert( db->nStatement==0 );
   63168     sqlite3CloseSavepoints(db);
   63169     if( p->rc==SQLITE_OK ){
   63170       rc = SQLITE_DONE;
   63171     }else{
   63172       rc = SQLITE_ERROR;
   63173     }
   63174     goto vdbe_return;
   63175   }else{
   63176     sqlite3SetString(&p->zErrMsg, db,
   63177         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
   63178         (u.ar.iRollback)?"cannot rollback - no transaction is active":
   63179                    "cannot commit - no transaction is active"));
   63180 
   63181     rc = SQLITE_ERROR;
   63182   }
   63183   break;
   63184 }
   63185 
   63186 /* Opcode: Transaction P1 P2 * * *
   63187 **
   63188 ** Begin a transaction.  The transaction ends when a Commit or Rollback
   63189 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
   63190 ** transaction might also be rolled back if an error is encountered.
   63191 **
   63192 ** P1 is the index of the database file on which the transaction is
   63193 ** started.  Index 0 is the main database file and index 1 is the
   63194 ** file used for temporary tables.  Indices of 2 or more are used for
   63195 ** attached databases.
   63196 **
   63197 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
   63198 ** obtained on the database file when a write-transaction is started.  No
   63199 ** other process can start another write transaction while this transaction is
   63200 ** underway.  Starting a write transaction also creates a rollback journal. A
   63201 ** write transaction must be started before any changes can be made to the
   63202 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
   63203 ** on the file.
   63204 **
   63205 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
   63206 ** true (this flag is set if the Vdbe may modify more than one row and may
   63207 ** throw an ABORT exception), a statement transaction may also be opened.
   63208 ** More specifically, a statement transaction is opened iff the database
   63209 ** connection is currently not in autocommit mode, or if there are other
   63210 ** active statements. A statement transaction allows the affects of this
   63211 ** VDBE to be rolled back after an error without having to roll back the
   63212 ** entire transaction. If no error is encountered, the statement transaction
   63213 ** will automatically commit when the VDBE halts.
   63214 **
   63215 ** If P2 is zero, then a read-lock is obtained on the database file.
   63216 */
   63217 case OP_Transaction: {
   63218 #if 0  /* local variables moved into u.as */
   63219   Btree *pBt;
   63220 #endif /* local variables moved into u.as */
   63221 
   63222   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   63223   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   63224   u.as.pBt = db->aDb[pOp->p1].pBt;
   63225 
   63226   if( u.as.pBt ){
   63227     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
   63228     if( rc==SQLITE_BUSY ){
   63229       p->pc = pc;
   63230       p->rc = rc = SQLITE_BUSY;
   63231       goto vdbe_return;
   63232     }
   63233     if( rc!=SQLITE_OK ){
   63234       goto abort_due_to_error;
   63235     }
   63236 
   63237     if( pOp->p2 && p->usesStmtJournal
   63238      && (db->autoCommit==0 || db->activeVdbeCnt>1)
   63239     ){
   63240       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
   63241       if( p->iStatement==0 ){
   63242         assert( db->nStatement>=0 && db->nSavepoint>=0 );
   63243         db->nStatement++;
   63244         p->iStatement = db->nSavepoint + db->nStatement;
   63245       }
   63246       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
   63247 
   63248       /* Store the current value of the database handles deferred constraint
   63249       ** counter. If the statement transaction needs to be rolled back,
   63250       ** the value of this counter needs to be restored too.  */
   63251       p->nStmtDefCons = db->nDeferredCons;
   63252     }
   63253   }
   63254   break;
   63255 }
   63256 
   63257 /* Opcode: ReadCookie P1 P2 P3 * *
   63258 **
   63259 ** Read cookie number P3 from database P1 and write it into register P2.
   63260 ** P3==1 is the schema version.  P3==2 is the database format.
   63261 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
   63262 ** the main database file and P1==1 is the database file used to store
   63263 ** temporary tables.
   63264 **
   63265 ** There must be a read-lock on the database (either a transaction
   63266 ** must be started or there must be an open cursor) before
   63267 ** executing this instruction.
   63268 */
   63269 case OP_ReadCookie: {               /* out2-prerelease */
   63270 #if 0  /* local variables moved into u.at */
   63271   int iMeta;
   63272   int iDb;
   63273   int iCookie;
   63274 #endif /* local variables moved into u.at */
   63275 
   63276   u.at.iDb = pOp->p1;
   63277   u.at.iCookie = pOp->p3;
   63278   assert( pOp->p3<SQLITE_N_BTREE_META );
   63279   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
   63280   assert( db->aDb[u.at.iDb].pBt!=0 );
   63281   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
   63282 
   63283   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
   63284   pOut->u.i = u.at.iMeta;
   63285   break;
   63286 }
   63287 
   63288 /* Opcode: SetCookie P1 P2 P3 * *
   63289 **
   63290 ** Write the content of register P3 (interpreted as an integer)
   63291 ** into cookie number P2 of database P1.  P2==1 is the schema version.
   63292 ** P2==2 is the database format. P2==3 is the recommended pager cache
   63293 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
   63294 ** database file used to store temporary tables.
   63295 **
   63296 ** A transaction must be started before executing this opcode.
   63297 */
   63298 case OP_SetCookie: {       /* in3 */
   63299 #if 0  /* local variables moved into u.au */
   63300   Db *pDb;
   63301 #endif /* local variables moved into u.au */
   63302   assert( pOp->p2<SQLITE_N_BTREE_META );
   63303   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   63304   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   63305   u.au.pDb = &db->aDb[pOp->p1];
   63306   assert( u.au.pDb->pBt!=0 );
   63307   pIn3 = &aMem[pOp->p3];
   63308   sqlite3VdbeMemIntegerify(pIn3);
   63309   /* See note about index shifting on OP_ReadCookie */
   63310   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
   63311   if( pOp->p2==BTREE_SCHEMA_VERSION ){
   63312     /* When the schema cookie changes, record the new cookie internally */
   63313     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
   63314     db->flags |= SQLITE_InternChanges;
   63315   }else if( pOp->p2==BTREE_FILE_FORMAT ){
   63316     /* Record changes in the file format */
   63317     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
   63318   }
   63319   if( pOp->p1==1 ){
   63320     /* Invalidate all prepared statements whenever the TEMP database
   63321     ** schema is changed.  Ticket #1644 */
   63322     sqlite3ExpirePreparedStatements(db);
   63323     p->expired = 0;
   63324   }
   63325   break;
   63326 }
   63327 
   63328 /* Opcode: VerifyCookie P1 P2 *
   63329 **
   63330 ** Check the value of global database parameter number 0 (the
   63331 ** schema version) and make sure it is equal to P2.
   63332 ** P1 is the database number which is 0 for the main database file
   63333 ** and 1 for the file holding temporary tables and some higher number
   63334 ** for auxiliary databases.
   63335 **
   63336 ** The cookie changes its value whenever the database schema changes.
   63337 ** This operation is used to detect when that the cookie has changed
   63338 ** and that the current process needs to reread the schema.
   63339 **
   63340 ** Either a transaction needs to have been started or an OP_Open needs
   63341 ** to be executed (to establish a read lock) before this opcode is
   63342 ** invoked.
   63343 */
   63344 case OP_VerifyCookie: {
   63345 #if 0  /* local variables moved into u.av */
   63346   int iMeta;
   63347   Btree *pBt;
   63348 #endif /* local variables moved into u.av */
   63349   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   63350   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   63351   u.av.pBt = db->aDb[pOp->p1].pBt;
   63352   if( u.av.pBt ){
   63353     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
   63354   }else{
   63355     u.av.iMeta = 0;
   63356   }
   63357   if( u.av.iMeta!=pOp->p2 ){
   63358     sqlite3DbFree(db, p->zErrMsg);
   63359     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
   63360     /* If the schema-cookie from the database file matches the cookie
   63361     ** stored with the in-memory representation of the schema, do
   63362     ** not reload the schema from the database file.
   63363     **
   63364     ** If virtual-tables are in use, this is not just an optimization.
   63365     ** Often, v-tables store their data in other SQLite tables, which
   63366     ** are queried from within xNext() and other v-table methods using
   63367     ** prepared queries. If such a query is out-of-date, we do not want to
   63368     ** discard the database schema, as the user code implementing the
   63369     ** v-table would have to be ready for the sqlite3_vtab structure itself
   63370     ** to be invalidated whenever sqlite3_step() is called from within
   63371     ** a v-table method.
   63372     */
   63373     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
   63374       sqlite3ResetInternalSchema(db, pOp->p1);
   63375     }
   63376 
   63377     sqlite3ExpirePreparedStatements(db);
   63378     rc = SQLITE_SCHEMA;
   63379   }
   63380   break;
   63381 }
   63382 
   63383 /* Opcode: OpenRead P1 P2 P3 P4 P5
   63384 **
   63385 ** Open a read-only cursor for the database table whose root page is
   63386 ** P2 in a database file.  The database file is determined by P3.
   63387 ** P3==0 means the main database, P3==1 means the database used for
   63388 ** temporary tables, and P3>1 means used the corresponding attached
   63389 ** database.  Give the new cursor an identifier of P1.  The P1
   63390 ** values need not be contiguous but all P1 values should be small integers.
   63391 ** It is an error for P1 to be negative.
   63392 **
   63393 ** If P5!=0 then use the content of register P2 as the root page, not
   63394 ** the value of P2 itself.
   63395 **
   63396 ** There will be a read lock on the database whenever there is an
   63397 ** open cursor.  If the database was unlocked prior to this instruction
   63398 ** then a read lock is acquired as part of this instruction.  A read
   63399 ** lock allows other processes to read the database but prohibits
   63400 ** any other process from modifying the database.  The read lock is
   63401 ** released when all cursors are closed.  If this instruction attempts
   63402 ** to get a read lock but fails, the script terminates with an
   63403 ** SQLITE_BUSY error code.
   63404 **
   63405 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   63406 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   63407 ** structure, then said structure defines the content and collating
   63408 ** sequence of the index being opened. Otherwise, if P4 is an integer
   63409 ** value, it is set to the number of columns in the table.
   63410 **
   63411 ** See also OpenWrite.
   63412 */
   63413 /* Opcode: OpenWrite P1 P2 P3 P4 P5
   63414 **
   63415 ** Open a read/write cursor named P1 on the table or index whose root
   63416 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
   63417 ** root page.
   63418 **
   63419 ** The P4 value may be either an integer (P4_INT32) or a pointer to
   63420 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
   63421 ** structure, then said structure defines the content and collating
   63422 ** sequence of the index being opened. Otherwise, if P4 is an integer
   63423 ** value, it is set to the number of columns in the table, or to the
   63424 ** largest index of any column of the table that is actually used.
   63425 **
   63426 ** This instruction works just like OpenRead except that it opens the cursor
   63427 ** in read/write mode.  For a given table, there can be one or more read-only
   63428 ** cursors or a single read/write cursor but not both.
   63429 **
   63430 ** See also OpenRead.
   63431 */
   63432 case OP_OpenRead:
   63433 case OP_OpenWrite: {
   63434 #if 0  /* local variables moved into u.aw */
   63435   int nField;
   63436   KeyInfo *pKeyInfo;
   63437   int p2;
   63438   int iDb;
   63439   int wrFlag;
   63440   Btree *pX;
   63441   VdbeCursor *pCur;
   63442   Db *pDb;
   63443 #endif /* local variables moved into u.aw */
   63444 
   63445   if( p->expired ){
   63446     rc = SQLITE_ABORT;
   63447     break;
   63448   }
   63449 
   63450   u.aw.nField = 0;
   63451   u.aw.pKeyInfo = 0;
   63452   u.aw.p2 = pOp->p2;
   63453   u.aw.iDb = pOp->p3;
   63454   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
   63455   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
   63456   u.aw.pDb = &db->aDb[u.aw.iDb];
   63457   u.aw.pX = u.aw.pDb->pBt;
   63458   assert( u.aw.pX!=0 );
   63459   if( pOp->opcode==OP_OpenWrite ){
   63460     u.aw.wrFlag = 1;
   63461     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
   63462       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
   63463     }
   63464   }else{
   63465     u.aw.wrFlag = 0;
   63466   }
   63467   if( pOp->p5 ){
   63468     assert( u.aw.p2>0 );
   63469     assert( u.aw.p2<=p->nMem );
   63470     pIn2 = &aMem[u.aw.p2];
   63471     assert( memIsValid(pIn2) );
   63472     assert( (pIn2->flags & MEM_Int)!=0 );
   63473     sqlite3VdbeMemIntegerify(pIn2);
   63474     u.aw.p2 = (int)pIn2->u.i;
   63475     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
   63476     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
   63477     ** If there were a failure, the prepared statement would have halted
   63478     ** before reaching this instruction. */
   63479     if( NEVER(u.aw.p2<2) ) {
   63480       rc = SQLITE_CORRUPT_BKPT;
   63481       goto abort_due_to_error;
   63482     }
   63483   }
   63484   if( pOp->p4type==P4_KEYINFO ){
   63485     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
   63486     u.aw.pKeyInfo->enc = ENC(p->db);
   63487     u.aw.nField = u.aw.pKeyInfo->nField+1;
   63488   }else if( pOp->p4type==P4_INT32 ){
   63489     u.aw.nField = pOp->p4.i;
   63490   }
   63491   assert( pOp->p1>=0 );
   63492   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
   63493   if( u.aw.pCur==0 ) goto no_mem;
   63494   u.aw.pCur->nullRow = 1;
   63495   u.aw.pCur->isOrdered = 1;
   63496   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
   63497   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
   63498 
   63499   /* Since it performs no memory allocation or IO, the only values that
   63500   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
   63501   ** SQLITE_EMPTY is only returned when attempting to open the table
   63502   ** rooted at page 1 of a zero-byte database.  */
   63503   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
   63504   if( rc==SQLITE_EMPTY ){
   63505     u.aw.pCur->pCursor = 0;
   63506     rc = SQLITE_OK;
   63507   }
   63508 
   63509   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
   63510   ** SQLite used to check if the root-page flags were sane at this point
   63511   ** and report database corruption if they were not, but this check has
   63512   ** since moved into the btree layer.  */
   63513   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
   63514   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
   63515   break;
   63516 }
   63517 
   63518 /* Opcode: OpenEphemeral P1 P2 * P4 *
   63519 **
   63520 ** Open a new cursor P1 to a transient table.
   63521 ** The cursor is always opened read/write even if
   63522 ** the main database is read-only.  The ephemeral
   63523 ** table is deleted automatically when the cursor is closed.
   63524 **
   63525 ** P2 is the number of columns in the ephemeral table.
   63526 ** The cursor points to a BTree table if P4==0 and to a BTree index
   63527 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
   63528 ** that defines the format of keys in the index.
   63529 **
   63530 ** This opcode was once called OpenTemp.  But that created
   63531 ** confusion because the term "temp table", might refer either
   63532 ** to a TEMP table at the SQL level, or to a table opened by
   63533 ** this opcode.  Then this opcode was call OpenVirtual.  But
   63534 ** that created confusion with the whole virtual-table idea.
   63535 */
   63536 /* Opcode: OpenAutoindex P1 P2 * P4 *
   63537 **
   63538 ** This opcode works the same as OP_OpenEphemeral.  It has a
   63539 ** different name to distinguish its use.  Tables created using
   63540 ** by this opcode will be used for automatically created transient
   63541 ** indices in joins.
   63542 */
   63543 case OP_OpenAutoindex:
   63544 case OP_OpenEphemeral: {
   63545 #if 0  /* local variables moved into u.ax */
   63546   VdbeCursor *pCx;
   63547 #endif /* local variables moved into u.ax */
   63548   static const int vfsFlags =
   63549       SQLITE_OPEN_READWRITE |
   63550       SQLITE_OPEN_CREATE |
   63551       SQLITE_OPEN_EXCLUSIVE |
   63552       SQLITE_OPEN_DELETEONCLOSE |
   63553       SQLITE_OPEN_TRANSIENT_DB;
   63554 
   63555   assert( pOp->p1>=0 );
   63556   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
   63557   if( u.ax.pCx==0 ) goto no_mem;
   63558   u.ax.pCx->nullRow = 1;
   63559   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
   63560                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
   63561   if( rc==SQLITE_OK ){
   63562     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
   63563   }
   63564   if( rc==SQLITE_OK ){
   63565     /* If a transient index is required, create it by calling
   63566     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
   63567     ** opening it. If a transient table is required, just use the
   63568     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
   63569     */
   63570     if( pOp->p4.pKeyInfo ){
   63571       int pgno;
   63572       assert( pOp->p4type==P4_KEYINFO );
   63573       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
   63574       if( rc==SQLITE_OK ){
   63575         assert( pgno==MASTER_ROOT+1 );
   63576         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
   63577                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
   63578         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
   63579         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
   63580       }
   63581       u.ax.pCx->isTable = 0;
   63582     }else{
   63583       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
   63584       u.ax.pCx->isTable = 1;
   63585     }
   63586   }
   63587   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
   63588   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
   63589   break;
   63590 }
   63591 
   63592 /* Opcode: OpenPseudo P1 P2 P3 * *
   63593 **
   63594 ** Open a new cursor that points to a fake table that contains a single
   63595 ** row of data.  The content of that one row in the content of memory
   63596 ** register P2.  In other words, cursor P1 becomes an alias for the
   63597 ** MEM_Blob content contained in register P2.
   63598 **
   63599 ** A pseudo-table created by this opcode is used to hold a single
   63600 ** row output from the sorter so that the row can be decomposed into
   63601 ** individual columns using the OP_Column opcode.  The OP_Column opcode
   63602 ** is the only cursor opcode that works with a pseudo-table.
   63603 **
   63604 ** P3 is the number of fields in the records that will be stored by
   63605 ** the pseudo-table.
   63606 */
   63607 case OP_OpenPseudo: {
   63608 #if 0  /* local variables moved into u.ay */
   63609   VdbeCursor *pCx;
   63610 #endif /* local variables moved into u.ay */
   63611 
   63612   assert( pOp->p1>=0 );
   63613   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
   63614   if( u.ay.pCx==0 ) goto no_mem;
   63615   u.ay.pCx->nullRow = 1;
   63616   u.ay.pCx->pseudoTableReg = pOp->p2;
   63617   u.ay.pCx->isTable = 1;
   63618   u.ay.pCx->isIndex = 0;
   63619   break;
   63620 }
   63621 
   63622 /* Opcode: Close P1 * * * *
   63623 **
   63624 ** Close a cursor previously opened as P1.  If P1 is not
   63625 ** currently open, this instruction is a no-op.
   63626 */
   63627 case OP_Close: {
   63628   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   63629   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
   63630   p->apCsr[pOp->p1] = 0;
   63631   break;
   63632 }
   63633 
   63634 /* Opcode: SeekGe P1 P2 P3 P4 *
   63635 **
   63636 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   63637 ** use the value in register P3 as the key.  If cursor P1 refers
   63638 ** to an SQL index, then P3 is the first in an array of P4 registers
   63639 ** that are used as an unpacked index key.
   63640 **
   63641 ** Reposition cursor P1 so that  it points to the smallest entry that
   63642 ** is greater than or equal to the key value. If there are no records
   63643 ** greater than or equal to the key and P2 is not zero, then jump to P2.
   63644 **
   63645 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
   63646 */
   63647 /* Opcode: SeekGt P1 P2 P3 P4 *
   63648 **
   63649 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   63650 ** use the value in register P3 as a key. If cursor P1 refers
   63651 ** to an SQL index, then P3 is the first in an array of P4 registers
   63652 ** that are used as an unpacked index key.
   63653 **
   63654 ** Reposition cursor P1 so that  it points to the smallest entry that
   63655 ** is greater than the key value. If there are no records greater than
   63656 ** the key and P2 is not zero, then jump to P2.
   63657 **
   63658 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
   63659 */
   63660 /* Opcode: SeekLt P1 P2 P3 P4 *
   63661 **
   63662 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   63663 ** use the value in register P3 as a key. If cursor P1 refers
   63664 ** to an SQL index, then P3 is the first in an array of P4 registers
   63665 ** that are used as an unpacked index key.
   63666 **
   63667 ** Reposition cursor P1 so that  it points to the largest entry that
   63668 ** is less than the key value. If there are no records less than
   63669 ** the key and P2 is not zero, then jump to P2.
   63670 **
   63671 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
   63672 */
   63673 /* Opcode: SeekLe P1 P2 P3 P4 *
   63674 **
   63675 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
   63676 ** use the value in register P3 as a key. If cursor P1 refers
   63677 ** to an SQL index, then P3 is the first in an array of P4 registers
   63678 ** that are used as an unpacked index key.
   63679 **
   63680 ** Reposition cursor P1 so that it points to the largest entry that
   63681 ** is less than or equal to the key value. If there are no records
   63682 ** less than or equal to the key and P2 is not zero, then jump to P2.
   63683 **
   63684 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
   63685 */
   63686 case OP_SeekLt:         /* jump, in3 */
   63687 case OP_SeekLe:         /* jump, in3 */
   63688 case OP_SeekGe:         /* jump, in3 */
   63689 case OP_SeekGt: {       /* jump, in3 */
   63690 #if 0  /* local variables moved into u.az */
   63691   int res;
   63692   int oc;
   63693   VdbeCursor *pC;
   63694   UnpackedRecord r;
   63695   int nField;
   63696   i64 iKey;      /* The rowid we are to seek to */
   63697 #endif /* local variables moved into u.az */
   63698 
   63699   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   63700   assert( pOp->p2!=0 );
   63701   u.az.pC = p->apCsr[pOp->p1];
   63702   assert( u.az.pC!=0 );
   63703   assert( u.az.pC->pseudoTableReg==0 );
   63704   assert( OP_SeekLe == OP_SeekLt+1 );
   63705   assert( OP_SeekGe == OP_SeekLt+2 );
   63706   assert( OP_SeekGt == OP_SeekLt+3 );
   63707   assert( u.az.pC->isOrdered );
   63708   if( u.az.pC->pCursor!=0 ){
   63709     u.az.oc = pOp->opcode;
   63710     u.az.pC->nullRow = 0;
   63711     if( u.az.pC->isTable ){
   63712       /* The input value in P3 might be of any type: integer, real, string,
   63713       ** blob, or NULL.  But it needs to be an integer before we can do
   63714       ** the seek, so covert it. */
   63715       pIn3 = &aMem[pOp->p3];
   63716       applyNumericAffinity(pIn3);
   63717       u.az.iKey = sqlite3VdbeIntValue(pIn3);
   63718       u.az.pC->rowidIsValid = 0;
   63719 
   63720       /* If the P3 value could not be converted into an integer without
   63721       ** loss of information, then special processing is required... */
   63722       if( (pIn3->flags & MEM_Int)==0 ){
   63723         if( (pIn3->flags & MEM_Real)==0 ){
   63724           /* If the P3 value cannot be converted into any kind of a number,
   63725           ** then the seek is not possible, so jump to P2 */
   63726           pc = pOp->p2 - 1;
   63727           break;
   63728         }
   63729         /* If we reach this point, then the P3 value must be a floating
   63730         ** point number. */
   63731         assert( (pIn3->flags & MEM_Real)!=0 );
   63732 
   63733         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
   63734           /* The P3 value is too large in magnitude to be expressed as an
   63735           ** integer. */
   63736           u.az.res = 1;
   63737           if( pIn3->r<0 ){
   63738             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
   63739               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
   63740               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   63741             }
   63742           }else{
   63743             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
   63744               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
   63745               if( rc!=SQLITE_OK ) goto abort_due_to_error;
   63746             }
   63747           }
   63748           if( u.az.res ){
   63749             pc = pOp->p2 - 1;
   63750           }
   63751           break;
   63752         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
   63753           /* Use the ceiling() function to convert real->int */
   63754           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
   63755         }else{
   63756           /* Use the floor() function to convert real->int */
   63757           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
   63758           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
   63759         }
   63760       }
   63761       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
   63762       if( rc!=SQLITE_OK ){
   63763         goto abort_due_to_error;
   63764       }
   63765       if( u.az.res==0 ){
   63766         u.az.pC->rowidIsValid = 1;
   63767         u.az.pC->lastRowid = u.az.iKey;
   63768       }
   63769     }else{
   63770       u.az.nField = pOp->p4.i;
   63771       assert( pOp->p4type==P4_INT32 );
   63772       assert( u.az.nField>0 );
   63773       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
   63774       u.az.r.nField = (u16)u.az.nField;
   63775 
   63776       /* The next line of code computes as follows, only faster:
   63777       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
   63778       **     u.az.r.flags = UNPACKED_INCRKEY;
   63779       **   }else{
   63780       **     u.az.r.flags = 0;
   63781       **   }
   63782       */
   63783       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
   63784       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
   63785       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
   63786       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
   63787       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
   63788 
   63789       u.az.r.aMem = &aMem[pOp->p3];
   63790 #ifdef SQLITE_DEBUG
   63791       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
   63792 #endif
   63793       ExpandBlob(u.az.r.aMem);
   63794       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
   63795       if( rc!=SQLITE_OK ){
   63796         goto abort_due_to_error;
   63797       }
   63798       u.az.pC->rowidIsValid = 0;
   63799     }
   63800     u.az.pC->deferredMoveto = 0;
   63801     u.az.pC->cacheStatus = CACHE_STALE;
   63802 #ifdef SQLITE_TEST
   63803     sqlite3_search_count++;
   63804 #endif
   63805     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
   63806       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
   63807         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
   63808         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   63809         u.az.pC->rowidIsValid = 0;
   63810       }else{
   63811         u.az.res = 0;
   63812       }
   63813     }else{
   63814       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
   63815       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
   63816         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
   63817         if( rc!=SQLITE_OK ) goto abort_due_to_error;
   63818         u.az.pC->rowidIsValid = 0;
   63819       }else{
   63820         /* u.az.res might be negative because the table is empty.  Check to
   63821         ** see if this is the case.
   63822         */
   63823         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
   63824       }
   63825     }
   63826     assert( pOp->p2>0 );
   63827     if( u.az.res ){
   63828       pc = pOp->p2 - 1;
   63829     }
   63830   }else{
   63831     /* This happens when attempting to open the sqlite3_master table
   63832     ** for read access returns SQLITE_EMPTY. In this case always
   63833     ** take the jump (since there are no records in the table).
   63834     */
   63835     pc = pOp->p2 - 1;
   63836   }
   63837   break;
   63838 }
   63839 
   63840 /* Opcode: Seek P1 P2 * * *
   63841 **
   63842 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
   63843 ** for P1 to move so that it points to the rowid given by P2.
   63844 **
   63845 ** This is actually a deferred seek.  Nothing actually happens until
   63846 ** the cursor is used to read a record.  That way, if no reads
   63847 ** occur, no unnecessary I/O happens.
   63848 */
   63849 case OP_Seek: {    /* in2 */
   63850 #if 0  /* local variables moved into u.ba */
   63851   VdbeCursor *pC;
   63852 #endif /* local variables moved into u.ba */
   63853 
   63854   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   63855   u.ba.pC = p->apCsr[pOp->p1];
   63856   assert( u.ba.pC!=0 );
   63857   if( ALWAYS(u.ba.pC->pCursor!=0) ){
   63858     assert( u.ba.pC->isTable );
   63859     u.ba.pC->nullRow = 0;
   63860     pIn2 = &aMem[pOp->p2];
   63861     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
   63862     u.ba.pC->rowidIsValid = 0;
   63863     u.ba.pC->deferredMoveto = 1;
   63864   }
   63865   break;
   63866 }
   63867 
   63868 
   63869 /* Opcode: Found P1 P2 P3 P4 *
   63870 **
   63871 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   63872 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   63873 ** record.
   63874 **
   63875 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   63876 ** is a prefix of any entry in P1 then a jump is made to P2 and
   63877 ** P1 is left pointing at the matching entry.
   63878 */
   63879 /* Opcode: NotFound P1 P2 P3 P4 *
   63880 **
   63881 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
   63882 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
   63883 ** record.
   63884 **
   63885 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
   63886 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
   63887 ** does contain an entry whose prefix matches the P3/P4 record then control
   63888 ** falls through to the next instruction and P1 is left pointing at the
   63889 ** matching entry.
   63890 **
   63891 ** See also: Found, NotExists, IsUnique
   63892 */
   63893 case OP_NotFound:       /* jump, in3 */
   63894 case OP_Found: {        /* jump, in3 */
   63895 #if 0  /* local variables moved into u.bb */
   63896   int alreadyExists;
   63897   VdbeCursor *pC;
   63898   int res;
   63899   UnpackedRecord *pIdxKey;
   63900   UnpackedRecord r;
   63901   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
   63902 #endif /* local variables moved into u.bb */
   63903 
   63904 #ifdef SQLITE_TEST
   63905   sqlite3_found_count++;
   63906 #endif
   63907 
   63908   u.bb.alreadyExists = 0;
   63909   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   63910   assert( pOp->p4type==P4_INT32 );
   63911   u.bb.pC = p->apCsr[pOp->p1];
   63912   assert( u.bb.pC!=0 );
   63913   pIn3 = &aMem[pOp->p3];
   63914   if( ALWAYS(u.bb.pC->pCursor!=0) ){
   63915 
   63916     assert( u.bb.pC->isTable==0 );
   63917     if( pOp->p4.i>0 ){
   63918       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
   63919       u.bb.r.nField = (u16)pOp->p4.i;
   63920       u.bb.r.aMem = pIn3;
   63921 #ifdef SQLITE_DEBUG
   63922       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
   63923 #endif
   63924       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
   63925       u.bb.pIdxKey = &u.bb.r;
   63926     }else{
   63927       assert( pIn3->flags & MEM_Blob );
   63928       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
   63929       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
   63930                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
   63931       if( u.bb.pIdxKey==0 ){
   63932         goto no_mem;
   63933       }
   63934       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
   63935     }
   63936     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
   63937     if( pOp->p4.i==0 ){
   63938       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
   63939     }
   63940     if( rc!=SQLITE_OK ){
   63941       break;
   63942     }
   63943     u.bb.alreadyExists = (u.bb.res==0);
   63944     u.bb.pC->deferredMoveto = 0;
   63945     u.bb.pC->cacheStatus = CACHE_STALE;
   63946   }
   63947   if( pOp->opcode==OP_Found ){
   63948     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
   63949   }else{
   63950     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
   63951   }
   63952   break;
   63953 }
   63954 
   63955 /* Opcode: IsUnique P1 P2 P3 P4 *
   63956 **
   63957 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
   63958 ** no data and where the key are records generated by OP_MakeRecord with
   63959 ** the list field being the integer ROWID of the entry that the index
   63960 ** entry refers to.
   63961 **
   63962 ** The P3 register contains an integer record number. Call this record
   63963 ** number R. Register P4 is the first in a set of N contiguous registers
   63964 ** that make up an unpacked index key that can be used with cursor P1.
   63965 ** The value of N can be inferred from the cursor. N includes the rowid
   63966 ** value appended to the end of the index record. This rowid value may
   63967 ** or may not be the same as R.
   63968 **
   63969 ** If any of the N registers beginning with register P4 contains a NULL
   63970 ** value, jump immediately to P2.
   63971 **
   63972 ** Otherwise, this instruction checks if cursor P1 contains an entry
   63973 ** where the first (N-1) fields match but the rowid value at the end
   63974 ** of the index entry is not R. If there is no such entry, control jumps
   63975 ** to instruction P2. Otherwise, the rowid of the conflicting index
   63976 ** entry is copied to register P3 and control falls through to the next
   63977 ** instruction.
   63978 **
   63979 ** See also: NotFound, NotExists, Found
   63980 */
   63981 case OP_IsUnique: {        /* jump, in3 */
   63982 #if 0  /* local variables moved into u.bc */
   63983   u16 ii;
   63984   VdbeCursor *pCx;
   63985   BtCursor *pCrsr;
   63986   u16 nField;
   63987   Mem *aMx;
   63988   UnpackedRecord r;                  /* B-Tree index search key */
   63989   i64 R;                             /* Rowid stored in register P3 */
   63990 #endif /* local variables moved into u.bc */
   63991 
   63992   pIn3 = &aMem[pOp->p3];
   63993   u.bc.aMx = &aMem[pOp->p4.i];
   63994   /* Assert that the values of parameters P1 and P4 are in range. */
   63995   assert( pOp->p4type==P4_INT32 );
   63996   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
   63997   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   63998 
   63999   /* Find the index cursor. */
   64000   u.bc.pCx = p->apCsr[pOp->p1];
   64001   assert( u.bc.pCx->deferredMoveto==0 );
   64002   u.bc.pCx->seekResult = 0;
   64003   u.bc.pCx->cacheStatus = CACHE_STALE;
   64004   u.bc.pCrsr = u.bc.pCx->pCursor;
   64005 
   64006   /* If any of the values are NULL, take the jump. */
   64007   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
   64008   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
   64009     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
   64010       pc = pOp->p2 - 1;
   64011       u.bc.pCrsr = 0;
   64012       break;
   64013     }
   64014   }
   64015   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
   64016 
   64017   if( u.bc.pCrsr!=0 ){
   64018     /* Populate the index search key. */
   64019     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
   64020     u.bc.r.nField = u.bc.nField + 1;
   64021     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
   64022     u.bc.r.aMem = u.bc.aMx;
   64023 #ifdef SQLITE_DEBUG
   64024     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
   64025 #endif
   64026 
   64027     /* Extract the value of u.bc.R from register P3. */
   64028     sqlite3VdbeMemIntegerify(pIn3);
   64029     u.bc.R = pIn3->u.i;
   64030 
   64031     /* Search the B-Tree index. If no conflicting record is found, jump
   64032     ** to P2. Otherwise, copy the rowid of the conflicting record to
   64033     ** register P3 and fall through to the next instruction.  */
   64034     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
   64035     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
   64036       pc = pOp->p2 - 1;
   64037     }else{
   64038       pIn3->u.i = u.bc.r.rowid;
   64039     }
   64040   }
   64041   break;
   64042 }
   64043 
   64044 /* Opcode: NotExists P1 P2 P3 * *
   64045 **
   64046 ** Use the content of register P3 as a integer key.  If a record
   64047 ** with that key does not exist in table of P1, then jump to P2.
   64048 ** If the record does exist, then fall through.  The cursor is left
   64049 ** pointing to the record if it exists.
   64050 **
   64051 ** The difference between this operation and NotFound is that this
   64052 ** operation assumes the key is an integer and that P1 is a table whereas
   64053 ** NotFound assumes key is a blob constructed from MakeRecord and
   64054 ** P1 is an index.
   64055 **
   64056 ** See also: Found, NotFound, IsUnique
   64057 */
   64058 case OP_NotExists: {        /* jump, in3 */
   64059 #if 0  /* local variables moved into u.bd */
   64060   VdbeCursor *pC;
   64061   BtCursor *pCrsr;
   64062   int res;
   64063   u64 iKey;
   64064 #endif /* local variables moved into u.bd */
   64065 
   64066   pIn3 = &aMem[pOp->p3];
   64067   assert( pIn3->flags & MEM_Int );
   64068   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64069   u.bd.pC = p->apCsr[pOp->p1];
   64070   assert( u.bd.pC!=0 );
   64071   assert( u.bd.pC->isTable );
   64072   assert( u.bd.pC->pseudoTableReg==0 );
   64073   u.bd.pCrsr = u.bd.pC->pCursor;
   64074   if( u.bd.pCrsr!=0 ){
   64075     u.bd.res = 0;
   64076     u.bd.iKey = pIn3->u.i;
   64077     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
   64078     u.bd.pC->lastRowid = pIn3->u.i;
   64079     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
   64080     u.bd.pC->nullRow = 0;
   64081     u.bd.pC->cacheStatus = CACHE_STALE;
   64082     u.bd.pC->deferredMoveto = 0;
   64083     if( u.bd.res!=0 ){
   64084       pc = pOp->p2 - 1;
   64085       assert( u.bd.pC->rowidIsValid==0 );
   64086     }
   64087     u.bd.pC->seekResult = u.bd.res;
   64088   }else{
   64089     /* This happens when an attempt to open a read cursor on the
   64090     ** sqlite_master table returns SQLITE_EMPTY.
   64091     */
   64092     pc = pOp->p2 - 1;
   64093     assert( u.bd.pC->rowidIsValid==0 );
   64094     u.bd.pC->seekResult = 0;
   64095   }
   64096   break;
   64097 }
   64098 
   64099 /* Opcode: Sequence P1 P2 * * *
   64100 **
   64101 ** Find the next available sequence number for cursor P1.
   64102 ** Write the sequence number into register P2.
   64103 ** The sequence number on the cursor is incremented after this
   64104 ** instruction.
   64105 */
   64106 case OP_Sequence: {           /* out2-prerelease */
   64107   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64108   assert( p->apCsr[pOp->p1]!=0 );
   64109   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
   64110   break;
   64111 }
   64112 
   64113 
   64114 /* Opcode: NewRowid P1 P2 P3 * *
   64115 **
   64116 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
   64117 ** The record number is not previously used as a key in the database
   64118 ** table that cursor P1 points to.  The new record number is written
   64119 ** written to register P2.
   64120 **
   64121 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
   64122 ** the largest previously generated record number. No new record numbers are
   64123 ** allowed to be less than this value. When this value reaches its maximum,
   64124 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
   64125 ** generated record number. This P3 mechanism is used to help implement the
   64126 ** AUTOINCREMENT feature.
   64127 */
   64128 case OP_NewRowid: {           /* out2-prerelease */
   64129 #if 0  /* local variables moved into u.be */
   64130   i64 v;                 /* The new rowid */
   64131   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
   64132   int res;               /* Result of an sqlite3BtreeLast() */
   64133   int cnt;               /* Counter to limit the number of searches */
   64134   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
   64135   VdbeFrame *pFrame;     /* Root frame of VDBE */
   64136 #endif /* local variables moved into u.be */
   64137 
   64138   u.be.v = 0;
   64139   u.be.res = 0;
   64140   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64141   u.be.pC = p->apCsr[pOp->p1];
   64142   assert( u.be.pC!=0 );
   64143   if( NEVER(u.be.pC->pCursor==0) ){
   64144     /* The zero initialization above is all that is needed */
   64145   }else{
   64146     /* The next rowid or record number (different terms for the same
   64147     ** thing) is obtained in a two-step algorithm.
   64148     **
   64149     ** First we attempt to find the largest existing rowid and add one
   64150     ** to that.  But if the largest existing rowid is already the maximum
   64151     ** positive integer, we have to fall through to the second
   64152     ** probabilistic algorithm
   64153     **
   64154     ** The second algorithm is to select a rowid at random and see if
   64155     ** it already exists in the table.  If it does not exist, we have
   64156     ** succeeded.  If the random rowid does exist, we select a new one
   64157     ** and try again, up to 100 times.
   64158     */
   64159     assert( u.be.pC->isTable );
   64160     u.be.cnt = 0;
   64161 
   64162 #ifdef SQLITE_32BIT_ROWID
   64163 #   define MAX_ROWID 0x7fffffff
   64164 #else
   64165     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
   64166     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
   64167     ** to provide the constant while making all compilers happy.
   64168     */
   64169 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
   64170 #endif
   64171 
   64172     if( !u.be.pC->useRandomRowid ){
   64173       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
   64174       if( u.be.v==0 ){
   64175         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
   64176         if( rc!=SQLITE_OK ){
   64177           goto abort_due_to_error;
   64178         }
   64179         if( u.be.res ){
   64180           u.be.v = 1;   /* IMP: R-61914-48074 */
   64181         }else{
   64182           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
   64183           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
   64184           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
   64185           if( u.be.v==MAX_ROWID ){
   64186             u.be.pC->useRandomRowid = 1;
   64187           }else{
   64188             u.be.v++;   /* IMP: R-29538-34987 */
   64189           }
   64190         }
   64191       }
   64192 
   64193 #ifndef SQLITE_OMIT_AUTOINCREMENT
   64194       if( pOp->p3 ){
   64195         /* Assert that P3 is a valid memory cell. */
   64196         assert( pOp->p3>0 );
   64197         if( p->pFrame ){
   64198           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
   64199           /* Assert that P3 is a valid memory cell. */
   64200           assert( pOp->p3<=u.be.pFrame->nMem );
   64201           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
   64202         }else{
   64203           /* Assert that P3 is a valid memory cell. */
   64204           assert( pOp->p3<=p->nMem );
   64205           u.be.pMem = &aMem[pOp->p3];
   64206           memAboutToChange(p, u.be.pMem);
   64207         }
   64208         assert( memIsValid(u.be.pMem) );
   64209 
   64210         REGISTER_TRACE(pOp->p3, u.be.pMem);
   64211         sqlite3VdbeMemIntegerify(u.be.pMem);
   64212         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
   64213         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
   64214           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
   64215           goto abort_due_to_error;
   64216         }
   64217         if( u.be.v<u.be.pMem->u.i+1 ){
   64218           u.be.v = u.be.pMem->u.i + 1;
   64219         }
   64220         u.be.pMem->u.i = u.be.v;
   64221       }
   64222 #endif
   64223 
   64224       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
   64225     }
   64226     if( u.be.pC->useRandomRowid ){
   64227       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
   64228       ** largest possible integer (9223372036854775807) then the database
   64229       ** engine starts picking positive candidate ROWIDs at random until
   64230       ** it finds one that is not previously used. */
   64231       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
   64232                              ** an AUTOINCREMENT table. */
   64233       /* on the first attempt, simply do one more than previous */
   64234       u.be.v = db->lastRowid;
   64235       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   64236       u.be.v++; /* ensure non-zero */
   64237       u.be.cnt = 0;
   64238       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
   64239                                                  0, &u.be.res))==SQLITE_OK)
   64240             && (u.be.res==0)
   64241             && (++u.be.cnt<100)){
   64242         /* collision - try another random rowid */
   64243         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
   64244         if( u.be.cnt<5 ){
   64245           /* try "small" random rowids for the initial attempts */
   64246           u.be.v &= 0xffffff;
   64247         }else{
   64248           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
   64249         }
   64250         u.be.v++; /* ensure non-zero */
   64251       }
   64252       if( rc==SQLITE_OK && u.be.res==0 ){
   64253         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
   64254         goto abort_due_to_error;
   64255       }
   64256       assert( u.be.v>0 );  /* EV: R-40812-03570 */
   64257     }
   64258     u.be.pC->rowidIsValid = 0;
   64259     u.be.pC->deferredMoveto = 0;
   64260     u.be.pC->cacheStatus = CACHE_STALE;
   64261   }
   64262   pOut->u.i = u.be.v;
   64263   break;
   64264 }
   64265 
   64266 /* Opcode: Insert P1 P2 P3 P4 P5
   64267 **
   64268 ** Write an entry into the table of cursor P1.  A new entry is
   64269 ** created if it doesn't already exist or the data for an existing
   64270 ** entry is overwritten.  The data is the value MEM_Blob stored in register
   64271 ** number P2. The key is stored in register P3. The key must
   64272 ** be a MEM_Int.
   64273 **
   64274 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
   64275 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
   64276 ** then rowid is stored for subsequent return by the
   64277 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
   64278 **
   64279 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
   64280 ** the last seek operation (OP_NotExists) was a success, then this
   64281 ** operation will not attempt to find the appropriate row before doing
   64282 ** the insert but will instead overwrite the row that the cursor is
   64283 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
   64284 ** has already positioned the cursor correctly.  This is an optimization
   64285 ** that boosts performance by avoiding redundant seeks.
   64286 **
   64287 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
   64288 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
   64289 ** is part of an INSERT operation.  The difference is only important to
   64290 ** the update hook.
   64291 **
   64292 ** Parameter P4 may point to a string containing the table-name, or
   64293 ** may be NULL. If it is not NULL, then the update-hook
   64294 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
   64295 **
   64296 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
   64297 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
   64298 ** and register P2 becomes ephemeral.  If the cursor is changed, the
   64299 ** value of register P2 will then change.  Make sure this does not
   64300 ** cause any problems.)
   64301 **
   64302 ** This instruction only works on tables.  The equivalent instruction
   64303 ** for indices is OP_IdxInsert.
   64304 */
   64305 /* Opcode: InsertInt P1 P2 P3 P4 P5
   64306 **
   64307 ** This works exactly like OP_Insert except that the key is the
   64308 ** integer value P3, not the value of the integer stored in register P3.
   64309 */
   64310 case OP_Insert:
   64311 case OP_InsertInt: {
   64312 #if 0  /* local variables moved into u.bf */
   64313   Mem *pData;       /* MEM cell holding data for the record to be inserted */
   64314   Mem *pKey;        /* MEM cell holding key  for the record */
   64315   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
   64316   VdbeCursor *pC;   /* Cursor to table into which insert is written */
   64317   int nZero;        /* Number of zero-bytes to append */
   64318   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
   64319   const char *zDb;  /* database name - used by the update hook */
   64320   const char *zTbl; /* Table name - used by the opdate hook */
   64321   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
   64322 #endif /* local variables moved into u.bf */
   64323 
   64324   u.bf.pData = &aMem[pOp->p2];
   64325   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64326   assert( memIsValid(u.bf.pData) );
   64327   u.bf.pC = p->apCsr[pOp->p1];
   64328   assert( u.bf.pC!=0 );
   64329   assert( u.bf.pC->pCursor!=0 );
   64330   assert( u.bf.pC->pseudoTableReg==0 );
   64331   assert( u.bf.pC->isTable );
   64332   REGISTER_TRACE(pOp->p2, u.bf.pData);
   64333 
   64334   if( pOp->opcode==OP_Insert ){
   64335     u.bf.pKey = &aMem[pOp->p3];
   64336     assert( u.bf.pKey->flags & MEM_Int );
   64337     assert( memIsValid(u.bf.pKey) );
   64338     REGISTER_TRACE(pOp->p3, u.bf.pKey);
   64339     u.bf.iKey = u.bf.pKey->u.i;
   64340   }else{
   64341     assert( pOp->opcode==OP_InsertInt );
   64342     u.bf.iKey = pOp->p3;
   64343   }
   64344 
   64345   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   64346   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
   64347   if( u.bf.pData->flags & MEM_Null ){
   64348     u.bf.pData->z = 0;
   64349     u.bf.pData->n = 0;
   64350   }else{
   64351     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
   64352   }
   64353   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
   64354   if( u.bf.pData->flags & MEM_Zero ){
   64355     u.bf.nZero = u.bf.pData->u.nZero;
   64356   }else{
   64357     u.bf.nZero = 0;
   64358   }
   64359   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
   64360   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
   64361                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
   64362                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
   64363   );
   64364   u.bf.pC->rowidIsValid = 0;
   64365   u.bf.pC->deferredMoveto = 0;
   64366   u.bf.pC->cacheStatus = CACHE_STALE;
   64367 
   64368   /* Invoke the update-hook if required. */
   64369   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   64370     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
   64371     u.bf.zTbl = pOp->p4.z;
   64372     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
   64373     assert( u.bf.pC->isTable );
   64374     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
   64375     assert( u.bf.pC->iDb>=0 );
   64376   }
   64377   break;
   64378 }
   64379 
   64380 /* Opcode: Delete P1 P2 * P4 *
   64381 **
   64382 ** Delete the record at which the P1 cursor is currently pointing.
   64383 **
   64384 ** The cursor will be left pointing at either the next or the previous
   64385 ** record in the table. If it is left pointing at the next record, then
   64386 ** the next Next instruction will be a no-op.  Hence it is OK to delete
   64387 ** a record from within an Next loop.
   64388 **
   64389 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
   64390 ** incremented (otherwise not).
   64391 **
   64392 ** P1 must not be pseudo-table.  It has to be a real table with
   64393 ** multiple rows.
   64394 **
   64395 ** If P4 is not NULL, then it is the name of the table that P1 is
   64396 ** pointing to.  The update hook will be invoked, if it exists.
   64397 ** If P4 is not NULL then the P1 cursor must have been positioned
   64398 ** using OP_NotFound prior to invoking this opcode.
   64399 */
   64400 case OP_Delete: {
   64401 #if 0  /* local variables moved into u.bg */
   64402   i64 iKey;
   64403   VdbeCursor *pC;
   64404 #endif /* local variables moved into u.bg */
   64405 
   64406   u.bg.iKey = 0;
   64407   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64408   u.bg.pC = p->apCsr[pOp->p1];
   64409   assert( u.bg.pC!=0 );
   64410   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
   64411 
   64412   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
   64413   ** row being deleted.
   64414   */
   64415   if( db->xUpdateCallback && pOp->p4.z ){
   64416     assert( u.bg.pC->isTable );
   64417     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
   64418     u.bg.iKey = u.bg.pC->lastRowid;
   64419   }
   64420 
   64421   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
   64422   ** OP_Column on the same table without any intervening operations that
   64423   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
   64424   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
   64425   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
   64426   ** to guard against future changes to the code generator.
   64427   **/
   64428   assert( u.bg.pC->deferredMoveto==0 );
   64429   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
   64430   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   64431 
   64432   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
   64433   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
   64434   u.bg.pC->cacheStatus = CACHE_STALE;
   64435 
   64436   /* Invoke the update-hook if required. */
   64437   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
   64438     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
   64439     const char *zTbl = pOp->p4.z;
   64440     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
   64441     assert( u.bg.pC->iDb>=0 );
   64442   }
   64443   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
   64444   break;
   64445 }
   64446 /* Opcode: ResetCount * * * * *
   64447 **
   64448 ** The value of the change counter is copied to the database handle
   64449 ** change counter (returned by subsequent calls to sqlite3_changes()).
   64450 ** Then the VMs internal change counter resets to 0.
   64451 ** This is used by trigger programs.
   64452 */
   64453 case OP_ResetCount: {
   64454   sqlite3VdbeSetChanges(db, p->nChange);
   64455   p->nChange = 0;
   64456   break;
   64457 }
   64458 
   64459 /* Opcode: RowData P1 P2 * * *
   64460 **
   64461 ** Write into register P2 the complete row data for cursor P1.
   64462 ** There is no interpretation of the data.
   64463 ** It is just copied onto the P2 register exactly as
   64464 ** it is found in the database file.
   64465 **
   64466 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   64467 ** of a real table, not a pseudo-table.
   64468 */
   64469 /* Opcode: RowKey P1 P2 * * *
   64470 **
   64471 ** Write into register P2 the complete row key for cursor P1.
   64472 ** There is no interpretation of the data.
   64473 ** The key is copied onto the P3 register exactly as
   64474 ** it is found in the database file.
   64475 **
   64476 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
   64477 ** of a real table, not a pseudo-table.
   64478 */
   64479 case OP_RowKey:
   64480 case OP_RowData: {
   64481 #if 0  /* local variables moved into u.bh */
   64482   VdbeCursor *pC;
   64483   BtCursor *pCrsr;
   64484   u32 n;
   64485   i64 n64;
   64486 #endif /* local variables moved into u.bh */
   64487 
   64488   pOut = &aMem[pOp->p2];
   64489   memAboutToChange(p, pOut);
   64490 
   64491   /* Note that RowKey and RowData are really exactly the same instruction */
   64492   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64493   u.bh.pC = p->apCsr[pOp->p1];
   64494   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
   64495   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
   64496   assert( u.bh.pC!=0 );
   64497   assert( u.bh.pC->nullRow==0 );
   64498   assert( u.bh.pC->pseudoTableReg==0 );
   64499   assert( u.bh.pC->pCursor!=0 );
   64500   u.bh.pCrsr = u.bh.pC->pCursor;
   64501   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
   64502 
   64503   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
   64504   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
   64505   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
   64506   ** a no-op and can never fail.  But we leave it in place as a safety.
   64507   */
   64508   assert( u.bh.pC->deferredMoveto==0 );
   64509   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
   64510   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
   64511 
   64512   if( u.bh.pC->isIndex ){
   64513     assert( !u.bh.pC->isTable );
   64514     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
   64515     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
   64516     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   64517       goto too_big;
   64518     }
   64519     u.bh.n = (u32)u.bh.n64;
   64520   }else{
   64521     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
   64522     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
   64523     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   64524       goto too_big;
   64525     }
   64526   }
   64527   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
   64528     goto no_mem;
   64529   }
   64530   pOut->n = u.bh.n;
   64531   MemSetTypeFlag(pOut, MEM_Blob);
   64532   if( u.bh.pC->isIndex ){
   64533     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
   64534   }else{
   64535     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
   64536   }
   64537   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
   64538   UPDATE_MAX_BLOBSIZE(pOut);
   64539   break;
   64540 }
   64541 
   64542 /* Opcode: Rowid P1 P2 * * *
   64543 **
   64544 ** Store in register P2 an integer which is the key of the table entry that
   64545 ** P1 is currently point to.
   64546 **
   64547 ** P1 can be either an ordinary table or a virtual table.  There used to
   64548 ** be a separate OP_VRowid opcode for use with virtual tables, but this
   64549 ** one opcode now works for both table types.
   64550 */
   64551 case OP_Rowid: {                 /* out2-prerelease */
   64552 #if 0  /* local variables moved into u.bi */
   64553   VdbeCursor *pC;
   64554   i64 v;
   64555   sqlite3_vtab *pVtab;
   64556   const sqlite3_module *pModule;
   64557 #endif /* local variables moved into u.bi */
   64558 
   64559   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64560   u.bi.pC = p->apCsr[pOp->p1];
   64561   assert( u.bi.pC!=0 );
   64562   assert( u.bi.pC->pseudoTableReg==0 );
   64563   if( u.bi.pC->nullRow ){
   64564     pOut->flags = MEM_Null;
   64565     break;
   64566   }else if( u.bi.pC->deferredMoveto ){
   64567     u.bi.v = u.bi.pC->movetoTarget;
   64568 #ifndef SQLITE_OMIT_VIRTUALTABLE
   64569   }else if( u.bi.pC->pVtabCursor ){
   64570     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
   64571     u.bi.pModule = u.bi.pVtab->pModule;
   64572     assert( u.bi.pModule->xRowid );
   64573     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
   64574     importVtabErrMsg(p, u.bi.pVtab);
   64575 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   64576   }else{
   64577     assert( u.bi.pC->pCursor!=0 );
   64578     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
   64579     if( rc ) goto abort_due_to_error;
   64580     if( u.bi.pC->rowidIsValid ){
   64581       u.bi.v = u.bi.pC->lastRowid;
   64582     }else{
   64583       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
   64584       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
   64585     }
   64586   }
   64587   pOut->u.i = u.bi.v;
   64588   break;
   64589 }
   64590 
   64591 /* Opcode: NullRow P1 * * * *
   64592 **
   64593 ** Move the cursor P1 to a null row.  Any OP_Column operations
   64594 ** that occur while the cursor is on the null row will always
   64595 ** write a NULL.
   64596 */
   64597 case OP_NullRow: {
   64598 #if 0  /* local variables moved into u.bj */
   64599   VdbeCursor *pC;
   64600 #endif /* local variables moved into u.bj */
   64601 
   64602   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64603   u.bj.pC = p->apCsr[pOp->p1];
   64604   assert( u.bj.pC!=0 );
   64605   u.bj.pC->nullRow = 1;
   64606   u.bj.pC->rowidIsValid = 0;
   64607   if( u.bj.pC->pCursor ){
   64608     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
   64609   }
   64610   break;
   64611 }
   64612 
   64613 /* Opcode: Last P1 P2 * * *
   64614 **
   64615 ** The next use of the Rowid or Column or Next instruction for P1
   64616 ** will refer to the last entry in the database table or index.
   64617 ** If the table or index is empty and P2>0, then jump immediately to P2.
   64618 ** If P2 is 0 or if the table or index is not empty, fall through
   64619 ** to the following instruction.
   64620 */
   64621 case OP_Last: {        /* jump */
   64622 #if 0  /* local variables moved into u.bk */
   64623   VdbeCursor *pC;
   64624   BtCursor *pCrsr;
   64625   int res;
   64626 #endif /* local variables moved into u.bk */
   64627 
   64628   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64629   u.bk.pC = p->apCsr[pOp->p1];
   64630   assert( u.bk.pC!=0 );
   64631   u.bk.pCrsr = u.bk.pC->pCursor;
   64632   if( u.bk.pCrsr==0 ){
   64633     u.bk.res = 1;
   64634   }else{
   64635     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
   64636   }
   64637   u.bk.pC->nullRow = (u8)u.bk.res;
   64638   u.bk.pC->deferredMoveto = 0;
   64639   u.bk.pC->rowidIsValid = 0;
   64640   u.bk.pC->cacheStatus = CACHE_STALE;
   64641   if( pOp->p2>0 && u.bk.res ){
   64642     pc = pOp->p2 - 1;
   64643   }
   64644   break;
   64645 }
   64646 
   64647 
   64648 /* Opcode: Sort P1 P2 * * *
   64649 **
   64650 ** This opcode does exactly the same thing as OP_Rewind except that
   64651 ** it increments an undocumented global variable used for testing.
   64652 **
   64653 ** Sorting is accomplished by writing records into a sorting index,
   64654 ** then rewinding that index and playing it back from beginning to
   64655 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
   64656 ** rewinding so that the global variable will be incremented and
   64657 ** regression tests can determine whether or not the optimizer is
   64658 ** correctly optimizing out sorts.
   64659 */
   64660 case OP_Sort: {        /* jump */
   64661 #ifdef SQLITE_TEST
   64662   sqlite3_sort_count++;
   64663   sqlite3_search_count--;
   64664 #endif
   64665   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
   64666   /* Fall through into OP_Rewind */
   64667 }
   64668 /* Opcode: Rewind P1 P2 * * *
   64669 **
   64670 ** The next use of the Rowid or Column or Next instruction for P1
   64671 ** will refer to the first entry in the database table or index.
   64672 ** If the table or index is empty and P2>0, then jump immediately to P2.
   64673 ** If P2 is 0 or if the table or index is not empty, fall through
   64674 ** to the following instruction.
   64675 */
   64676 case OP_Rewind: {        /* jump */
   64677 #if 0  /* local variables moved into u.bl */
   64678   VdbeCursor *pC;
   64679   BtCursor *pCrsr;
   64680   int res;
   64681 #endif /* local variables moved into u.bl */
   64682 
   64683   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64684   u.bl.pC = p->apCsr[pOp->p1];
   64685   assert( u.bl.pC!=0 );
   64686   u.bl.res = 1;
   64687   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
   64688     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
   64689     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
   64690     u.bl.pC->deferredMoveto = 0;
   64691     u.bl.pC->cacheStatus = CACHE_STALE;
   64692     u.bl.pC->rowidIsValid = 0;
   64693   }
   64694   u.bl.pC->nullRow = (u8)u.bl.res;
   64695   assert( pOp->p2>0 && pOp->p2<p->nOp );
   64696   if( u.bl.res ){
   64697     pc = pOp->p2 - 1;
   64698   }
   64699   break;
   64700 }
   64701 
   64702 /* Opcode: Next P1 P2 * * P5
   64703 **
   64704 ** Advance cursor P1 so that it points to the next key/data pair in its
   64705 ** table or index.  If there are no more key/value pairs then fall through
   64706 ** to the following instruction.  But if the cursor advance was successful,
   64707 ** jump immediately to P2.
   64708 **
   64709 ** The P1 cursor must be for a real table, not a pseudo-table.
   64710 **
   64711 ** If P5 is positive and the jump is taken, then event counter
   64712 ** number P5-1 in the prepared statement is incremented.
   64713 **
   64714 ** See also: Prev
   64715 */
   64716 /* Opcode: Prev P1 P2 * * P5
   64717 **
   64718 ** Back up cursor P1 so that it points to the previous key/data pair in its
   64719 ** table or index.  If there is no previous key/value pairs then fall through
   64720 ** to the following instruction.  But if the cursor backup was successful,
   64721 ** jump immediately to P2.
   64722 **
   64723 ** The P1 cursor must be for a real table, not a pseudo-table.
   64724 **
   64725 ** If P5 is positive and the jump is taken, then event counter
   64726 ** number P5-1 in the prepared statement is incremented.
   64727 */
   64728 case OP_Prev:          /* jump */
   64729 case OP_Next: {        /* jump */
   64730 #if 0  /* local variables moved into u.bm */
   64731   VdbeCursor *pC;
   64732   BtCursor *pCrsr;
   64733   int res;
   64734 #endif /* local variables moved into u.bm */
   64735 
   64736   CHECK_FOR_INTERRUPT;
   64737   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64738   assert( pOp->p5<=ArraySize(p->aCounter) );
   64739   u.bm.pC = p->apCsr[pOp->p1];
   64740   if( u.bm.pC==0 ){
   64741     break;  /* See ticket #2273 */
   64742   }
   64743   u.bm.pCrsr = u.bm.pC->pCursor;
   64744   if( u.bm.pCrsr==0 ){
   64745     u.bm.pC->nullRow = 1;
   64746     break;
   64747   }
   64748   u.bm.res = 1;
   64749   assert( u.bm.pC->deferredMoveto==0 );
   64750   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
   64751                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
   64752   u.bm.pC->nullRow = (u8)u.bm.res;
   64753   u.bm.pC->cacheStatus = CACHE_STALE;
   64754   if( u.bm.res==0 ){
   64755     pc = pOp->p2 - 1;
   64756     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
   64757 #ifdef SQLITE_TEST
   64758     sqlite3_search_count++;
   64759 #endif
   64760   }
   64761   u.bm.pC->rowidIsValid = 0;
   64762   break;
   64763 }
   64764 
   64765 /* Opcode: IdxInsert P1 P2 P3 * P5
   64766 **
   64767 ** Register P2 holds a SQL index key made using the
   64768 ** MakeRecord instructions.  This opcode writes that key
   64769 ** into the index P1.  Data for the entry is nil.
   64770 **
   64771 ** P3 is a flag that provides a hint to the b-tree layer that this
   64772 ** insert is likely to be an append.
   64773 **
   64774 ** This instruction only works for indices.  The equivalent instruction
   64775 ** for tables is OP_Insert.
   64776 */
   64777 case OP_IdxInsert: {        /* in2 */
   64778 #if 0  /* local variables moved into u.bn */
   64779   VdbeCursor *pC;
   64780   BtCursor *pCrsr;
   64781   int nKey;
   64782   const char *zKey;
   64783 #endif /* local variables moved into u.bn */
   64784 
   64785   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64786   u.bn.pC = p->apCsr[pOp->p1];
   64787   assert( u.bn.pC!=0 );
   64788   pIn2 = &aMem[pOp->p2];
   64789   assert( pIn2->flags & MEM_Blob );
   64790   u.bn.pCrsr = u.bn.pC->pCursor;
   64791   if( ALWAYS(u.bn.pCrsr!=0) ){
   64792     assert( u.bn.pC->isTable==0 );
   64793     rc = ExpandBlob(pIn2);
   64794     if( rc==SQLITE_OK ){
   64795       u.bn.nKey = pIn2->n;
   64796       u.bn.zKey = pIn2->z;
   64797       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
   64798           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
   64799       );
   64800       assert( u.bn.pC->deferredMoveto==0 );
   64801       u.bn.pC->cacheStatus = CACHE_STALE;
   64802     }
   64803   }
   64804   break;
   64805 }
   64806 
   64807 /* Opcode: IdxDelete P1 P2 P3 * *
   64808 **
   64809 ** The content of P3 registers starting at register P2 form
   64810 ** an unpacked index key. This opcode removes that entry from the
   64811 ** index opened by cursor P1.
   64812 */
   64813 case OP_IdxDelete: {
   64814 #if 0  /* local variables moved into u.bo */
   64815   VdbeCursor *pC;
   64816   BtCursor *pCrsr;
   64817   int res;
   64818   UnpackedRecord r;
   64819 #endif /* local variables moved into u.bo */
   64820 
   64821   assert( pOp->p3>0 );
   64822   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
   64823   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64824   u.bo.pC = p->apCsr[pOp->p1];
   64825   assert( u.bo.pC!=0 );
   64826   u.bo.pCrsr = u.bo.pC->pCursor;
   64827   if( ALWAYS(u.bo.pCrsr!=0) ){
   64828     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
   64829     u.bo.r.nField = (u16)pOp->p3;
   64830     u.bo.r.flags = 0;
   64831     u.bo.r.aMem = &aMem[pOp->p2];
   64832 #ifdef SQLITE_DEBUG
   64833     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
   64834 #endif
   64835     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
   64836     if( rc==SQLITE_OK && u.bo.res==0 ){
   64837       rc = sqlite3BtreeDelete(u.bo.pCrsr);
   64838     }
   64839     assert( u.bo.pC->deferredMoveto==0 );
   64840     u.bo.pC->cacheStatus = CACHE_STALE;
   64841   }
   64842   break;
   64843 }
   64844 
   64845 /* Opcode: IdxRowid P1 P2 * * *
   64846 **
   64847 ** Write into register P2 an integer which is the last entry in the record at
   64848 ** the end of the index key pointed to by cursor P1.  This integer should be
   64849 ** the rowid of the table entry to which this index entry points.
   64850 **
   64851 ** See also: Rowid, MakeRecord.
   64852 */
   64853 case OP_IdxRowid: {              /* out2-prerelease */
   64854 #if 0  /* local variables moved into u.bp */
   64855   BtCursor *pCrsr;
   64856   VdbeCursor *pC;
   64857   i64 rowid;
   64858 #endif /* local variables moved into u.bp */
   64859 
   64860   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64861   u.bp.pC = p->apCsr[pOp->p1];
   64862   assert( u.bp.pC!=0 );
   64863   u.bp.pCrsr = u.bp.pC->pCursor;
   64864   pOut->flags = MEM_Null;
   64865   if( ALWAYS(u.bp.pCrsr!=0) ){
   64866     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
   64867     if( NEVER(rc) ) goto abort_due_to_error;
   64868     assert( u.bp.pC->deferredMoveto==0 );
   64869     assert( u.bp.pC->isTable==0 );
   64870     if( !u.bp.pC->nullRow ){
   64871       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
   64872       if( rc!=SQLITE_OK ){
   64873         goto abort_due_to_error;
   64874       }
   64875       pOut->u.i = u.bp.rowid;
   64876       pOut->flags = MEM_Int;
   64877     }
   64878   }
   64879   break;
   64880 }
   64881 
   64882 /* Opcode: IdxGE P1 P2 P3 P4 P5
   64883 **
   64884 ** The P4 register values beginning with P3 form an unpacked index
   64885 ** key that omits the ROWID.  Compare this key value against the index
   64886 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   64887 **
   64888 ** If the P1 index entry is greater than or equal to the key value
   64889 ** then jump to P2.  Otherwise fall through to the next instruction.
   64890 **
   64891 ** If P5 is non-zero then the key value is increased by an epsilon
   64892 ** prior to the comparison.  This make the opcode work like IdxGT except
   64893 ** that if the key from register P3 is a prefix of the key in the cursor,
   64894 ** the result is false whereas it would be true with IdxGT.
   64895 */
   64896 /* Opcode: IdxLT P1 P2 P3 P4 P5
   64897 **
   64898 ** The P4 register values beginning with P3 form an unpacked index
   64899 ** key that omits the ROWID.  Compare this key value against the index
   64900 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
   64901 **
   64902 ** If the P1 index entry is less than the key value then jump to P2.
   64903 ** Otherwise fall through to the next instruction.
   64904 **
   64905 ** If P5 is non-zero then the key value is increased by an epsilon prior
   64906 ** to the comparison.  This makes the opcode work like IdxLE.
   64907 */
   64908 case OP_IdxLT:          /* jump */
   64909 case OP_IdxGE: {        /* jump */
   64910 #if 0  /* local variables moved into u.bq */
   64911   VdbeCursor *pC;
   64912   int res;
   64913   UnpackedRecord r;
   64914 #endif /* local variables moved into u.bq */
   64915 
   64916   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   64917   u.bq.pC = p->apCsr[pOp->p1];
   64918   assert( u.bq.pC!=0 );
   64919   assert( u.bq.pC->isOrdered );
   64920   if( ALWAYS(u.bq.pC->pCursor!=0) ){
   64921     assert( u.bq.pC->deferredMoveto==0 );
   64922     assert( pOp->p5==0 || pOp->p5==1 );
   64923     assert( pOp->p4type==P4_INT32 );
   64924     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
   64925     u.bq.r.nField = (u16)pOp->p4.i;
   64926     if( pOp->p5 ){
   64927       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
   64928     }else{
   64929       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
   64930     }
   64931     u.bq.r.aMem = &aMem[pOp->p3];
   64932 #ifdef SQLITE_DEBUG
   64933     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
   64934 #endif
   64935     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
   64936     if( pOp->opcode==OP_IdxLT ){
   64937       u.bq.res = -u.bq.res;
   64938     }else{
   64939       assert( pOp->opcode==OP_IdxGE );
   64940       u.bq.res++;
   64941     }
   64942     if( u.bq.res>0 ){
   64943       pc = pOp->p2 - 1 ;
   64944     }
   64945   }
   64946   break;
   64947 }
   64948 
   64949 /* Opcode: Destroy P1 P2 P3 * *
   64950 **
   64951 ** Delete an entire database table or index whose root page in the database
   64952 ** file is given by P1.
   64953 **
   64954 ** The table being destroyed is in the main database file if P3==0.  If
   64955 ** P3==1 then the table to be clear is in the auxiliary database file
   64956 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   64957 **
   64958 ** If AUTOVACUUM is enabled then it is possible that another root page
   64959 ** might be moved into the newly deleted root page in order to keep all
   64960 ** root pages contiguous at the beginning of the database.  The former
   64961 ** value of the root page that moved - its value before the move occurred -
   64962 ** is stored in register P2.  If no page
   64963 ** movement was required (because the table being dropped was already
   64964 ** the last one in the database) then a zero is stored in register P2.
   64965 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
   64966 **
   64967 ** See also: Clear
   64968 */
   64969 case OP_Destroy: {     /* out2-prerelease */
   64970 #if 0  /* local variables moved into u.br */
   64971   int iMoved;
   64972   int iCnt;
   64973   Vdbe *pVdbe;
   64974   int iDb;
   64975 #endif /* local variables moved into u.br */
   64976 #ifndef SQLITE_OMIT_VIRTUALTABLE
   64977   u.br.iCnt = 0;
   64978   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
   64979     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
   64980       u.br.iCnt++;
   64981     }
   64982   }
   64983 #else
   64984   u.br.iCnt = db->activeVdbeCnt;
   64985 #endif
   64986   pOut->flags = MEM_Null;
   64987   if( u.br.iCnt>1 ){
   64988     rc = SQLITE_LOCKED;
   64989     p->errorAction = OE_Abort;
   64990   }else{
   64991     u.br.iDb = pOp->p3;
   64992     assert( u.br.iCnt==1 );
   64993     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
   64994     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
   64995     pOut->flags = MEM_Int;
   64996     pOut->u.i = u.br.iMoved;
   64997 #ifndef SQLITE_OMIT_AUTOVACUUM
   64998     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
   64999       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
   65000       resetSchemaOnFault = 1;
   65001     }
   65002 #endif
   65003   }
   65004   break;
   65005 }
   65006 
   65007 /* Opcode: Clear P1 P2 P3
   65008 **
   65009 ** Delete all contents of the database table or index whose root page
   65010 ** in the database file is given by P1.  But, unlike Destroy, do not
   65011 ** remove the table or index from the database file.
   65012 **
   65013 ** The table being clear is in the main database file if P2==0.  If
   65014 ** P2==1 then the table to be clear is in the auxiliary database file
   65015 ** that is used to store tables create using CREATE TEMPORARY TABLE.
   65016 **
   65017 ** If the P3 value is non-zero, then the table referred to must be an
   65018 ** intkey table (an SQL table, not an index). In this case the row change
   65019 ** count is incremented by the number of rows in the table being cleared.
   65020 ** If P3 is greater than zero, then the value stored in register P3 is
   65021 ** also incremented by the number of rows in the table being cleared.
   65022 **
   65023 ** See also: Destroy
   65024 */
   65025 case OP_Clear: {
   65026 #if 0  /* local variables moved into u.bs */
   65027   int nChange;
   65028 #endif /* local variables moved into u.bs */
   65029 
   65030   u.bs.nChange = 0;
   65031   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
   65032   rc = sqlite3BtreeClearTable(
   65033       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
   65034   );
   65035   if( pOp->p3 ){
   65036     p->nChange += u.bs.nChange;
   65037     if( pOp->p3>0 ){
   65038       assert( memIsValid(&aMem[pOp->p3]) );
   65039       memAboutToChange(p, &aMem[pOp->p3]);
   65040       aMem[pOp->p3].u.i += u.bs.nChange;
   65041     }
   65042   }
   65043   break;
   65044 }
   65045 
   65046 /* Opcode: CreateTable P1 P2 * * *
   65047 **
   65048 ** Allocate a new table in the main database file if P1==0 or in the
   65049 ** auxiliary database file if P1==1 or in an attached database if
   65050 ** P1>1.  Write the root page number of the new table into
   65051 ** register P2
   65052 **
   65053 ** The difference between a table and an index is this:  A table must
   65054 ** have a 4-byte integer key and can have arbitrary data.  An index
   65055 ** has an arbitrary key but no data.
   65056 **
   65057 ** See also: CreateIndex
   65058 */
   65059 /* Opcode: CreateIndex P1 P2 * * *
   65060 **
   65061 ** Allocate a new index in the main database file if P1==0 or in the
   65062 ** auxiliary database file if P1==1 or in an attached database if
   65063 ** P1>1.  Write the root page number of the new table into
   65064 ** register P2.
   65065 **
   65066 ** See documentation on OP_CreateTable for additional information.
   65067 */
   65068 case OP_CreateIndex:            /* out2-prerelease */
   65069 case OP_CreateTable: {          /* out2-prerelease */
   65070 #if 0  /* local variables moved into u.bt */
   65071   int pgno;
   65072   int flags;
   65073   Db *pDb;
   65074 #endif /* local variables moved into u.bt */
   65075 
   65076   u.bt.pgno = 0;
   65077   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   65078   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   65079   u.bt.pDb = &db->aDb[pOp->p1];
   65080   assert( u.bt.pDb->pBt!=0 );
   65081   if( pOp->opcode==OP_CreateTable ){
   65082     /* u.bt.flags = BTREE_INTKEY; */
   65083     u.bt.flags = BTREE_INTKEY;
   65084   }else{
   65085     u.bt.flags = BTREE_BLOBKEY;
   65086   }
   65087   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
   65088   pOut->u.i = u.bt.pgno;
   65089   break;
   65090 }
   65091 
   65092 /* Opcode: ParseSchema P1 P2 * P4 *
   65093 **
   65094 ** Read and parse all entries from the SQLITE_MASTER table of database P1
   65095 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
   65096 ** the parsing if P2 is true.  If P2 is false, then this routine is a
   65097 ** no-op if the schema is not currently loaded.  In other words, if P2
   65098 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
   65099 ** schema is already loaded into the symbol table.
   65100 **
   65101 ** This opcode invokes the parser to create a new virtual machine,
   65102 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
   65103 */
   65104 case OP_ParseSchema: {
   65105 #if 0  /* local variables moved into u.bu */
   65106   int iDb;
   65107   const char *zMaster;
   65108   char *zSql;
   65109   InitData initData;
   65110 #endif /* local variables moved into u.bu */
   65111 
   65112   u.bu.iDb = pOp->p1;
   65113   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
   65114 
   65115   /* If pOp->p2 is 0, then this opcode is being executed to read a
   65116   ** single row, for example the row corresponding to a new index
   65117   ** created by this VDBE, from the sqlite_master table. It only
   65118   ** does this if the corresponding in-memory schema is currently
   65119   ** loaded. Otherwise, the new index definition can be loaded along
   65120   ** with the rest of the schema when it is required.
   65121   **
   65122   ** Although the mutex on the BtShared object that corresponds to
   65123   ** database u.bu.iDb (the database containing the sqlite_master table
   65124   ** read by this instruction) is currently held, it is necessary to
   65125   ** obtain the mutexes on all attached databases before checking if
   65126   ** the schema of u.bu.iDb is loaded. This is because, at the start of
   65127   ** the sqlite3_exec() call below, SQLite will invoke
   65128   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
   65129   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
   65130   ** this happens, then some other thread may delete the in-memory
   65131   ** schema of database u.bu.iDb before the SQL statement runs. The schema
   65132   ** will not be reloaded becuase the db->init.busy flag is set. This
   65133   ** can result in a "no such table: sqlite_master" or "malformed
   65134   ** database schema" error being returned to the user.
   65135   */
   65136   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
   65137   sqlite3BtreeEnterAll(db);
   65138   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
   65139     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
   65140     u.bu.initData.db = db;
   65141     u.bu.initData.iDb = pOp->p1;
   65142     u.bu.initData.pzErrMsg = &p->zErrMsg;
   65143     u.bu.zSql = sqlite3MPrintf(db,
   65144        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
   65145        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
   65146     if( u.bu.zSql==0 ){
   65147       rc = SQLITE_NOMEM;
   65148     }else{
   65149       assert( db->init.busy==0 );
   65150       db->init.busy = 1;
   65151       u.bu.initData.rc = SQLITE_OK;
   65152       assert( !db->mallocFailed );
   65153       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
   65154       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
   65155       sqlite3DbFree(db, u.bu.zSql);
   65156       db->init.busy = 0;
   65157     }
   65158   }
   65159   sqlite3BtreeLeaveAll(db);
   65160   if( rc==SQLITE_NOMEM ){
   65161     goto no_mem;
   65162   }
   65163   break;
   65164 }
   65165 
   65166 #if !defined(SQLITE_OMIT_ANALYZE)
   65167 /* Opcode: LoadAnalysis P1 * * * *
   65168 **
   65169 ** Read the sqlite_stat1 table for database P1 and load the content
   65170 ** of that table into the internal index hash table.  This will cause
   65171 ** the analysis to be used when preparing all subsequent queries.
   65172 */
   65173 case OP_LoadAnalysis: {
   65174   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   65175   rc = sqlite3AnalysisLoad(db, pOp->p1);
   65176   break;
   65177 }
   65178 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
   65179 
   65180 /* Opcode: DropTable P1 * * P4 *
   65181 **
   65182 ** Remove the internal (in-memory) data structures that describe
   65183 ** the table named P4 in database P1.  This is called after a table
   65184 ** is dropped in order to keep the internal representation of the
   65185 ** schema consistent with what is on disk.
   65186 */
   65187 case OP_DropTable: {
   65188   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
   65189   break;
   65190 }
   65191 
   65192 /* Opcode: DropIndex P1 * * P4 *
   65193 **
   65194 ** Remove the internal (in-memory) data structures that describe
   65195 ** the index named P4 in database P1.  This is called after an index
   65196 ** is dropped in order to keep the internal representation of the
   65197 ** schema consistent with what is on disk.
   65198 */
   65199 case OP_DropIndex: {
   65200   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
   65201   break;
   65202 }
   65203 
   65204 /* Opcode: DropTrigger P1 * * P4 *
   65205 **
   65206 ** Remove the internal (in-memory) data structures that describe
   65207 ** the trigger named P4 in database P1.  This is called after a trigger
   65208 ** is dropped in order to keep the internal representation of the
   65209 ** schema consistent with what is on disk.
   65210 */
   65211 case OP_DropTrigger: {
   65212   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
   65213   break;
   65214 }
   65215 
   65216 
   65217 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   65218 /* Opcode: IntegrityCk P1 P2 P3 * P5
   65219 **
   65220 ** Do an analysis of the currently open database.  Store in
   65221 ** register P1 the text of an error message describing any problems.
   65222 ** If no problems are found, store a NULL in register P1.
   65223 **
   65224 ** The register P3 contains the maximum number of allowed errors.
   65225 ** At most reg(P3) errors will be reported.
   65226 ** In other words, the analysis stops as soon as reg(P1) errors are
   65227 ** seen.  Reg(P1) is updated with the number of errors remaining.
   65228 **
   65229 ** The root page numbers of all tables in the database are integer
   65230 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
   65231 ** total.
   65232 **
   65233 ** If P5 is not zero, the check is done on the auxiliary database
   65234 ** file, not the main database file.
   65235 **
   65236 ** This opcode is used to implement the integrity_check pragma.
   65237 */
   65238 case OP_IntegrityCk: {
   65239 #if 0  /* local variables moved into u.bv */
   65240   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
   65241   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
   65242   int j;          /* Loop counter */
   65243   int nErr;       /* Number of errors reported */
   65244   char *z;        /* Text of the error report */
   65245   Mem *pnErr;     /* Register keeping track of errors remaining */
   65246 #endif /* local variables moved into u.bv */
   65247 
   65248   u.bv.nRoot = pOp->p2;
   65249   assert( u.bv.nRoot>0 );
   65250   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
   65251   if( u.bv.aRoot==0 ) goto no_mem;
   65252   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   65253   u.bv.pnErr = &aMem[pOp->p3];
   65254   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
   65255   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
   65256   pIn1 = &aMem[pOp->p1];
   65257   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
   65258     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
   65259   }
   65260   u.bv.aRoot[u.bv.j] = 0;
   65261   assert( pOp->p5<db->nDb );
   65262   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
   65263   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
   65264                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
   65265   sqlite3DbFree(db, u.bv.aRoot);
   65266   u.bv.pnErr->u.i -= u.bv.nErr;
   65267   sqlite3VdbeMemSetNull(pIn1);
   65268   if( u.bv.nErr==0 ){
   65269     assert( u.bv.z==0 );
   65270   }else if( u.bv.z==0 ){
   65271     goto no_mem;
   65272   }else{
   65273     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
   65274   }
   65275   UPDATE_MAX_BLOBSIZE(pIn1);
   65276   sqlite3VdbeChangeEncoding(pIn1, encoding);
   65277   break;
   65278 }
   65279 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   65280 
   65281 /* Opcode: RowSetAdd P1 P2 * * *
   65282 **
   65283 ** Insert the integer value held by register P2 into a boolean index
   65284 ** held in register P1.
   65285 **
   65286 ** An assertion fails if P2 is not an integer.
   65287 */
   65288 case OP_RowSetAdd: {       /* in1, in2 */
   65289   pIn1 = &aMem[pOp->p1];
   65290   pIn2 = &aMem[pOp->p2];
   65291   assert( (pIn2->flags & MEM_Int)!=0 );
   65292   if( (pIn1->flags & MEM_RowSet)==0 ){
   65293     sqlite3VdbeMemSetRowSet(pIn1);
   65294     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   65295   }
   65296   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
   65297   break;
   65298 }
   65299 
   65300 /* Opcode: RowSetRead P1 P2 P3 * *
   65301 **
   65302 ** Extract the smallest value from boolean index P1 and put that value into
   65303 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
   65304 ** unchanged and jump to instruction P2.
   65305 */
   65306 case OP_RowSetRead: {       /* jump, in1, out3 */
   65307 #if 0  /* local variables moved into u.bw */
   65308   i64 val;
   65309 #endif /* local variables moved into u.bw */
   65310   CHECK_FOR_INTERRUPT;
   65311   pIn1 = &aMem[pOp->p1];
   65312   if( (pIn1->flags & MEM_RowSet)==0
   65313    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
   65314   ){
   65315     /* The boolean index is empty */
   65316     sqlite3VdbeMemSetNull(pIn1);
   65317     pc = pOp->p2 - 1;
   65318   }else{
   65319     /* A value was pulled from the index */
   65320     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
   65321   }
   65322   break;
   65323 }
   65324 
   65325 /* Opcode: RowSetTest P1 P2 P3 P4
   65326 **
   65327 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
   65328 ** contains a RowSet object and that RowSet object contains
   65329 ** the value held in P3, jump to register P2. Otherwise, insert the
   65330 ** integer in P3 into the RowSet and continue on to the
   65331 ** next opcode.
   65332 **
   65333 ** The RowSet object is optimized for the case where successive sets
   65334 ** of integers, where each set contains no duplicates. Each set
   65335 ** of values is identified by a unique P4 value. The first set
   65336 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
   65337 ** non-negative.  For non-negative values of P4 only the lower 4
   65338 ** bits are significant.
   65339 **
   65340 ** This allows optimizations: (a) when P4==0 there is no need to test
   65341 ** the rowset object for P3, as it is guaranteed not to contain it,
   65342 ** (b) when P4==-1 there is no need to insert the value, as it will
   65343 ** never be tested for, and (c) when a value that is part of set X is
   65344 ** inserted, there is no need to search to see if the same value was
   65345 ** previously inserted as part of set X (only if it was previously
   65346 ** inserted as part of some other set).
   65347 */
   65348 case OP_RowSetTest: {                     /* jump, in1, in3 */
   65349 #if 0  /* local variables moved into u.bx */
   65350   int iSet;
   65351   int exists;
   65352 #endif /* local variables moved into u.bx */
   65353 
   65354   pIn1 = &aMem[pOp->p1];
   65355   pIn3 = &aMem[pOp->p3];
   65356   u.bx.iSet = pOp->p4.i;
   65357   assert( pIn3->flags&MEM_Int );
   65358 
   65359   /* If there is anything other than a rowset object in memory cell P1,
   65360   ** delete it now and initialize P1 with an empty rowset
   65361   */
   65362   if( (pIn1->flags & MEM_RowSet)==0 ){
   65363     sqlite3VdbeMemSetRowSet(pIn1);
   65364     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
   65365   }
   65366 
   65367   assert( pOp->p4type==P4_INT32 );
   65368   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
   65369   if( u.bx.iSet ){
   65370     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
   65371                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
   65372                                pIn3->u.i);
   65373     if( u.bx.exists ){
   65374       pc = pOp->p2 - 1;
   65375       break;
   65376     }
   65377   }
   65378   if( u.bx.iSet>=0 ){
   65379     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
   65380   }
   65381   break;
   65382 }
   65383 
   65384 
   65385 #ifndef SQLITE_OMIT_TRIGGER
   65386 
   65387 /* Opcode: Program P1 P2 P3 P4 *
   65388 **
   65389 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
   65390 **
   65391 ** P1 contains the address of the memory cell that contains the first memory
   65392 ** cell in an array of values used as arguments to the sub-program. P2
   65393 ** contains the address to jump to if the sub-program throws an IGNORE
   65394 ** exception using the RAISE() function. Register P3 contains the address
   65395 ** of a memory cell in this (the parent) VM that is used to allocate the
   65396 ** memory required by the sub-vdbe at runtime.
   65397 **
   65398 ** P4 is a pointer to the VM containing the trigger program.
   65399 */
   65400 case OP_Program: {        /* jump */
   65401 #if 0  /* local variables moved into u.by */
   65402   int nMem;               /* Number of memory registers for sub-program */
   65403   int nByte;              /* Bytes of runtime space required for sub-program */
   65404   Mem *pRt;               /* Register to allocate runtime space */
   65405   Mem *pMem;              /* Used to iterate through memory cells */
   65406   Mem *pEnd;              /* Last memory cell in new array */
   65407   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
   65408   SubProgram *pProgram;   /* Sub-program to execute */
   65409   void *t;                /* Token identifying trigger */
   65410 #endif /* local variables moved into u.by */
   65411 
   65412   u.by.pProgram = pOp->p4.pProgram;
   65413   u.by.pRt = &aMem[pOp->p3];
   65414   assert( memIsValid(u.by.pRt) );
   65415   assert( u.by.pProgram->nOp>0 );
   65416 
   65417   /* If the p5 flag is clear, then recursive invocation of triggers is
   65418   ** disabled for backwards compatibility (p5 is set if this sub-program
   65419   ** is really a trigger, not a foreign key action, and the flag set
   65420   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
   65421   **
   65422   ** It is recursive invocation of triggers, at the SQL level, that is
   65423   ** disabled. In some cases a single trigger may generate more than one
   65424   ** SubProgram (if the trigger may be executed with more than one different
   65425   ** ON CONFLICT algorithm). SubProgram structures associated with a
   65426   ** single trigger all have the same value for the SubProgram.token
   65427   ** variable.  */
   65428   if( pOp->p5 ){
   65429     u.by.t = u.by.pProgram->token;
   65430     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
   65431     if( u.by.pFrame ) break;
   65432   }
   65433 
   65434   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
   65435     rc = SQLITE_ERROR;
   65436     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
   65437     break;
   65438   }
   65439 
   65440   /* Register u.by.pRt is used to store the memory required to save the state
   65441   ** of the current program, and the memory required at runtime to execute
   65442   ** the trigger program. If this trigger has been fired before, then u.by.pRt
   65443   ** is already allocated. Otherwise, it must be initialized.  */
   65444   if( (u.by.pRt->flags&MEM_Frame)==0 ){
   65445     /* SubProgram.nMem is set to the number of memory cells used by the
   65446     ** program stored in SubProgram.aOp. As well as these, one memory
   65447     ** cell is required for each cursor used by the program. Set local
   65448     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
   65449     */
   65450     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
   65451     u.by.nByte = ROUND8(sizeof(VdbeFrame))
   65452               + u.by.nMem * sizeof(Mem)
   65453               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
   65454     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
   65455     if( !u.by.pFrame ){
   65456       goto no_mem;
   65457     }
   65458     sqlite3VdbeMemRelease(u.by.pRt);
   65459     u.by.pRt->flags = MEM_Frame;
   65460     u.by.pRt->u.pFrame = u.by.pFrame;
   65461 
   65462     u.by.pFrame->v = p;
   65463     u.by.pFrame->nChildMem = u.by.nMem;
   65464     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
   65465     u.by.pFrame->pc = pc;
   65466     u.by.pFrame->aMem = p->aMem;
   65467     u.by.pFrame->nMem = p->nMem;
   65468     u.by.pFrame->apCsr = p->apCsr;
   65469     u.by.pFrame->nCursor = p->nCursor;
   65470     u.by.pFrame->aOp = p->aOp;
   65471     u.by.pFrame->nOp = p->nOp;
   65472     u.by.pFrame->token = u.by.pProgram->token;
   65473 
   65474     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
   65475     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
   65476       u.by.pMem->flags = MEM_Null;
   65477       u.by.pMem->db = db;
   65478     }
   65479   }else{
   65480     u.by.pFrame = u.by.pRt->u.pFrame;
   65481     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
   65482     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
   65483     assert( pc==u.by.pFrame->pc );
   65484   }
   65485 
   65486   p->nFrame++;
   65487   u.by.pFrame->pParent = p->pFrame;
   65488   u.by.pFrame->lastRowid = db->lastRowid;
   65489   u.by.pFrame->nChange = p->nChange;
   65490   p->nChange = 0;
   65491   p->pFrame = u.by.pFrame;
   65492   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
   65493   p->nMem = u.by.pFrame->nChildMem;
   65494   p->nCursor = (u16)u.by.pFrame->nChildCsr;
   65495   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
   65496   p->aOp = aOp = u.by.pProgram->aOp;
   65497   p->nOp = u.by.pProgram->nOp;
   65498   pc = -1;
   65499 
   65500   break;
   65501 }
   65502 
   65503 /* Opcode: Param P1 P2 * * *
   65504 **
   65505 ** This opcode is only ever present in sub-programs called via the
   65506 ** OP_Program instruction. Copy a value currently stored in a memory
   65507 ** cell of the calling (parent) frame to cell P2 in the current frames
   65508 ** address space. This is used by trigger programs to access the new.*
   65509 ** and old.* values.
   65510 **
   65511 ** The address of the cell in the parent frame is determined by adding
   65512 ** the value of the P1 argument to the value of the P1 argument to the
   65513 ** calling OP_Program instruction.
   65514 */
   65515 case OP_Param: {           /* out2-prerelease */
   65516 #if 0  /* local variables moved into u.bz */
   65517   VdbeFrame *pFrame;
   65518   Mem *pIn;
   65519 #endif /* local variables moved into u.bz */
   65520   u.bz.pFrame = p->pFrame;
   65521   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
   65522   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
   65523   break;
   65524 }
   65525 
   65526 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
   65527 
   65528 #ifndef SQLITE_OMIT_FOREIGN_KEY
   65529 /* Opcode: FkCounter P1 P2 * * *
   65530 **
   65531 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
   65532 ** If P1 is non-zero, the database constraint counter is incremented
   65533 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
   65534 ** statement counter is incremented (immediate foreign key constraints).
   65535 */
   65536 case OP_FkCounter: {
   65537   if( pOp->p1 ){
   65538     db->nDeferredCons += pOp->p2;
   65539   }else{
   65540     p->nFkConstraint += pOp->p2;
   65541   }
   65542   break;
   65543 }
   65544 
   65545 /* Opcode: FkIfZero P1 P2 * * *
   65546 **
   65547 ** This opcode tests if a foreign key constraint-counter is currently zero.
   65548 ** If so, jump to instruction P2. Otherwise, fall through to the next
   65549 ** instruction.
   65550 **
   65551 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
   65552 ** is zero (the one that counts deferred constraint violations). If P1 is
   65553 ** zero, the jump is taken if the statement constraint-counter is zero
   65554 ** (immediate foreign key constraint violations).
   65555 */
   65556 case OP_FkIfZero: {         /* jump */
   65557   if( pOp->p1 ){
   65558     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
   65559   }else{
   65560     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
   65561   }
   65562   break;
   65563 }
   65564 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
   65565 
   65566 #ifndef SQLITE_OMIT_AUTOINCREMENT
   65567 /* Opcode: MemMax P1 P2 * * *
   65568 **
   65569 ** P1 is a register in the root frame of this VM (the root frame is
   65570 ** different from the current frame if this instruction is being executed
   65571 ** within a sub-program). Set the value of register P1 to the maximum of
   65572 ** its current value and the value in register P2.
   65573 **
   65574 ** This instruction throws an error if the memory cell is not initially
   65575 ** an integer.
   65576 */
   65577 case OP_MemMax: {        /* in2 */
   65578 #if 0  /* local variables moved into u.ca */
   65579   Mem *pIn1;
   65580   VdbeFrame *pFrame;
   65581 #endif /* local variables moved into u.ca */
   65582   if( p->pFrame ){
   65583     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
   65584     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
   65585   }else{
   65586     u.ca.pIn1 = &aMem[pOp->p1];
   65587   }
   65588   assert( memIsValid(u.ca.pIn1) );
   65589   sqlite3VdbeMemIntegerify(u.ca.pIn1);
   65590   pIn2 = &aMem[pOp->p2];
   65591   sqlite3VdbeMemIntegerify(pIn2);
   65592   if( u.ca.pIn1->u.i<pIn2->u.i){
   65593     u.ca.pIn1->u.i = pIn2->u.i;
   65594   }
   65595   break;
   65596 }
   65597 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   65598 
   65599 /* Opcode: IfPos P1 P2 * * *
   65600 **
   65601 ** If the value of register P1 is 1 or greater, jump to P2.
   65602 **
   65603 ** It is illegal to use this instruction on a register that does
   65604 ** not contain an integer.  An assertion fault will result if you try.
   65605 */
   65606 case OP_IfPos: {        /* jump, in1 */
   65607   pIn1 = &aMem[pOp->p1];
   65608   assert( pIn1->flags&MEM_Int );
   65609   if( pIn1->u.i>0 ){
   65610      pc = pOp->p2 - 1;
   65611   }
   65612   break;
   65613 }
   65614 
   65615 /* Opcode: IfNeg P1 P2 * * *
   65616 **
   65617 ** If the value of register P1 is less than zero, jump to P2.
   65618 **
   65619 ** It is illegal to use this instruction on a register that does
   65620 ** not contain an integer.  An assertion fault will result if you try.
   65621 */
   65622 case OP_IfNeg: {        /* jump, in1 */
   65623   pIn1 = &aMem[pOp->p1];
   65624   assert( pIn1->flags&MEM_Int );
   65625   if( pIn1->u.i<0 ){
   65626      pc = pOp->p2 - 1;
   65627   }
   65628   break;
   65629 }
   65630 
   65631 /* Opcode: IfZero P1 P2 P3 * *
   65632 **
   65633 ** The register P1 must contain an integer.  Add literal P3 to the
   65634 ** value in register P1.  If the result is exactly 0, jump to P2.
   65635 **
   65636 ** It is illegal to use this instruction on a register that does
   65637 ** not contain an integer.  An assertion fault will result if you try.
   65638 */
   65639 case OP_IfZero: {        /* jump, in1 */
   65640   pIn1 = &aMem[pOp->p1];
   65641   assert( pIn1->flags&MEM_Int );
   65642   pIn1->u.i += pOp->p3;
   65643   if( pIn1->u.i==0 ){
   65644      pc = pOp->p2 - 1;
   65645   }
   65646   break;
   65647 }
   65648 
   65649 /* Opcode: AggStep * P2 P3 P4 P5
   65650 **
   65651 ** Execute the step function for an aggregate.  The
   65652 ** function has P5 arguments.   P4 is a pointer to the FuncDef
   65653 ** structure that specifies the function.  Use register
   65654 ** P3 as the accumulator.
   65655 **
   65656 ** The P5 arguments are taken from register P2 and its
   65657 ** successors.
   65658 */
   65659 case OP_AggStep: {
   65660 #if 0  /* local variables moved into u.cb */
   65661   int n;
   65662   int i;
   65663   Mem *pMem;
   65664   Mem *pRec;
   65665   sqlite3_context ctx;
   65666   sqlite3_value **apVal;
   65667 #endif /* local variables moved into u.cb */
   65668 
   65669   u.cb.n = pOp->p5;
   65670   assert( u.cb.n>=0 );
   65671   u.cb.pRec = &aMem[pOp->p2];
   65672   u.cb.apVal = p->apArg;
   65673   assert( u.cb.apVal || u.cb.n==0 );
   65674   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
   65675     assert( memIsValid(u.cb.pRec) );
   65676     u.cb.apVal[u.cb.i] = u.cb.pRec;
   65677     memAboutToChange(p, u.cb.pRec);
   65678     sqlite3VdbeMemStoreType(u.cb.pRec);
   65679   }
   65680   u.cb.ctx.pFunc = pOp->p4.pFunc;
   65681   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   65682   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
   65683   u.cb.pMem->n++;
   65684   u.cb.ctx.s.flags = MEM_Null;
   65685   u.cb.ctx.s.z = 0;
   65686   u.cb.ctx.s.zMalloc = 0;
   65687   u.cb.ctx.s.xDel = 0;
   65688   u.cb.ctx.s.db = db;
   65689   u.cb.ctx.isError = 0;
   65690   u.cb.ctx.pColl = 0;
   65691   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   65692     assert( pOp>p->aOp );
   65693     assert( pOp[-1].p4type==P4_COLLSEQ );
   65694     assert( pOp[-1].opcode==OP_CollSeq );
   65695     u.cb.ctx.pColl = pOp[-1].p4.pColl;
   65696   }
   65697   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
   65698   if( u.cb.ctx.isError ){
   65699     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
   65700     rc = u.cb.ctx.isError;
   65701   }
   65702   sqlite3VdbeMemRelease(&u.cb.ctx.s);
   65703   break;
   65704 }
   65705 
   65706 /* Opcode: AggFinal P1 P2 * P4 *
   65707 **
   65708 ** Execute the finalizer function for an aggregate.  P1 is
   65709 ** the memory location that is the accumulator for the aggregate.
   65710 **
   65711 ** P2 is the number of arguments that the step function takes and
   65712 ** P4 is a pointer to the FuncDef for this function.  The P2
   65713 ** argument is not used by this opcode.  It is only there to disambiguate
   65714 ** functions that can take varying numbers of arguments.  The
   65715 ** P4 argument is only needed for the degenerate case where
   65716 ** the step function was not previously called.
   65717 */
   65718 case OP_AggFinal: {
   65719 #if 0  /* local variables moved into u.cc */
   65720   Mem *pMem;
   65721 #endif /* local variables moved into u.cc */
   65722   assert( pOp->p1>0 && pOp->p1<=p->nMem );
   65723   u.cc.pMem = &aMem[pOp->p1];
   65724   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
   65725   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
   65726   if( rc ){
   65727     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
   65728   }
   65729   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
   65730   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
   65731   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
   65732     goto too_big;
   65733   }
   65734   break;
   65735 }
   65736 
   65737 #ifndef SQLITE_OMIT_WAL
   65738 /* Opcode: Checkpoint P1 * * * *
   65739 **
   65740 ** Checkpoint database P1. This is a no-op if P1 is not currently in
   65741 ** WAL mode.
   65742 */
   65743 case OP_Checkpoint: {
   65744   rc = sqlite3Checkpoint(db, pOp->p1);
   65745   break;
   65746 };
   65747 #endif
   65748 
   65749 #ifndef SQLITE_OMIT_PRAGMA
   65750 /* Opcode: JournalMode P1 P2 P3 * P5
   65751 **
   65752 ** Change the journal mode of database P1 to P3. P3 must be one of the
   65753 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
   65754 ** modes (delete, truncate, persist, off and memory), this is a simple
   65755 ** operation. No IO is required.
   65756 **
   65757 ** If changing into or out of WAL mode the procedure is more complicated.
   65758 **
   65759 ** Write a string containing the final journal-mode to register P2.
   65760 */
   65761 case OP_JournalMode: {    /* out2-prerelease */
   65762 #if 0  /* local variables moved into u.cd */
   65763   Btree *pBt;                     /* Btree to change journal mode of */
   65764   Pager *pPager;                  /* Pager associated with pBt */
   65765   int eNew;                       /* New journal mode */
   65766   int eOld;                       /* The old journal mode */
   65767   const char *zFilename;          /* Name of database file for pPager */
   65768 #endif /* local variables moved into u.cd */
   65769 
   65770   u.cd.eNew = pOp->p3;
   65771   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
   65772        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
   65773        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
   65774        || u.cd.eNew==PAGER_JOURNALMODE_OFF
   65775        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
   65776        || u.cd.eNew==PAGER_JOURNALMODE_WAL
   65777        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
   65778   );
   65779   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   65780 
   65781   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
   65782   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
   65783   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
   65784   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
   65785   ** is not called when the statement is prepared because it requires the
   65786   ** iDb index of the database as a parameter, and the database has not
   65787   ** yet been attached so that index is unavailable.  We have to wait
   65788   ** until runtime (now) to get the mutex on the newly attached database.
   65789   ** No other mutexes are required by the ATTACH command so this is safe
   65790   ** to do.
   65791   */
   65792   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
   65793   if( p->aMutex.nMutex==0 ){
   65794     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
   65795     ** database. */
   65796     sqlite3VdbeUsesBtree(p, pOp->p1);
   65797     sqlite3VdbeMutexArrayEnter(p);
   65798   }
   65799 
   65800   u.cd.pBt = db->aDb[pOp->p1].pBt;
   65801   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
   65802   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
   65803   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
   65804   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
   65805 
   65806 #ifndef SQLITE_OMIT_WAL
   65807   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
   65808 
   65809   /* Do not allow a transition to journal_mode=WAL for a database
   65810   ** in temporary storage or if the VFS does not support shared memory
   65811   */
   65812   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
   65813    && (u.cd.zFilename[0]==0                         /* Temp file */
   65814        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
   65815   ){
   65816     u.cd.eNew = u.cd.eOld;
   65817   }
   65818 
   65819   if( (u.cd.eNew!=u.cd.eOld)
   65820    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
   65821   ){
   65822     if( !db->autoCommit || db->activeVdbeCnt>1 ){
   65823       rc = SQLITE_ERROR;
   65824       sqlite3SetString(&p->zErrMsg, db,
   65825           "cannot change %s wal mode from within a transaction",
   65826           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
   65827       );
   65828       break;
   65829     }else{
   65830 
   65831       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
   65832         /* If leaving WAL mode, close the log file. If successful, the call
   65833         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
   65834         ** file. An EXCLUSIVE lock may still be held on the database file
   65835         ** after a successful return.
   65836         */
   65837         rc = sqlite3PagerCloseWal(u.cd.pPager);
   65838         if( rc==SQLITE_OK ){
   65839           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
   65840         }
   65841       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
   65842         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
   65843         ** as an intermediate */
   65844         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
   65845       }
   65846 
   65847       /* Open a transaction on the database file. Regardless of the journal
   65848       ** mode, this transaction always uses a rollback journal.
   65849       */
   65850       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
   65851       if( rc==SQLITE_OK ){
   65852         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
   65853       }
   65854     }
   65855   }
   65856 #endif /* ifndef SQLITE_OMIT_WAL */
   65857 
   65858   if( rc ){
   65859     u.cd.eNew = u.cd.eOld;
   65860   }
   65861   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
   65862 
   65863   pOut = &aMem[pOp->p2];
   65864   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
   65865   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
   65866   pOut->n = sqlite3Strlen30(pOut->z);
   65867   pOut->enc = SQLITE_UTF8;
   65868   sqlite3VdbeChangeEncoding(pOut, encoding);
   65869   break;
   65870 };
   65871 #endif /* SQLITE_OMIT_PRAGMA */
   65872 
   65873 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   65874 /* Opcode: Vacuum * * * * *
   65875 **
   65876 ** Vacuum the entire database.  This opcode will cause other virtual
   65877 ** machines to be created and run.  It may not be called from within
   65878 ** a transaction.
   65879 */
   65880 case OP_Vacuum: {
   65881   rc = sqlite3RunVacuum(&p->zErrMsg, db);
   65882   break;
   65883 }
   65884 #endif
   65885 
   65886 #if !defined(SQLITE_OMIT_AUTOVACUUM)
   65887 /* Opcode: IncrVacuum P1 P2 * * *
   65888 **
   65889 ** Perform a single step of the incremental vacuum procedure on
   65890 ** the P1 database. If the vacuum has finished, jump to instruction
   65891 ** P2. Otherwise, fall through to the next instruction.
   65892 */
   65893 case OP_IncrVacuum: {        /* jump */
   65894 #if 0  /* local variables moved into u.ce */
   65895   Btree *pBt;
   65896 #endif /* local variables moved into u.ce */
   65897 
   65898   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   65899   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
   65900   u.ce.pBt = db->aDb[pOp->p1].pBt;
   65901   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
   65902   if( rc==SQLITE_DONE ){
   65903     pc = pOp->p2 - 1;
   65904     rc = SQLITE_OK;
   65905   }
   65906   break;
   65907 }
   65908 #endif
   65909 
   65910 /* Opcode: Expire P1 * * * *
   65911 **
   65912 ** Cause precompiled statements to become expired. An expired statement
   65913 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
   65914 ** (via sqlite3_step()).
   65915 **
   65916 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
   65917 ** then only the currently executing statement is affected.
   65918 */
   65919 case OP_Expire: {
   65920   if( !pOp->p1 ){
   65921     sqlite3ExpirePreparedStatements(db);
   65922   }else{
   65923     p->expired = 1;
   65924   }
   65925   break;
   65926 }
   65927 
   65928 #ifndef SQLITE_OMIT_SHARED_CACHE
   65929 /* Opcode: TableLock P1 P2 P3 P4 *
   65930 **
   65931 ** Obtain a lock on a particular table. This instruction is only used when
   65932 ** the shared-cache feature is enabled.
   65933 **
   65934 ** P1 is the index of the database in sqlite3.aDb[] of the database
   65935 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
   65936 ** a write lock if P3==1.
   65937 **
   65938 ** P2 contains the root-page of the table to lock.
   65939 **
   65940 ** P4 contains a pointer to the name of the table being locked. This is only
   65941 ** used to generate an error message if the lock cannot be obtained.
   65942 */
   65943 case OP_TableLock: {
   65944   u8 isWriteLock = (u8)pOp->p3;
   65945   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
   65946     int p1 = pOp->p1;
   65947     assert( p1>=0 && p1<db->nDb );
   65948     assert( (p->btreeMask & (1<<p1))!=0 );
   65949     assert( isWriteLock==0 || isWriteLock==1 );
   65950     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
   65951     if( (rc&0xFF)==SQLITE_LOCKED ){
   65952       const char *z = pOp->p4.z;
   65953       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
   65954     }
   65955   }
   65956   break;
   65957 }
   65958 #endif /* SQLITE_OMIT_SHARED_CACHE */
   65959 
   65960 #ifndef SQLITE_OMIT_VIRTUALTABLE
   65961 /* Opcode: VBegin * * * P4 *
   65962 **
   65963 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
   65964 ** xBegin method for that table.
   65965 **
   65966 ** Also, whether or not P4 is set, check that this is not being called from
   65967 ** within a callback to a virtual table xSync() method. If it is, the error
   65968 ** code will be set to SQLITE_LOCKED.
   65969 */
   65970 case OP_VBegin: {
   65971 #if 0  /* local variables moved into u.cf */
   65972   VTable *pVTab;
   65973 #endif /* local variables moved into u.cf */
   65974   u.cf.pVTab = pOp->p4.pVtab;
   65975   rc = sqlite3VtabBegin(db, u.cf.pVTab);
   65976   if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
   65977   break;
   65978 }
   65979 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   65980 
   65981 #ifndef SQLITE_OMIT_VIRTUALTABLE
   65982 /* Opcode: VCreate P1 * * P4 *
   65983 **
   65984 ** P4 is the name of a virtual table in database P1. Call the xCreate method
   65985 ** for that table.
   65986 */
   65987 case OP_VCreate: {
   65988   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
   65989   break;
   65990 }
   65991 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   65992 
   65993 #ifndef SQLITE_OMIT_VIRTUALTABLE
   65994 /* Opcode: VDestroy P1 * * P4 *
   65995 **
   65996 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
   65997 ** of that table.
   65998 */
   65999 case OP_VDestroy: {
   66000   p->inVtabMethod = 2;
   66001   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
   66002   p->inVtabMethod = 0;
   66003   break;
   66004 }
   66005 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66006 
   66007 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66008 /* Opcode: VOpen P1 * * P4 *
   66009 **
   66010 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   66011 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
   66012 ** table and stores that cursor in P1.
   66013 */
   66014 case OP_VOpen: {
   66015 #if 0  /* local variables moved into u.cg */
   66016   VdbeCursor *pCur;
   66017   sqlite3_vtab_cursor *pVtabCursor;
   66018   sqlite3_vtab *pVtab;
   66019   sqlite3_module *pModule;
   66020 #endif /* local variables moved into u.cg */
   66021 
   66022   u.cg.pCur = 0;
   66023   u.cg.pVtabCursor = 0;
   66024   u.cg.pVtab = pOp->p4.pVtab->pVtab;
   66025   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
   66026   assert(u.cg.pVtab && u.cg.pModule);
   66027   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
   66028   importVtabErrMsg(p, u.cg.pVtab);
   66029   if( SQLITE_OK==rc ){
   66030     /* Initialize sqlite3_vtab_cursor base class */
   66031     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
   66032 
   66033     /* Initialise vdbe cursor object */
   66034     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
   66035     if( u.cg.pCur ){
   66036       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
   66037       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
   66038     }else{
   66039       db->mallocFailed = 1;
   66040       u.cg.pModule->xClose(u.cg.pVtabCursor);
   66041     }
   66042   }
   66043   break;
   66044 }
   66045 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66046 
   66047 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66048 /* Opcode: VFilter P1 P2 P3 P4 *
   66049 **
   66050 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
   66051 ** the filtered result set is empty.
   66052 **
   66053 ** P4 is either NULL or a string that was generated by the xBestIndex
   66054 ** method of the module.  The interpretation of the P4 string is left
   66055 ** to the module implementation.
   66056 **
   66057 ** This opcode invokes the xFilter method on the virtual table specified
   66058 ** by P1.  The integer query plan parameter to xFilter is stored in register
   66059 ** P3. Register P3+1 stores the argc parameter to be passed to the
   66060 ** xFilter method. Registers P3+2..P3+1+argc are the argc
   66061 ** additional parameters which are passed to
   66062 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
   66063 **
   66064 ** A jump is made to P2 if the result set after filtering would be empty.
   66065 */
   66066 case OP_VFilter: {   /* jump */
   66067 #if 0  /* local variables moved into u.ch */
   66068   int nArg;
   66069   int iQuery;
   66070   const sqlite3_module *pModule;
   66071   Mem *pQuery;
   66072   Mem *pArgc;
   66073   sqlite3_vtab_cursor *pVtabCursor;
   66074   sqlite3_vtab *pVtab;
   66075   VdbeCursor *pCur;
   66076   int res;
   66077   int i;
   66078   Mem **apArg;
   66079 #endif /* local variables moved into u.ch */
   66080 
   66081   u.ch.pQuery = &aMem[pOp->p3];
   66082   u.ch.pArgc = &u.ch.pQuery[1];
   66083   u.ch.pCur = p->apCsr[pOp->p1];
   66084   assert( memIsValid(u.ch.pQuery) );
   66085   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
   66086   assert( u.ch.pCur->pVtabCursor );
   66087   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
   66088   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
   66089   u.ch.pModule = u.ch.pVtab->pModule;
   66090 
   66091   /* Grab the index number and argc parameters */
   66092   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
   66093   u.ch.nArg = (int)u.ch.pArgc->u.i;
   66094   u.ch.iQuery = (int)u.ch.pQuery->u.i;
   66095 
   66096   /* Invoke the xFilter method */
   66097   {
   66098     u.ch.res = 0;
   66099     u.ch.apArg = p->apArg;
   66100     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
   66101       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
   66102       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
   66103     }
   66104 
   66105     p->inVtabMethod = 1;
   66106     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
   66107     p->inVtabMethod = 0;
   66108     importVtabErrMsg(p, u.ch.pVtab);
   66109     if( rc==SQLITE_OK ){
   66110       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
   66111     }
   66112 
   66113     if( u.ch.res ){
   66114       pc = pOp->p2 - 1;
   66115     }
   66116   }
   66117   u.ch.pCur->nullRow = 0;
   66118 
   66119   break;
   66120 }
   66121 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66122 
   66123 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66124 /* Opcode: VColumn P1 P2 P3 * *
   66125 **
   66126 ** Store the value of the P2-th column of
   66127 ** the row of the virtual-table that the
   66128 ** P1 cursor is pointing to into register P3.
   66129 */
   66130 case OP_VColumn: {
   66131 #if 0  /* local variables moved into u.ci */
   66132   sqlite3_vtab *pVtab;
   66133   const sqlite3_module *pModule;
   66134   Mem *pDest;
   66135   sqlite3_context sContext;
   66136 #endif /* local variables moved into u.ci */
   66137 
   66138   VdbeCursor *pCur = p->apCsr[pOp->p1];
   66139   assert( pCur->pVtabCursor );
   66140   assert( pOp->p3>0 && pOp->p3<=p->nMem );
   66141   u.ci.pDest = &aMem[pOp->p3];
   66142   memAboutToChange(p, u.ci.pDest);
   66143   if( pCur->nullRow ){
   66144     sqlite3VdbeMemSetNull(u.ci.pDest);
   66145     break;
   66146   }
   66147   u.ci.pVtab = pCur->pVtabCursor->pVtab;
   66148   u.ci.pModule = u.ci.pVtab->pModule;
   66149   assert( u.ci.pModule->xColumn );
   66150   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
   66151 
   66152   /* The output cell may already have a buffer allocated. Move
   66153   ** the current contents to u.ci.sContext.s so in case the user-function
   66154   ** can use the already allocated buffer instead of allocating a
   66155   ** new one.
   66156   */
   66157   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
   66158   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
   66159 
   66160   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
   66161   importVtabErrMsg(p, u.ci.pVtab);
   66162   if( u.ci.sContext.isError ){
   66163     rc = u.ci.sContext.isError;
   66164   }
   66165 
   66166   /* Copy the result of the function to the P3 register. We
   66167   ** do this regardless of whether or not an error occurred to ensure any
   66168   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
   66169   */
   66170   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
   66171   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
   66172   REGISTER_TRACE(pOp->p3, u.ci.pDest);
   66173   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
   66174 
   66175   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
   66176     goto too_big;
   66177   }
   66178   break;
   66179 }
   66180 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66181 
   66182 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66183 /* Opcode: VNext P1 P2 * * *
   66184 **
   66185 ** Advance virtual table P1 to the next row in its result set and
   66186 ** jump to instruction P2.  Or, if the virtual table has reached
   66187 ** the end of its result set, then fall through to the next instruction.
   66188 */
   66189 case OP_VNext: {   /* jump */
   66190 #if 0  /* local variables moved into u.cj */
   66191   sqlite3_vtab *pVtab;
   66192   const sqlite3_module *pModule;
   66193   int res;
   66194   VdbeCursor *pCur;
   66195 #endif /* local variables moved into u.cj */
   66196 
   66197   u.cj.res = 0;
   66198   u.cj.pCur = p->apCsr[pOp->p1];
   66199   assert( u.cj.pCur->pVtabCursor );
   66200   if( u.cj.pCur->nullRow ){
   66201     break;
   66202   }
   66203   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
   66204   u.cj.pModule = u.cj.pVtab->pModule;
   66205   assert( u.cj.pModule->xNext );
   66206 
   66207   /* Invoke the xNext() method of the module. There is no way for the
   66208   ** underlying implementation to return an error if one occurs during
   66209   ** xNext(). Instead, if an error occurs, true is returned (indicating that
   66210   ** data is available) and the error code returned when xColumn or
   66211   ** some other method is next invoked on the save virtual table cursor.
   66212   */
   66213   p->inVtabMethod = 1;
   66214   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
   66215   p->inVtabMethod = 0;
   66216   importVtabErrMsg(p, u.cj.pVtab);
   66217   if( rc==SQLITE_OK ){
   66218     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
   66219   }
   66220 
   66221   if( !u.cj.res ){
   66222     /* If there is data, jump to P2 */
   66223     pc = pOp->p2 - 1;
   66224   }
   66225   break;
   66226 }
   66227 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66228 
   66229 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66230 /* Opcode: VRename P1 * * P4 *
   66231 **
   66232 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   66233 ** This opcode invokes the corresponding xRename method. The value
   66234 ** in register P1 is passed as the zName argument to the xRename method.
   66235 */
   66236 case OP_VRename: {
   66237 #if 0  /* local variables moved into u.ck */
   66238   sqlite3_vtab *pVtab;
   66239   Mem *pName;
   66240 #endif /* local variables moved into u.ck */
   66241 
   66242   u.ck.pVtab = pOp->p4.pVtab->pVtab;
   66243   u.ck.pName = &aMem[pOp->p1];
   66244   assert( u.ck.pVtab->pModule->xRename );
   66245   assert( memIsValid(u.ck.pName) );
   66246   REGISTER_TRACE(pOp->p1, u.ck.pName);
   66247   assert( u.ck.pName->flags & MEM_Str );
   66248   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
   66249   importVtabErrMsg(p, u.ck.pVtab);
   66250   p->expired = 0;
   66251 
   66252   break;
   66253 }
   66254 #endif
   66255 
   66256 #ifndef SQLITE_OMIT_VIRTUALTABLE
   66257 /* Opcode: VUpdate P1 P2 P3 P4 *
   66258 **
   66259 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
   66260 ** This opcode invokes the corresponding xUpdate method. P2 values
   66261 ** are contiguous memory cells starting at P3 to pass to the xUpdate
   66262 ** invocation. The value in register (P3+P2-1) corresponds to the
   66263 ** p2th element of the argv array passed to xUpdate.
   66264 **
   66265 ** The xUpdate method will do a DELETE or an INSERT or both.
   66266 ** The argv[0] element (which corresponds to memory cell P3)
   66267 ** is the rowid of a row to delete.  If argv[0] is NULL then no
   66268 ** deletion occurs.  The argv[1] element is the rowid of the new
   66269 ** row.  This can be NULL to have the virtual table select the new
   66270 ** rowid for itself.  The subsequent elements in the array are
   66271 ** the values of columns in the new row.
   66272 **
   66273 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
   66274 ** a row to delete.
   66275 **
   66276 ** P1 is a boolean flag. If it is set to true and the xUpdate call
   66277 ** is successful, then the value returned by sqlite3_last_insert_rowid()
   66278 ** is set to the value of the rowid for the row just inserted.
   66279 */
   66280 case OP_VUpdate: {
   66281 #if 0  /* local variables moved into u.cl */
   66282   sqlite3_vtab *pVtab;
   66283   sqlite3_module *pModule;
   66284   int nArg;
   66285   int i;
   66286   sqlite_int64 rowid;
   66287   Mem **apArg;
   66288   Mem *pX;
   66289 #endif /* local variables moved into u.cl */
   66290 
   66291   u.cl.pVtab = pOp->p4.pVtab->pVtab;
   66292   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
   66293   u.cl.nArg = pOp->p2;
   66294   assert( pOp->p4type==P4_VTAB );
   66295   if( ALWAYS(u.cl.pModule->xUpdate) ){
   66296     u.cl.apArg = p->apArg;
   66297     u.cl.pX = &aMem[pOp->p3];
   66298     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
   66299       assert( memIsValid(u.cl.pX) );
   66300       memAboutToChange(p, u.cl.pX);
   66301       sqlite3VdbeMemStoreType(u.cl.pX);
   66302       u.cl.apArg[u.cl.i] = u.cl.pX;
   66303       u.cl.pX++;
   66304     }
   66305     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
   66306     importVtabErrMsg(p, u.cl.pVtab);
   66307     if( rc==SQLITE_OK && pOp->p1 ){
   66308       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
   66309       db->lastRowid = u.cl.rowid;
   66310     }
   66311     p->nChange++;
   66312   }
   66313   break;
   66314 }
   66315 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   66316 
   66317 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   66318 /* Opcode: Pagecount P1 P2 * * *
   66319 **
   66320 ** Write the current number of pages in database P1 to memory cell P2.
   66321 */
   66322 case OP_Pagecount: {            /* out2-prerelease */
   66323   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
   66324   break;
   66325 }
   66326 #endif
   66327 
   66328 
   66329 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
   66330 /* Opcode: MaxPgcnt P1 P2 P3 * *
   66331 **
   66332 ** Try to set the maximum page count for database P1 to the value in P3.
   66333 ** Do not let the maximum page count fall below the current page count and
   66334 ** do not change the maximum page count value if P3==0.
   66335 **
   66336 ** Store the maximum page count after the change in register P2.
   66337 */
   66338 case OP_MaxPgcnt: {            /* out2-prerelease */
   66339   unsigned int newMax;
   66340   Btree *pBt;
   66341 
   66342   pBt = db->aDb[pOp->p1].pBt;
   66343   newMax = 0;
   66344   if( pOp->p3 ){
   66345     newMax = sqlite3BtreeLastPage(pBt);
   66346     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
   66347   }
   66348   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
   66349   break;
   66350 }
   66351 #endif
   66352 
   66353 
   66354 #ifndef SQLITE_OMIT_TRACE
   66355 /* Opcode: Trace * * * P4 *
   66356 **
   66357 ** If tracing is enabled (by the sqlite3_trace()) interface, then
   66358 ** the UTF-8 string contained in P4 is emitted on the trace callback.
   66359 */
   66360 case OP_Trace: {
   66361 #if 0  /* local variables moved into u.cm */
   66362   char *zTrace;
   66363 #endif /* local variables moved into u.cm */
   66364 
   66365   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
   66366   if( u.cm.zTrace ){
   66367     if( db->xTrace ){
   66368       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
   66369       db->xTrace(db->pTraceArg, z);
   66370       sqlite3DbFree(db, z);
   66371     }
   66372 #ifdef SQLITE_DEBUG
   66373     if( (db->flags & SQLITE_SqlTrace)!=0 ){
   66374       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
   66375     }
   66376 #endif /* SQLITE_DEBUG */
   66377   }
   66378   break;
   66379 }
   66380 #endif
   66381 
   66382 
   66383 /* Opcode: Noop * * * * *
   66384 **
   66385 ** Do nothing.  This instruction is often useful as a jump
   66386 ** destination.
   66387 */
   66388 /*
   66389 ** The magic Explain opcode are only inserted when explain==2 (which
   66390 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
   66391 ** This opcode records information from the optimizer.  It is the
   66392 ** the same as a no-op.  This opcodesnever appears in a real VM program.
   66393 */
   66394 default: {          /* This is really OP_Noop and OP_Explain */
   66395   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
   66396   break;
   66397 }
   66398 
   66399 /*****************************************************************************
   66400 ** The cases of the switch statement above this line should all be indented
   66401 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
   66402 ** readability.  From this point on down, the normal indentation rules are
   66403 ** restored.
   66404 *****************************************************************************/
   66405     }
   66406 
   66407 #ifdef VDBE_PROFILE
   66408     {
   66409       u64 elapsed = sqlite3Hwtime() - start;
   66410       pOp->cycles += elapsed;
   66411       pOp->cnt++;
   66412 #if 0
   66413         fprintf(stdout, "%10llu ", elapsed);
   66414         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
   66415 #endif
   66416     }
   66417 #endif
   66418 
   66419     /* The following code adds nothing to the actual functionality
   66420     ** of the program.  It is only here for testing and debugging.
   66421     ** On the other hand, it does burn CPU cycles every time through
   66422     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
   66423     */
   66424 #ifndef NDEBUG
   66425     assert( pc>=-1 && pc<p->nOp );
   66426 
   66427 #ifdef SQLITE_DEBUG
   66428     if( p->trace ){
   66429       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
   66430       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
   66431         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
   66432       }
   66433       if( pOp->opflags & OPFLG_OUT3 ){
   66434         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
   66435       }
   66436     }
   66437 #endif  /* SQLITE_DEBUG */
   66438 #endif  /* NDEBUG */
   66439   }  /* The end of the for(;;) loop the loops through opcodes */
   66440 
   66441   /* If we reach this point, it means that execution is finished with
   66442   ** an error of some kind.
   66443   */
   66444 vdbe_error_halt:
   66445   assert( rc );
   66446   p->rc = rc;
   66447   testcase( sqlite3GlobalConfig.xLog!=0 );
   66448   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
   66449                    pc, p->zSql, p->zErrMsg);
   66450   sqlite3VdbeHalt(p);
   66451   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
   66452   rc = SQLITE_ERROR;
   66453   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
   66454 
   66455   /* This is the only way out of this procedure.  We have to
   66456   ** release the mutexes on btrees that were acquired at the
   66457   ** top. */
   66458 vdbe_return:
   66459   sqlite3BtreeMutexArrayLeave(&p->aMutex);
   66460   return rc;
   66461 
   66462   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
   66463   ** is encountered.
   66464   */
   66465 too_big:
   66466   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
   66467   rc = SQLITE_TOOBIG;
   66468   goto vdbe_error_halt;
   66469 
   66470   /* Jump to here if a malloc() fails.
   66471   */
   66472 no_mem:
   66473   db->mallocFailed = 1;
   66474   sqlite3SetString(&p->zErrMsg, db, "out of memory");
   66475   rc = SQLITE_NOMEM;
   66476   goto vdbe_error_halt;
   66477 
   66478   /* Jump to here for any other kind of fatal error.  The "rc" variable
   66479   ** should hold the error number.
   66480   */
   66481 abort_due_to_error:
   66482   assert( p->zErrMsg==0 );
   66483   if( db->mallocFailed ) rc = SQLITE_NOMEM;
   66484   if( rc!=SQLITE_IOERR_NOMEM ){
   66485     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   66486   }
   66487   goto vdbe_error_halt;
   66488 
   66489   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
   66490   ** flag.
   66491   */
   66492 abort_due_to_interrupt:
   66493   assert( db->u1.isInterrupted );
   66494   rc = SQLITE_INTERRUPT;
   66495   p->rc = rc;
   66496   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
   66497   goto vdbe_error_halt;
   66498 }
   66499 
   66500 /************** End of vdbe.c ************************************************/
   66501 /************** Begin file vdbeblob.c ****************************************/
   66502 /*
   66503 ** 2007 May 1
   66504 **
   66505 ** The author disclaims copyright to this source code.  In place of
   66506 ** a legal notice, here is a blessing:
   66507 **
   66508 **    May you do good and not evil.
   66509 **    May you find forgiveness for yourself and forgive others.
   66510 **    May you share freely, never taking more than you give.
   66511 **
   66512 *************************************************************************
   66513 **
   66514 ** This file contains code used to implement incremental BLOB I/O.
   66515 */
   66516 
   66517 
   66518 #ifndef SQLITE_OMIT_INCRBLOB
   66519 
   66520 /*
   66521 ** Valid sqlite3_blob* handles point to Incrblob structures.
   66522 */
   66523 typedef struct Incrblob Incrblob;
   66524 struct Incrblob {
   66525   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
   66526   int nByte;              /* Size of open blob, in bytes */
   66527   int iOffset;            /* Byte offset of blob in cursor data */
   66528   int iCol;               /* Table column this handle is open on */
   66529   BtCursor *pCsr;         /* Cursor pointing at blob row */
   66530   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
   66531   sqlite3 *db;            /* The associated database */
   66532 };
   66533 
   66534 
   66535 /*
   66536 ** This function is used by both blob_open() and blob_reopen(). It seeks
   66537 ** the b-tree cursor associated with blob handle p to point to row iRow.
   66538 ** If successful, SQLITE_OK is returned and subsequent calls to
   66539 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
   66540 **
   66541 ** If an error occurs, or if the specified row does not exist or does not
   66542 ** contain a value of type TEXT or BLOB in the column nominated when the
   66543 ** blob handle was opened, then an error code is returned and *pzErr may
   66544 ** be set to point to a buffer containing an error message. It is the
   66545 ** responsibility of the caller to free the error message buffer using
   66546 ** sqlite3DbFree().
   66547 **
   66548 ** If an error does occur, then the b-tree cursor is closed. All subsequent
   66549 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
   66550 ** immediately return SQLITE_ABORT.
   66551 */
   66552 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   66553   int rc;                         /* Error code */
   66554   char *zErr = 0;                 /* Error message */
   66555   Vdbe *v = (Vdbe *)p->pStmt;
   66556 
   66557   /* Set the value of the SQL statements only variable to integer iRow.
   66558   ** This is done directly instead of using sqlite3_bind_int64() to avoid
   66559   ** triggering asserts related to mutexes.
   66560   */
   66561   assert( v->aVar[0].flags&MEM_Int );
   66562   v->aVar[0].u.i = iRow;
   66563 
   66564   rc = sqlite3_step(p->pStmt);
   66565   if( rc==SQLITE_ROW ){
   66566     u32 type = v->apCsr[0]->aType[p->iCol];
   66567     if( type<12 ){
   66568       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
   66569           type==0?"null": type==7?"real": "integer"
   66570       );
   66571       rc = SQLITE_ERROR;
   66572       sqlite3_finalize(p->pStmt);
   66573       p->pStmt = 0;
   66574     }else{
   66575       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
   66576       p->nByte = sqlite3VdbeSerialTypeLen(type);
   66577       p->pCsr =  v->apCsr[0]->pCursor;
   66578       sqlite3BtreeEnterCursor(p->pCsr);
   66579       sqlite3BtreeCacheOverflow(p->pCsr);
   66580       sqlite3BtreeLeaveCursor(p->pCsr);
   66581     }
   66582   }
   66583 
   66584   if( rc==SQLITE_ROW ){
   66585     rc = SQLITE_OK;
   66586   }else if( p->pStmt ){
   66587     rc = sqlite3_finalize(p->pStmt);
   66588     p->pStmt = 0;
   66589     if( rc==SQLITE_OK ){
   66590       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
   66591       rc = SQLITE_ERROR;
   66592     }else{
   66593       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
   66594     }
   66595   }
   66596 
   66597   assert( rc!=SQLITE_OK || zErr==0 );
   66598   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
   66599 
   66600   *pzErr = zErr;
   66601   return rc;
   66602 }
   66603 
   66604 /*
   66605 ** Open a blob handle.
   66606 */
   66607 SQLITE_API int sqlite3_blob_open(
   66608   sqlite3* db,            /* The database connection */
   66609   const char *zDb,        /* The attached database containing the blob */
   66610   const char *zTable,     /* The table containing the blob */
   66611   const char *zColumn,    /* The column containing the blob */
   66612   sqlite_int64 iRow,      /* The row containing the glob */
   66613   int flags,              /* True -> read/write access, false -> read-only */
   66614   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
   66615 ){
   66616   int nAttempt = 0;
   66617   int iCol;               /* Index of zColumn in row-record */
   66618 
   66619   /* This VDBE program seeks a btree cursor to the identified
   66620   ** db/table/row entry. The reason for using a vdbe program instead
   66621   ** of writing code to use the b-tree layer directly is that the
   66622   ** vdbe program will take advantage of the various transaction,
   66623   ** locking and error handling infrastructure built into the vdbe.
   66624   **
   66625   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
   66626   ** Code external to the Vdbe then "borrows" the b-tree cursor and
   66627   ** uses it to implement the blob_read(), blob_write() and
   66628   ** blob_bytes() functions.
   66629   **
   66630   ** The sqlite3_blob_close() function finalizes the vdbe program,
   66631   ** which closes the b-tree cursor and (possibly) commits the
   66632   ** transaction.
   66633   */
   66634   static const VdbeOpList openBlob[] = {
   66635     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
   66636     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
   66637     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
   66638 
   66639     /* One of the following two instructions is replaced by an OP_Noop. */
   66640     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
   66641     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
   66642 
   66643     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
   66644     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
   66645     {OP_Column, 0, 0, 1},          /* 7  */
   66646     {OP_ResultRow, 1, 0, 0},       /* 8  */
   66647     {OP_Goto, 0, 5, 0},            /* 9  */
   66648     {OP_Close, 0, 0, 0},           /* 10 */
   66649     {OP_Halt, 0, 0, 0},            /* 11 */
   66650   };
   66651 
   66652   int rc = SQLITE_OK;
   66653   char *zErr = 0;
   66654   Table *pTab;
   66655   Parse *pParse = 0;
   66656   Incrblob *pBlob = 0;
   66657 
   66658   flags = !!flags;                /* flags = (flags ? 1 : 0); */
   66659   *ppBlob = 0;
   66660 
   66661   sqlite3_mutex_enter(db->mutex);
   66662 
   66663   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
   66664   if( !pBlob ) goto blob_open_out;
   66665   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
   66666   if( !pParse ) goto blob_open_out;
   66667 
   66668   do {
   66669     memset(pParse, 0, sizeof(Parse));
   66670     pParse->db = db;
   66671     sqlite3DbFree(db, zErr);
   66672     zErr = 0;
   66673 
   66674     sqlite3BtreeEnterAll(db);
   66675     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
   66676     if( pTab && IsVirtual(pTab) ){
   66677       pTab = 0;
   66678       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
   66679     }
   66680 #ifndef SQLITE_OMIT_VIEW
   66681     if( pTab && pTab->pSelect ){
   66682       pTab = 0;
   66683       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
   66684     }
   66685 #endif
   66686     if( !pTab ){
   66687       if( pParse->zErrMsg ){
   66688         sqlite3DbFree(db, zErr);
   66689         zErr = pParse->zErrMsg;
   66690         pParse->zErrMsg = 0;
   66691       }
   66692       rc = SQLITE_ERROR;
   66693       sqlite3BtreeLeaveAll(db);
   66694       goto blob_open_out;
   66695     }
   66696 
   66697     /* Now search pTab for the exact column. */
   66698     for(iCol=0; iCol<pTab->nCol; iCol++) {
   66699       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
   66700         break;
   66701       }
   66702     }
   66703     if( iCol==pTab->nCol ){
   66704       sqlite3DbFree(db, zErr);
   66705       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
   66706       rc = SQLITE_ERROR;
   66707       sqlite3BtreeLeaveAll(db);
   66708       goto blob_open_out;
   66709     }
   66710 
   66711     /* If the value is being opened for writing, check that the
   66712     ** column is not indexed, and that it is not part of a foreign key.
   66713     ** It is against the rules to open a column to which either of these
   66714     ** descriptions applies for writing.  */
   66715     if( flags ){
   66716       const char *zFault = 0;
   66717       Index *pIdx;
   66718 #ifndef SQLITE_OMIT_FOREIGN_KEY
   66719       if( db->flags&SQLITE_ForeignKeys ){
   66720         /* Check that the column is not part of an FK child key definition. It
   66721         ** is not necessary to check if it is part of a parent key, as parent
   66722         ** key columns must be indexed. The check below will pick up this
   66723         ** case.  */
   66724         FKey *pFKey;
   66725         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   66726           int j;
   66727           for(j=0; j<pFKey->nCol; j++){
   66728             if( pFKey->aCol[j].iFrom==iCol ){
   66729               zFault = "foreign key";
   66730             }
   66731           }
   66732         }
   66733       }
   66734 #endif
   66735       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   66736         int j;
   66737         for(j=0; j<pIdx->nColumn; j++){
   66738           if( pIdx->aiColumn[j]==iCol ){
   66739             zFault = "indexed";
   66740           }
   66741         }
   66742       }
   66743       if( zFault ){
   66744         sqlite3DbFree(db, zErr);
   66745         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
   66746         rc = SQLITE_ERROR;
   66747         sqlite3BtreeLeaveAll(db);
   66748         goto blob_open_out;
   66749       }
   66750     }
   66751 
   66752     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
   66753     assert( pBlob->pStmt || db->mallocFailed );
   66754     if( pBlob->pStmt ){
   66755       Vdbe *v = (Vdbe *)pBlob->pStmt;
   66756       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   66757 
   66758       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
   66759 
   66760 
   66761       /* Configure the OP_Transaction */
   66762       sqlite3VdbeChangeP1(v, 0, iDb);
   66763       sqlite3VdbeChangeP2(v, 0, flags);
   66764 
   66765       /* Configure the OP_VerifyCookie */
   66766       sqlite3VdbeChangeP1(v, 1, iDb);
   66767       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
   66768 
   66769       /* Make sure a mutex is held on the table to be accessed */
   66770       sqlite3VdbeUsesBtree(v, iDb);
   66771 
   66772       /* Configure the OP_TableLock instruction */
   66773 #ifdef SQLITE_OMIT_SHARED_CACHE
   66774       sqlite3VdbeChangeToNoop(v, 2, 1);
   66775 #else
   66776       sqlite3VdbeChangeP1(v, 2, iDb);
   66777       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
   66778       sqlite3VdbeChangeP3(v, 2, flags);
   66779       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
   66780 #endif
   66781 
   66782       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
   66783       ** parameter of the other to pTab->tnum.  */
   66784       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
   66785       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
   66786       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
   66787 
   66788       /* Configure the number of columns. Configure the cursor to
   66789       ** think that the table has one more column than it really
   66790       ** does. An OP_Column to retrieve this imaginary column will
   66791       ** always return an SQL NULL. This is useful because it means
   66792       ** we can invoke OP_Column to fill in the vdbe cursors type
   66793       ** and offset cache without causing any IO.
   66794       */
   66795       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
   66796       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
   66797       if( !db->mallocFailed ){
   66798         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
   66799       }
   66800     }
   66801 
   66802     pBlob->flags = flags;
   66803     pBlob->iCol = iCol;
   66804     pBlob->db = db;
   66805     sqlite3BtreeLeaveAll(db);
   66806     if( db->mallocFailed ){
   66807       goto blob_open_out;
   66808     }
   66809     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
   66810     rc = blobSeekToRow(pBlob, iRow, &zErr);
   66811   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
   66812 
   66813 blob_open_out:
   66814   if( rc==SQLITE_OK && db->mallocFailed==0 ){
   66815     *ppBlob = (sqlite3_blob *)pBlob;
   66816   }else{
   66817     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   66818     sqlite3DbFree(db, pBlob);
   66819   }
   66820   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   66821   sqlite3DbFree(db, zErr);
   66822   sqlite3StackFree(db, pParse);
   66823   rc = sqlite3ApiExit(db, rc);
   66824   sqlite3_mutex_leave(db->mutex);
   66825   return rc;
   66826 }
   66827 
   66828 /*
   66829 ** Close a blob handle that was previously created using
   66830 ** sqlite3_blob_open().
   66831 */
   66832 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
   66833   Incrblob *p = (Incrblob *)pBlob;
   66834   int rc;
   66835   sqlite3 *db;
   66836 
   66837   if( p ){
   66838     db = p->db;
   66839     sqlite3_mutex_enter(db->mutex);
   66840     rc = sqlite3_finalize(p->pStmt);
   66841     sqlite3DbFree(db, p);
   66842     sqlite3_mutex_leave(db->mutex);
   66843   }else{
   66844     rc = SQLITE_OK;
   66845   }
   66846   return rc;
   66847 }
   66848 
   66849 /*
   66850 ** Perform a read or write operation on a blob
   66851 */
   66852 static int blobReadWrite(
   66853   sqlite3_blob *pBlob,
   66854   void *z,
   66855   int n,
   66856   int iOffset,
   66857   int (*xCall)(BtCursor*, u32, u32, void*)
   66858 ){
   66859   int rc;
   66860   Incrblob *p = (Incrblob *)pBlob;
   66861   Vdbe *v;
   66862   sqlite3 *db;
   66863 
   66864   if( p==0 ) return SQLITE_MISUSE_BKPT;
   66865   db = p->db;
   66866   sqlite3_mutex_enter(db->mutex);
   66867   v = (Vdbe*)p->pStmt;
   66868 
   66869   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
   66870     /* Request is out of range. Return a transient error. */
   66871     rc = SQLITE_ERROR;
   66872     sqlite3Error(db, SQLITE_ERROR, 0);
   66873   }else if( v==0 ){
   66874     /* If there is no statement handle, then the blob-handle has
   66875     ** already been invalidated. Return SQLITE_ABORT in this case.
   66876     */
   66877     rc = SQLITE_ABORT;
   66878   }else{
   66879     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
   66880     ** returned, clean-up the statement handle.
   66881     */
   66882     assert( db == v->db );
   66883     sqlite3BtreeEnterCursor(p->pCsr);
   66884     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
   66885     sqlite3BtreeLeaveCursor(p->pCsr);
   66886     if( rc==SQLITE_ABORT ){
   66887       sqlite3VdbeFinalize(v);
   66888       p->pStmt = 0;
   66889     }else{
   66890       db->errCode = rc;
   66891       v->rc = rc;
   66892     }
   66893   }
   66894   rc = sqlite3ApiExit(db, rc);
   66895   sqlite3_mutex_leave(db->mutex);
   66896   return rc;
   66897 }
   66898 
   66899 /*
   66900 ** Read data from a blob handle.
   66901 */
   66902 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
   66903   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
   66904 }
   66905 
   66906 /*
   66907 ** Write data to a blob handle.
   66908 */
   66909 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
   66910   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
   66911 }
   66912 
   66913 /*
   66914 ** Query a blob handle for the size of the data.
   66915 **
   66916 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
   66917 ** so no mutex is required for access.
   66918 */
   66919 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
   66920   Incrblob *p = (Incrblob *)pBlob;
   66921   return (p && p->pStmt) ? p->nByte : 0;
   66922 }
   66923 
   66924 /*
   66925 ** Move an existing blob handle to point to a different row of the same
   66926 ** database table.
   66927 **
   66928 ** If an error occurs, or if the specified row does not exist or does not
   66929 ** contain a blob or text value, then an error code is returned and the
   66930 ** database handle error code and message set. If this happens, then all
   66931 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
   66932 ** immediately return SQLITE_ABORT.
   66933 */
   66934 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
   66935   int rc;
   66936   Incrblob *p = (Incrblob *)pBlob;
   66937   sqlite3 *db;
   66938 
   66939   if( p==0 ) return SQLITE_MISUSE_BKPT;
   66940   db = p->db;
   66941   sqlite3_mutex_enter(db->mutex);
   66942 
   66943   if( p->pStmt==0 ){
   66944     /* If there is no statement handle, then the blob-handle has
   66945     ** already been invalidated. Return SQLITE_ABORT in this case.
   66946     */
   66947     rc = SQLITE_ABORT;
   66948   }else{
   66949     char *zErr;
   66950     rc = blobSeekToRow(p, iRow, &zErr);
   66951     if( rc!=SQLITE_OK ){
   66952       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   66953       sqlite3DbFree(db, zErr);
   66954     }
   66955     assert( rc!=SQLITE_SCHEMA );
   66956   }
   66957 
   66958   rc = sqlite3ApiExit(db, rc);
   66959   assert( rc==SQLITE_OK || p->pStmt==0 );
   66960   sqlite3_mutex_leave(db->mutex);
   66961   return rc;
   66962 }
   66963 
   66964 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
   66965 
   66966 /************** End of vdbeblob.c ********************************************/
   66967 /************** Begin file journal.c *****************************************/
   66968 /*
   66969 ** 2007 August 22
   66970 **
   66971 ** The author disclaims copyright to this source code.  In place of
   66972 ** a legal notice, here is a blessing:
   66973 **
   66974 **    May you do good and not evil.
   66975 **    May you find forgiveness for yourself and forgive others.
   66976 **    May you share freely, never taking more than you give.
   66977 **
   66978 *************************************************************************
   66979 **
   66980 ** This file implements a special kind of sqlite3_file object used
   66981 ** by SQLite to create journal files if the atomic-write optimization
   66982 ** is enabled.
   66983 **
   66984 ** The distinctive characteristic of this sqlite3_file is that the
   66985 ** actual on disk file is created lazily. When the file is created,
   66986 ** the caller specifies a buffer size for an in-memory buffer to
   66987 ** be used to service read() and write() requests. The actual file
   66988 ** on disk is not created or populated until either:
   66989 **
   66990 **   1) The in-memory representation grows too large for the allocated
   66991 **      buffer, or
   66992 **   2) The sqlite3JournalCreate() function is called.
   66993 */
   66994 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
   66995 
   66996 
   66997 /*
   66998 ** A JournalFile object is a subclass of sqlite3_file used by
   66999 ** as an open file handle for journal files.
   67000 */
   67001 struct JournalFile {
   67002   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
   67003   int nBuf;                       /* Size of zBuf[] in bytes */
   67004   char *zBuf;                     /* Space to buffer journal writes */
   67005   int iSize;                      /* Amount of zBuf[] currently used */
   67006   int flags;                      /* xOpen flags */
   67007   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
   67008   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
   67009   const char *zJournal;           /* Name of the journal file */
   67010 };
   67011 typedef struct JournalFile JournalFile;
   67012 
   67013 /*
   67014 ** If it does not already exists, create and populate the on-disk file
   67015 ** for JournalFile p.
   67016 */
   67017 static int createFile(JournalFile *p){
   67018   int rc = SQLITE_OK;
   67019   if( !p->pReal ){
   67020     sqlite3_file *pReal = (sqlite3_file *)&p[1];
   67021     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
   67022     if( rc==SQLITE_OK ){
   67023       p->pReal = pReal;
   67024       if( p->iSize>0 ){
   67025         assert(p->iSize<=p->nBuf);
   67026         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
   67027       }
   67028     }
   67029   }
   67030   return rc;
   67031 }
   67032 
   67033 /*
   67034 ** Close the file.
   67035 */
   67036 static int jrnlClose(sqlite3_file *pJfd){
   67037   JournalFile *p = (JournalFile *)pJfd;
   67038   if( p->pReal ){
   67039     sqlite3OsClose(p->pReal);
   67040   }
   67041   sqlite3_free(p->zBuf);
   67042   return SQLITE_OK;
   67043 }
   67044 
   67045 /*
   67046 ** Read data from the file.
   67047 */
   67048 static int jrnlRead(
   67049   sqlite3_file *pJfd,    /* The journal file from which to read */
   67050   void *zBuf,            /* Put the results here */
   67051   int iAmt,              /* Number of bytes to read */
   67052   sqlite_int64 iOfst     /* Begin reading at this offset */
   67053 ){
   67054   int rc = SQLITE_OK;
   67055   JournalFile *p = (JournalFile *)pJfd;
   67056   if( p->pReal ){
   67057     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
   67058   }else if( (iAmt+iOfst)>p->iSize ){
   67059     rc = SQLITE_IOERR_SHORT_READ;
   67060   }else{
   67061     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
   67062   }
   67063   return rc;
   67064 }
   67065 
   67066 /*
   67067 ** Write data to the file.
   67068 */
   67069 static int jrnlWrite(
   67070   sqlite3_file *pJfd,    /* The journal file into which to write */
   67071   const void *zBuf,      /* Take data to be written from here */
   67072   int iAmt,              /* Number of bytes to write */
   67073   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   67074 ){
   67075   int rc = SQLITE_OK;
   67076   JournalFile *p = (JournalFile *)pJfd;
   67077   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
   67078     rc = createFile(p);
   67079   }
   67080   if( rc==SQLITE_OK ){
   67081     if( p->pReal ){
   67082       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
   67083     }else{
   67084       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
   67085       if( p->iSize<(iOfst+iAmt) ){
   67086         p->iSize = (iOfst+iAmt);
   67087       }
   67088     }
   67089   }
   67090   return rc;
   67091 }
   67092 
   67093 /*
   67094 ** Truncate the file.
   67095 */
   67096 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   67097   int rc = SQLITE_OK;
   67098   JournalFile *p = (JournalFile *)pJfd;
   67099   if( p->pReal ){
   67100     rc = sqlite3OsTruncate(p->pReal, size);
   67101   }else if( size<p->iSize ){
   67102     p->iSize = size;
   67103   }
   67104   return rc;
   67105 }
   67106 
   67107 /*
   67108 ** Sync the file.
   67109 */
   67110 static int jrnlSync(sqlite3_file *pJfd, int flags){
   67111   int rc;
   67112   JournalFile *p = (JournalFile *)pJfd;
   67113   if( p->pReal ){
   67114     rc = sqlite3OsSync(p->pReal, flags);
   67115   }else{
   67116     rc = SQLITE_OK;
   67117   }
   67118   return rc;
   67119 }
   67120 
   67121 /*
   67122 ** Query the size of the file in bytes.
   67123 */
   67124 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   67125   int rc = SQLITE_OK;
   67126   JournalFile *p = (JournalFile *)pJfd;
   67127   if( p->pReal ){
   67128     rc = sqlite3OsFileSize(p->pReal, pSize);
   67129   }else{
   67130     *pSize = (sqlite_int64) p->iSize;
   67131   }
   67132   return rc;
   67133 }
   67134 
   67135 /*
   67136 ** Table of methods for JournalFile sqlite3_file object.
   67137 */
   67138 static struct sqlite3_io_methods JournalFileMethods = {
   67139   1,             /* iVersion */
   67140   jrnlClose,     /* xClose */
   67141   jrnlRead,      /* xRead */
   67142   jrnlWrite,     /* xWrite */
   67143   jrnlTruncate,  /* xTruncate */
   67144   jrnlSync,      /* xSync */
   67145   jrnlFileSize,  /* xFileSize */
   67146   0,             /* xLock */
   67147   0,             /* xUnlock */
   67148   0,             /* xCheckReservedLock */
   67149   0,             /* xFileControl */
   67150   0,             /* xSectorSize */
   67151   0,             /* xDeviceCharacteristics */
   67152   0,             /* xShmMap */
   67153   0,             /* xShmLock */
   67154   0,             /* xShmBarrier */
   67155   0              /* xShmUnmap */
   67156 };
   67157 
   67158 /*
   67159 ** Open a journal file.
   67160 */
   67161 SQLITE_PRIVATE int sqlite3JournalOpen(
   67162   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
   67163   const char *zName,         /* Name of the journal file */
   67164   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
   67165   int flags,                 /* Opening flags */
   67166   int nBuf                   /* Bytes buffered before opening the file */
   67167 ){
   67168   JournalFile *p = (JournalFile *)pJfd;
   67169   memset(p, 0, sqlite3JournalSize(pVfs));
   67170   if( nBuf>0 ){
   67171     p->zBuf = sqlite3MallocZero(nBuf);
   67172     if( !p->zBuf ){
   67173       return SQLITE_NOMEM;
   67174     }
   67175   }else{
   67176     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
   67177   }
   67178   p->pMethod = &JournalFileMethods;
   67179   p->nBuf = nBuf;
   67180   p->flags = flags;
   67181   p->zJournal = zName;
   67182   p->pVfs = pVfs;
   67183   return SQLITE_OK;
   67184 }
   67185 
   67186 /*
   67187 ** If the argument p points to a JournalFile structure, and the underlying
   67188 ** file has not yet been created, create it now.
   67189 */
   67190 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
   67191   if( p->pMethods!=&JournalFileMethods ){
   67192     return SQLITE_OK;
   67193   }
   67194   return createFile((JournalFile *)p);
   67195 }
   67196 
   67197 /*
   67198 ** Return the number of bytes required to store a JournalFile that uses vfs
   67199 ** pVfs to create the underlying on-disk files.
   67200 */
   67201 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
   67202   return (pVfs->szOsFile+sizeof(JournalFile));
   67203 }
   67204 #endif
   67205 
   67206 /************** End of journal.c *********************************************/
   67207 /************** Begin file memjournal.c **************************************/
   67208 /*
   67209 ** 2008 October 7
   67210 **
   67211 ** The author disclaims copyright to this source code.  In place of
   67212 ** a legal notice, here is a blessing:
   67213 **
   67214 **    May you do good and not evil.
   67215 **    May you find forgiveness for yourself and forgive others.
   67216 **    May you share freely, never taking more than you give.
   67217 **
   67218 *************************************************************************
   67219 **
   67220 ** This file contains code use to implement an in-memory rollback journal.
   67221 ** The in-memory rollback journal is used to journal transactions for
   67222 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
   67223 */
   67224 
   67225 /* Forward references to internal structures */
   67226 typedef struct MemJournal MemJournal;
   67227 typedef struct FilePoint FilePoint;
   67228 typedef struct FileChunk FileChunk;
   67229 
   67230 /* Space to hold the rollback journal is allocated in increments of
   67231 ** this many bytes.
   67232 **
   67233 ** The size chosen is a little less than a power of two.  That way,
   67234 ** the FileChunk object will have a size that almost exactly fills
   67235 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
   67236 ** memory allocators.
   67237 */
   67238 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
   67239 
   67240 /* Macro to find the minimum of two numeric values.
   67241 */
   67242 #ifndef MIN
   67243 # define MIN(x,y) ((x)<(y)?(x):(y))
   67244 #endif
   67245 
   67246 /*
   67247 ** The rollback journal is composed of a linked list of these structures.
   67248 */
   67249 struct FileChunk {
   67250   FileChunk *pNext;               /* Next chunk in the journal */
   67251   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
   67252 };
   67253 
   67254 /*
   67255 ** An instance of this object serves as a cursor into the rollback journal.
   67256 ** The cursor can be either for reading or writing.
   67257 */
   67258 struct FilePoint {
   67259   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
   67260   FileChunk *pChunk;              /* Specific chunk into which cursor points */
   67261 };
   67262 
   67263 /*
   67264 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
   67265 ** is an instance of this class.
   67266 */
   67267 struct MemJournal {
   67268   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
   67269   FileChunk *pFirst;              /* Head of in-memory chunk-list */
   67270   FilePoint endpoint;             /* Pointer to the end of the file */
   67271   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
   67272 };
   67273 
   67274 /*
   67275 ** Read data from the in-memory journal file.  This is the implementation
   67276 ** of the sqlite3_vfs.xRead method.
   67277 */
   67278 static int memjrnlRead(
   67279   sqlite3_file *pJfd,    /* The journal file from which to read */
   67280   void *zBuf,            /* Put the results here */
   67281   int iAmt,              /* Number of bytes to read */
   67282   sqlite_int64 iOfst     /* Begin reading at this offset */
   67283 ){
   67284   MemJournal *p = (MemJournal *)pJfd;
   67285   u8 *zOut = zBuf;
   67286   int nRead = iAmt;
   67287   int iChunkOffset;
   67288   FileChunk *pChunk;
   67289 
   67290   /* SQLite never tries to read past the end of a rollback journal file */
   67291   assert( iOfst+iAmt<=p->endpoint.iOffset );
   67292 
   67293   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
   67294     sqlite3_int64 iOff = 0;
   67295     for(pChunk=p->pFirst;
   67296         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
   67297         pChunk=pChunk->pNext
   67298     ){
   67299       iOff += JOURNAL_CHUNKSIZE;
   67300     }
   67301   }else{
   67302     pChunk = p->readpoint.pChunk;
   67303   }
   67304 
   67305   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
   67306   do {
   67307     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
   67308     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
   67309     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
   67310     zOut += nCopy;
   67311     nRead -= iSpace;
   67312     iChunkOffset = 0;
   67313   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
   67314   p->readpoint.iOffset = iOfst+iAmt;
   67315   p->readpoint.pChunk = pChunk;
   67316 
   67317   return SQLITE_OK;
   67318 }
   67319 
   67320 /*
   67321 ** Write data to the file.
   67322 */
   67323 static int memjrnlWrite(
   67324   sqlite3_file *pJfd,    /* The journal file into which to write */
   67325   const void *zBuf,      /* Take data to be written from here */
   67326   int iAmt,              /* Number of bytes to write */
   67327   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
   67328 ){
   67329   MemJournal *p = (MemJournal *)pJfd;
   67330   int nWrite = iAmt;
   67331   u8 *zWrite = (u8 *)zBuf;
   67332 
   67333   /* An in-memory journal file should only ever be appended to. Random
   67334   ** access writes are not required by sqlite.
   67335   */
   67336   assert( iOfst==p->endpoint.iOffset );
   67337   UNUSED_PARAMETER(iOfst);
   67338 
   67339   while( nWrite>0 ){
   67340     FileChunk *pChunk = p->endpoint.pChunk;
   67341     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
   67342     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
   67343 
   67344     if( iChunkOffset==0 ){
   67345       /* New chunk is required to extend the file. */
   67346       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
   67347       if( !pNew ){
   67348         return SQLITE_IOERR_NOMEM;
   67349       }
   67350       pNew->pNext = 0;
   67351       if( pChunk ){
   67352         assert( p->pFirst );
   67353         pChunk->pNext = pNew;
   67354       }else{
   67355         assert( !p->pFirst );
   67356         p->pFirst = pNew;
   67357       }
   67358       p->endpoint.pChunk = pNew;
   67359     }
   67360 
   67361     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
   67362     zWrite += iSpace;
   67363     nWrite -= iSpace;
   67364     p->endpoint.iOffset += iSpace;
   67365   }
   67366 
   67367   return SQLITE_OK;
   67368 }
   67369 
   67370 /*
   67371 ** Truncate the file.
   67372 */
   67373 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   67374   MemJournal *p = (MemJournal *)pJfd;
   67375   FileChunk *pChunk;
   67376   assert(size==0);
   67377   UNUSED_PARAMETER(size);
   67378   pChunk = p->pFirst;
   67379   while( pChunk ){
   67380     FileChunk *pTmp = pChunk;
   67381     pChunk = pChunk->pNext;
   67382     sqlite3_free(pTmp);
   67383   }
   67384   sqlite3MemJournalOpen(pJfd);
   67385   return SQLITE_OK;
   67386 }
   67387 
   67388 /*
   67389 ** Close the file.
   67390 */
   67391 static int memjrnlClose(sqlite3_file *pJfd){
   67392   memjrnlTruncate(pJfd, 0);
   67393   return SQLITE_OK;
   67394 }
   67395 
   67396 
   67397 /*
   67398 ** Sync the file.
   67399 **
   67400 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
   67401 ** is never called in a working implementation.  This implementation
   67402 ** exists purely as a contingency, in case some malfunction in some other
   67403 ** part of SQLite causes Sync to be called by mistake.
   67404 */
   67405 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
   67406   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   67407   return SQLITE_OK;
   67408 }
   67409 
   67410 /*
   67411 ** Query the size of the file in bytes.
   67412 */
   67413 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
   67414   MemJournal *p = (MemJournal *)pJfd;
   67415   *pSize = (sqlite_int64) p->endpoint.iOffset;
   67416   return SQLITE_OK;
   67417 }
   67418 
   67419 /*
   67420 ** Table of methods for MemJournal sqlite3_file object.
   67421 */
   67422 static const struct sqlite3_io_methods MemJournalMethods = {
   67423   1,                /* iVersion */
   67424   memjrnlClose,     /* xClose */
   67425   memjrnlRead,      /* xRead */
   67426   memjrnlWrite,     /* xWrite */
   67427   memjrnlTruncate,  /* xTruncate */
   67428   memjrnlSync,      /* xSync */
   67429   memjrnlFileSize,  /* xFileSize */
   67430   0,                /* xLock */
   67431   0,                /* xUnlock */
   67432   0,                /* xCheckReservedLock */
   67433   0,                /* xFileControl */
   67434   0,                /* xSectorSize */
   67435   0,                /* xDeviceCharacteristics */
   67436   0,                /* xShmMap */
   67437   0,                /* xShmLock */
   67438   0,                /* xShmBarrier */
   67439   0                 /* xShmUnlock */
   67440 };
   67441 
   67442 /*
   67443 ** Open a journal file.
   67444 */
   67445 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
   67446   MemJournal *p = (MemJournal *)pJfd;
   67447   assert( EIGHT_BYTE_ALIGNMENT(p) );
   67448   memset(p, 0, sqlite3MemJournalSize());
   67449   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
   67450 }
   67451 
   67452 /*
   67453 ** Return true if the file-handle passed as an argument is
   67454 ** an in-memory journal
   67455 */
   67456 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
   67457   return pJfd->pMethods==&MemJournalMethods;
   67458 }
   67459 
   67460 /*
   67461 ** Return the number of bytes required to store a MemJournal file descriptor.
   67462 */
   67463 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
   67464   return sizeof(MemJournal);
   67465 }
   67466 
   67467 /************** End of memjournal.c ******************************************/
   67468 /************** Begin file walker.c ******************************************/
   67469 /*
   67470 ** 2008 August 16
   67471 **
   67472 ** The author disclaims copyright to this source code.  In place of
   67473 ** a legal notice, here is a blessing:
   67474 **
   67475 **    May you do good and not evil.
   67476 **    May you find forgiveness for yourself and forgive others.
   67477 **    May you share freely, never taking more than you give.
   67478 **
   67479 *************************************************************************
   67480 ** This file contains routines used for walking the parser tree for
   67481 ** an SQL statement.
   67482 */
   67483 
   67484 
   67485 /*
   67486 ** Walk an expression tree.  Invoke the callback once for each node
   67487 ** of the expression, while decending.  (In other words, the callback
   67488 ** is invoked before visiting children.)
   67489 **
   67490 ** The return value from the callback should be one of the WRC_*
   67491 ** constants to specify how to proceed with the walk.
   67492 **
   67493 **    WRC_Continue      Continue descending down the tree.
   67494 **
   67495 **    WRC_Prune         Do not descend into child nodes.  But allow
   67496 **                      the walk to continue with sibling nodes.
   67497 **
   67498 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
   67499 **                      return the top-level walk call.
   67500 **
   67501 ** The return value from this routine is WRC_Abort to abandon the tree walk
   67502 ** and WRC_Continue to continue.
   67503 */
   67504 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
   67505   int rc;
   67506   if( pExpr==0 ) return WRC_Continue;
   67507   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
   67508   testcase( ExprHasProperty(pExpr, EP_Reduced) );
   67509   rc = pWalker->xExprCallback(pWalker, pExpr);
   67510   if( rc==WRC_Continue
   67511               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
   67512     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
   67513     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
   67514     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   67515       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
   67516     }else{
   67517       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
   67518     }
   67519   }
   67520   return rc & WRC_Abort;
   67521 }
   67522 
   67523 /*
   67524 ** Call sqlite3WalkExpr() for every expression in list p or until
   67525 ** an abort request is seen.
   67526 */
   67527 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
   67528   int i;
   67529   struct ExprList_item *pItem;
   67530   if( p ){
   67531     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
   67532       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
   67533     }
   67534   }
   67535   return WRC_Continue;
   67536 }
   67537 
   67538 /*
   67539 ** Walk all expressions associated with SELECT statement p.  Do
   67540 ** not invoke the SELECT callback on p, but do (of course) invoke
   67541 ** any expr callbacks and SELECT callbacks that come from subqueries.
   67542 ** Return WRC_Abort or WRC_Continue.
   67543 */
   67544 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
   67545   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
   67546   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
   67547   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
   67548   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
   67549   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
   67550   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
   67551   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
   67552   return WRC_Continue;
   67553 }
   67554 
   67555 /*
   67556 ** Walk the parse trees associated with all subqueries in the
   67557 ** FROM clause of SELECT statement p.  Do not invoke the select
   67558 ** callback on p, but do invoke it on each FROM clause subquery
   67559 ** and on any subqueries further down in the tree.  Return
   67560 ** WRC_Abort or WRC_Continue;
   67561 */
   67562 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   67563   SrcList *pSrc;
   67564   int i;
   67565   struct SrcList_item *pItem;
   67566 
   67567   pSrc = p->pSrc;
   67568   if( ALWAYS(pSrc) ){
   67569     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   67570       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
   67571         return WRC_Abort;
   67572       }
   67573     }
   67574   }
   67575   return WRC_Continue;
   67576 }
   67577 
   67578 /*
   67579 ** Call sqlite3WalkExpr() for every expression in Select statement p.
   67580 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
   67581 ** on the compound select chain, p->pPrior.
   67582 **
   67583 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
   67584 ** there is an abort request.
   67585 **
   67586 ** If the Walker does not have an xSelectCallback() then this routine
   67587 ** is a no-op returning WRC_Continue.
   67588 */
   67589 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   67590   int rc;
   67591   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
   67592   rc = WRC_Continue;
   67593   while( p  ){
   67594     rc = pWalker->xSelectCallback(pWalker, p);
   67595     if( rc ) break;
   67596     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
   67597     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
   67598     p = p->pPrior;
   67599   }
   67600   return rc & WRC_Abort;
   67601 }
   67602 
   67603 /************** End of walker.c **********************************************/
   67604 /************** Begin file resolve.c *****************************************/
   67605 /*
   67606 ** 2008 August 18
   67607 **
   67608 ** The author disclaims copyright to this source code.  In place of
   67609 ** a legal notice, here is a blessing:
   67610 **
   67611 **    May you do good and not evil.
   67612 **    May you find forgiveness for yourself and forgive others.
   67613 **    May you share freely, never taking more than you give.
   67614 **
   67615 *************************************************************************
   67616 **
   67617 ** This file contains routines used for walking the parser tree and
   67618 ** resolve all identifiers by associating them with a particular
   67619 ** table and column.
   67620 */
   67621 
   67622 /*
   67623 ** Turn the pExpr expression into an alias for the iCol-th column of the
   67624 ** result set in pEList.
   67625 **
   67626 ** If the result set column is a simple column reference, then this routine
   67627 ** makes an exact copy.  But for any other kind of expression, this
   67628 ** routine make a copy of the result set column as the argument to the
   67629 ** TK_AS operator.  The TK_AS operator causes the expression to be
   67630 ** evaluated just once and then reused for each alias.
   67631 **
   67632 ** The reason for suppressing the TK_AS term when the expression is a simple
   67633 ** column reference is so that the column reference will be recognized as
   67634 ** usable by indices within the WHERE clause processing logic.
   67635 **
   67636 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
   67637 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
   67638 **
   67639 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
   67640 **
   67641 ** Is equivalent to:
   67642 **
   67643 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
   67644 **
   67645 ** The result of random()%5 in the GROUP BY clause is probably different
   67646 ** from the result in the result-set.  We might fix this someday.  Or
   67647 ** then again, we might not...
   67648 */
   67649 static void resolveAlias(
   67650   Parse *pParse,         /* Parsing context */
   67651   ExprList *pEList,      /* A result set */
   67652   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
   67653   Expr *pExpr,           /* Transform this into an alias to the result set */
   67654   const char *zType      /* "GROUP" or "ORDER" or "" */
   67655 ){
   67656   Expr *pOrig;           /* The iCol-th column of the result set */
   67657   Expr *pDup;            /* Copy of pOrig */
   67658   sqlite3 *db;           /* The database connection */
   67659 
   67660   assert( iCol>=0 && iCol<pEList->nExpr );
   67661   pOrig = pEList->a[iCol].pExpr;
   67662   assert( pOrig!=0 );
   67663   assert( pOrig->flags & EP_Resolved );
   67664   db = pParse->db;
   67665   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   67666     pDup = sqlite3ExprDup(db, pOrig, 0);
   67667     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   67668     if( pDup==0 ) return;
   67669     if( pEList->a[iCol].iAlias==0 ){
   67670       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
   67671     }
   67672     pDup->iTable = pEList->a[iCol].iAlias;
   67673   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
   67674     pDup = sqlite3ExprDup(db, pOrig, 0);
   67675     if( pDup==0 ) return;
   67676   }else{
   67677     char *zToken = pOrig->u.zToken;
   67678     assert( zToken!=0 );
   67679     pOrig->u.zToken = 0;
   67680     pDup = sqlite3ExprDup(db, pOrig, 0);
   67681     pOrig->u.zToken = zToken;
   67682     if( pDup==0 ) return;
   67683     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
   67684     pDup->flags2 |= EP2_MallocedToken;
   67685     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
   67686   }
   67687   if( pExpr->flags & EP_ExpCollate ){
   67688     pDup->pColl = pExpr->pColl;
   67689     pDup->flags |= EP_ExpCollate;
   67690   }
   67691 
   67692   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
   67693   ** prevents ExprDelete() from deleting the Expr structure itself,
   67694   ** allowing it to be repopulated by the memcpy() on the following line.
   67695   */
   67696   ExprSetProperty(pExpr, EP_Static);
   67697   sqlite3ExprDelete(db, pExpr);
   67698   memcpy(pExpr, pDup, sizeof(*pExpr));
   67699   sqlite3DbFree(db, pDup);
   67700 }
   67701 
   67702 /*
   67703 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
   67704 ** that name in the set of source tables in pSrcList and make the pExpr
   67705 ** expression node refer back to that source column.  The following changes
   67706 ** are made to pExpr:
   67707 **
   67708 **    pExpr->iDb           Set the index in db->aDb[] of the database X
   67709 **                         (even if X is implied).
   67710 **    pExpr->iTable        Set to the cursor number for the table obtained
   67711 **                         from pSrcList.
   67712 **    pExpr->pTab          Points to the Table structure of X.Y (even if
   67713 **                         X and/or Y are implied.)
   67714 **    pExpr->iColumn       Set to the column number within the table.
   67715 **    pExpr->op            Set to TK_COLUMN.
   67716 **    pExpr->pLeft         Any expression this points to is deleted
   67717 **    pExpr->pRight        Any expression this points to is deleted.
   67718 **
   67719 ** The zDb variable is the name of the database (the "X").  This value may be
   67720 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
   67721 ** can be used.  The zTable variable is the name of the table (the "Y").  This
   67722 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
   67723 ** means that the form of the name is Z and that columns from any table
   67724 ** can be used.
   67725 **
   67726 ** If the name cannot be resolved unambiguously, leave an error message
   67727 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
   67728 */
   67729 static int lookupName(
   67730   Parse *pParse,       /* The parsing context */
   67731   const char *zDb,     /* Name of the database containing table, or NULL */
   67732   const char *zTab,    /* Name of table containing column, or NULL */
   67733   const char *zCol,    /* Name of the column. */
   67734   NameContext *pNC,    /* The name context used to resolve the name */
   67735   Expr *pExpr          /* Make this EXPR node point to the selected column */
   67736 ){
   67737   int i, j;            /* Loop counters */
   67738   int cnt = 0;                      /* Number of matching column names */
   67739   int cntTab = 0;                   /* Number of matching table names */
   67740   sqlite3 *db = pParse->db;         /* The database connection */
   67741   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
   67742   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
   67743   NameContext *pTopNC = pNC;        /* First namecontext in the list */
   67744   Schema *pSchema = 0;              /* Schema of the expression */
   67745   int isTrigger = 0;
   67746 
   67747   assert( pNC );     /* the name context cannot be NULL. */
   67748   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
   67749   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   67750 
   67751   /* Initialize the node to no-match */
   67752   pExpr->iTable = -1;
   67753   pExpr->pTab = 0;
   67754   ExprSetIrreducible(pExpr);
   67755 
   67756   /* Start at the inner-most context and move outward until a match is found */
   67757   while( pNC && cnt==0 ){
   67758     ExprList *pEList;
   67759     SrcList *pSrcList = pNC->pSrcList;
   67760 
   67761     if( pSrcList ){
   67762       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   67763         Table *pTab;
   67764         int iDb;
   67765         Column *pCol;
   67766 
   67767         pTab = pItem->pTab;
   67768         assert( pTab!=0 && pTab->zName!=0 );
   67769         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   67770         assert( pTab->nCol>0 );
   67771         if( zTab ){
   67772           if( pItem->zAlias ){
   67773             char *zTabName = pItem->zAlias;
   67774             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   67775           }else{
   67776             char *zTabName = pTab->zName;
   67777             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
   67778               continue;
   67779             }
   67780             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
   67781               continue;
   67782             }
   67783           }
   67784         }
   67785         if( 0==(cntTab++) ){
   67786           pExpr->iTable = pItem->iCursor;
   67787           pExpr->pTab = pTab;
   67788           pSchema = pTab->pSchema;
   67789           pMatch = pItem;
   67790         }
   67791         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   67792           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   67793             IdList *pUsing;
   67794             cnt++;
   67795             pExpr->iTable = pItem->iCursor;
   67796             pExpr->pTab = pTab;
   67797             pMatch = pItem;
   67798             pSchema = pTab->pSchema;
   67799             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   67800             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
   67801             if( i<pSrcList->nSrc-1 ){
   67802               if( pItem[1].jointype & JT_NATURAL ){
   67803                 /* If this match occurred in the left table of a natural join,
   67804                 ** then skip the right table to avoid a duplicate match */
   67805                 pItem++;
   67806                 i++;
   67807               }else if( (pUsing = pItem[1].pUsing)!=0 ){
   67808                 /* If this match occurs on a column that is in the USING clause
   67809                 ** of a join, skip the search of the right table of the join
   67810                 ** to avoid a duplicate match there. */
   67811                 int k;
   67812                 for(k=0; k<pUsing->nId; k++){
   67813                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
   67814                     pItem++;
   67815                     i++;
   67816                     break;
   67817                   }
   67818                 }
   67819               }
   67820             }
   67821             break;
   67822           }
   67823         }
   67824       }
   67825     }
   67826 
   67827 #ifndef SQLITE_OMIT_TRIGGER
   67828     /* If we have not already resolved the name, then maybe
   67829     ** it is a new.* or old.* trigger argument reference
   67830     */
   67831     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
   67832       int op = pParse->eTriggerOp;
   67833       Table *pTab = 0;
   67834       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   67835       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   67836         pExpr->iTable = 1;
   67837         pTab = pParse->pTriggerTab;
   67838       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   67839         pExpr->iTable = 0;
   67840         pTab = pParse->pTriggerTab;
   67841       }
   67842 
   67843       if( pTab ){
   67844         int iCol;
   67845         pSchema = pTab->pSchema;
   67846         cntTab++;
   67847         for(iCol=0; iCol<pTab->nCol; iCol++){
   67848           Column *pCol = &pTab->aCol[iCol];
   67849           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   67850             if( iCol==pTab->iPKey ){
   67851               iCol = -1;
   67852             }
   67853             break;
   67854           }
   67855         }
   67856         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
   67857           iCol = -1;        /* IMP: R-44911-55124 */
   67858         }
   67859         if( iCol<pTab->nCol ){
   67860           cnt++;
   67861           if( iCol<0 ){
   67862             pExpr->affinity = SQLITE_AFF_INTEGER;
   67863           }else if( pExpr->iTable==0 ){
   67864             testcase( iCol==31 );
   67865             testcase( iCol==32 );
   67866             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   67867           }else{
   67868             testcase( iCol==31 );
   67869             testcase( iCol==32 );
   67870             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
   67871           }
   67872           pExpr->iColumn = (i16)iCol;
   67873           pExpr->pTab = pTab;
   67874           isTrigger = 1;
   67875         }
   67876       }
   67877     }
   67878 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   67879 
   67880     /*
   67881     ** Perhaps the name is a reference to the ROWID
   67882     */
   67883     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
   67884       cnt = 1;
   67885       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   67886       pExpr->affinity = SQLITE_AFF_INTEGER;
   67887     }
   67888 
   67889     /*
   67890     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
   67891     ** might refer to an result-set alias.  This happens, for example, when
   67892     ** we are resolving names in the WHERE clause of the following command:
   67893     **
   67894     **     SELECT a+b AS x FROM table WHERE x<10;
   67895     **
   67896     ** In cases like this, replace pExpr with a copy of the expression that
   67897     ** forms the result set entry ("a+b" in the example) and return immediately.
   67898     ** Note that the expression in the result set should have already been
   67899     ** resolved by the time the WHERE clause is resolved.
   67900     */
   67901     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
   67902       for(j=0; j<pEList->nExpr; j++){
   67903         char *zAs = pEList->a[j].zName;
   67904         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   67905           Expr *pOrig;
   67906           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   67907           assert( pExpr->x.pList==0 );
   67908           assert( pExpr->x.pSelect==0 );
   67909           pOrig = pEList->a[j].pExpr;
   67910           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
   67911             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
   67912             return WRC_Abort;
   67913           }
   67914           resolveAlias(pParse, pEList, j, pExpr, "");
   67915           cnt = 1;
   67916           pMatch = 0;
   67917           assert( zTab==0 && zDb==0 );
   67918           goto lookupname_end;
   67919         }
   67920       }
   67921     }
   67922 
   67923     /* Advance to the next name context.  The loop will exit when either
   67924     ** we have a match (cnt>0) or when we run out of name contexts.
   67925     */
   67926     if( cnt==0 ){
   67927       pNC = pNC->pNext;
   67928     }
   67929   }
   67930 
   67931   /*
   67932   ** If X and Y are NULL (in other words if only the column name Z is
   67933   ** supplied) and the value of Z is enclosed in double-quotes, then
   67934   ** Z is a string literal if it doesn't match any column names.  In that
   67935   ** case, we need to return right away and not make any changes to
   67936   ** pExpr.
   67937   **
   67938   ** Because no reference was made to outer contexts, the pNC->nRef
   67939   ** fields are not changed in any context.
   67940   */
   67941   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
   67942     pExpr->op = TK_STRING;
   67943     pExpr->pTab = 0;
   67944     return WRC_Prune;
   67945   }
   67946 
   67947   /*
   67948   ** cnt==0 means there was not match.  cnt>1 means there were two or
   67949   ** more matches.  Either way, we have an error.
   67950   */
   67951   if( cnt!=1 ){
   67952     const char *zErr;
   67953     zErr = cnt==0 ? "no such column" : "ambiguous column name";
   67954     if( zDb ){
   67955       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
   67956     }else if( zTab ){
   67957       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
   67958     }else{
   67959       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
   67960     }
   67961     pParse->checkSchema = 1;
   67962     pTopNC->nErr++;
   67963   }
   67964 
   67965   /* If a column from a table in pSrcList is referenced, then record
   67966   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
   67967   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
   67968   ** column number is greater than the number of bits in the bitmask
   67969   ** then set the high-order bit of the bitmask.
   67970   */
   67971   if( pExpr->iColumn>=0 && pMatch!=0 ){
   67972     int n = pExpr->iColumn;
   67973     testcase( n==BMS-1 );
   67974     if( n>=BMS ){
   67975       n = BMS-1;
   67976     }
   67977     assert( pMatch->iCursor==pExpr->iTable );
   67978     pMatch->colUsed |= ((Bitmask)1)<<n;
   67979   }
   67980 
   67981   /* Clean up and return
   67982   */
   67983   sqlite3ExprDelete(db, pExpr->pLeft);
   67984   pExpr->pLeft = 0;
   67985   sqlite3ExprDelete(db, pExpr->pRight);
   67986   pExpr->pRight = 0;
   67987   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
   67988 lookupname_end:
   67989   if( cnt==1 ){
   67990     assert( pNC!=0 );
   67991     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
   67992     /* Increment the nRef value on all name contexts from TopNC up to
   67993     ** the point where the name matched. */
   67994     for(;;){
   67995       assert( pTopNC!=0 );
   67996       pTopNC->nRef++;
   67997       if( pTopNC==pNC ) break;
   67998       pTopNC = pTopNC->pNext;
   67999     }
   68000     return WRC_Prune;
   68001   } else {
   68002     return WRC_Abort;
   68003   }
   68004 }
   68005 
   68006 /*
   68007 ** Allocate and return a pointer to an expression to load the column iCol
   68008 ** from datasource iSrc in SrcList pSrc.
   68009 */
   68010 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
   68011   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   68012   if( p ){
   68013     struct SrcList_item *pItem = &pSrc->a[iSrc];
   68014     p->pTab = pItem->pTab;
   68015     p->iTable = pItem->iCursor;
   68016     if( p->pTab->iPKey==iCol ){
   68017       p->iColumn = -1;
   68018     }else{
   68019       p->iColumn = (ynVar)iCol;
   68020       testcase( iCol==BMS );
   68021       testcase( iCol==BMS-1 );
   68022       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   68023     }
   68024     ExprSetProperty(p, EP_Resolved);
   68025   }
   68026   return p;
   68027 }
   68028 
   68029 /*
   68030 ** This routine is callback for sqlite3WalkExpr().
   68031 **
   68032 ** Resolve symbolic names into TK_COLUMN operators for the current
   68033 ** node in the expression tree.  Return 0 to continue the search down
   68034 ** the tree or 2 to abort the tree walk.
   68035 **
   68036 ** This routine also does error checking and name resolution for
   68037 ** function names.  The operator for aggregate functions is changed
   68038 ** to TK_AGG_FUNCTION.
   68039 */
   68040 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
   68041   NameContext *pNC;
   68042   Parse *pParse;
   68043 
   68044   pNC = pWalker->u.pNC;
   68045   assert( pNC!=0 );
   68046   pParse = pNC->pParse;
   68047   assert( pParse==pWalker->pParse );
   68048 
   68049   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
   68050   ExprSetProperty(pExpr, EP_Resolved);
   68051 #ifndef NDEBUG
   68052   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
   68053     SrcList *pSrcList = pNC->pSrcList;
   68054     int i;
   68055     for(i=0; i<pNC->pSrcList->nSrc; i++){
   68056       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
   68057     }
   68058   }
   68059 #endif
   68060   switch( pExpr->op ){
   68061 
   68062 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   68063     /* The special operator TK_ROW means use the rowid for the first
   68064     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
   68065     ** clause processing on UPDATE and DELETE statements.
   68066     */
   68067     case TK_ROW: {
   68068       SrcList *pSrcList = pNC->pSrcList;
   68069       struct SrcList_item *pItem;
   68070       assert( pSrcList && pSrcList->nSrc==1 );
   68071       pItem = pSrcList->a;
   68072       pExpr->op = TK_COLUMN;
   68073       pExpr->pTab = pItem->pTab;
   68074       pExpr->iTable = pItem->iCursor;
   68075       pExpr->iColumn = -1;
   68076       pExpr->affinity = SQLITE_AFF_INTEGER;
   68077       break;
   68078     }
   68079 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   68080 
   68081     /* A lone identifier is the name of a column.
   68082     */
   68083     case TK_ID: {
   68084       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
   68085     }
   68086 
   68087     /* A table name and column name:     ID.ID
   68088     ** Or a database, table and column:  ID.ID.ID
   68089     */
   68090     case TK_DOT: {
   68091       const char *zColumn;
   68092       const char *zTable;
   68093       const char *zDb;
   68094       Expr *pRight;
   68095 
   68096       /* if( pSrcList==0 ) break; */
   68097       pRight = pExpr->pRight;
   68098       if( pRight->op==TK_ID ){
   68099         zDb = 0;
   68100         zTable = pExpr->pLeft->u.zToken;
   68101         zColumn = pRight->u.zToken;
   68102       }else{
   68103         assert( pRight->op==TK_DOT );
   68104         zDb = pExpr->pLeft->u.zToken;
   68105         zTable = pRight->pLeft->u.zToken;
   68106         zColumn = pRight->pRight->u.zToken;
   68107       }
   68108       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
   68109     }
   68110 
   68111     /* Resolve function names
   68112     */
   68113     case TK_CONST_FUNC:
   68114     case TK_FUNCTION: {
   68115       ExprList *pList = pExpr->x.pList;    /* The argument list */
   68116       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
   68117       int no_such_func = 0;       /* True if no such function exists */
   68118       int wrong_num_args = 0;     /* True if wrong number of arguments */
   68119       int is_agg = 0;             /* True if is an aggregate function */
   68120       int auth;                   /* Authorization to use the function */
   68121       int nId;                    /* Number of characters in function name */
   68122       const char *zId;            /* The function name. */
   68123       FuncDef *pDef;              /* Information about the function */
   68124       u8 enc = ENC(pParse->db);   /* The database encoding */
   68125 
   68126       testcase( pExpr->op==TK_CONST_FUNC );
   68127       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   68128       zId = pExpr->u.zToken;
   68129       nId = sqlite3Strlen30(zId);
   68130       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   68131       if( pDef==0 ){
   68132         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
   68133         if( pDef==0 ){
   68134           no_such_func = 1;
   68135         }else{
   68136           wrong_num_args = 1;
   68137         }
   68138       }else{
   68139         is_agg = pDef->xFunc==0;
   68140       }
   68141 #ifndef SQLITE_OMIT_AUTHORIZATION
   68142       if( pDef ){
   68143         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
   68144         if( auth!=SQLITE_OK ){
   68145           if( auth==SQLITE_DENY ){
   68146             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
   68147                                     pDef->zName);
   68148             pNC->nErr++;
   68149           }
   68150           pExpr->op = TK_NULL;
   68151           return WRC_Prune;
   68152         }
   68153       }
   68154 #endif
   68155       if( is_agg && !pNC->allowAgg ){
   68156         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
   68157         pNC->nErr++;
   68158         is_agg = 0;
   68159       }else if( no_such_func ){
   68160         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
   68161         pNC->nErr++;
   68162       }else if( wrong_num_args ){
   68163         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
   68164              nId, zId);
   68165         pNC->nErr++;
   68166       }
   68167       if( is_agg ){
   68168         pExpr->op = TK_AGG_FUNCTION;
   68169         pNC->hasAgg = 1;
   68170       }
   68171       if( is_agg ) pNC->allowAgg = 0;
   68172       sqlite3WalkExprList(pWalker, pList);
   68173       if( is_agg ) pNC->allowAgg = 1;
   68174       /* FIX ME:  Compute pExpr->affinity based on the expected return
   68175       ** type of the function
   68176       */
   68177       return WRC_Prune;
   68178     }
   68179 #ifndef SQLITE_OMIT_SUBQUERY
   68180     case TK_SELECT:
   68181     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   68182 #endif
   68183     case TK_IN: {
   68184       testcase( pExpr->op==TK_IN );
   68185       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   68186         int nRef = pNC->nRef;
   68187 #ifndef SQLITE_OMIT_CHECK
   68188         if( pNC->isCheck ){
   68189           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
   68190         }
   68191 #endif
   68192         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   68193         assert( pNC->nRef>=nRef );
   68194         if( nRef!=pNC->nRef ){
   68195           ExprSetProperty(pExpr, EP_VarSelect);
   68196         }
   68197       }
   68198       break;
   68199     }
   68200 #ifndef SQLITE_OMIT_CHECK
   68201     case TK_VARIABLE: {
   68202       if( pNC->isCheck ){
   68203         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
   68204       }
   68205       break;
   68206     }
   68207 #endif
   68208   }
   68209   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   68210 }
   68211 
   68212 /*
   68213 ** pEList is a list of expressions which are really the result set of the
   68214 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
   68215 ** This routine checks to see if pE is a simple identifier which corresponds
   68216 ** to the AS-name of one of the terms of the expression list.  If it is,
   68217 ** this routine return an integer between 1 and N where N is the number of
   68218 ** elements in pEList, corresponding to the matching entry.  If there is
   68219 ** no match, or if pE is not a simple identifier, then this routine
   68220 ** return 0.
   68221 **
   68222 ** pEList has been resolved.  pE has not.
   68223 */
   68224 static int resolveAsName(
   68225   Parse *pParse,     /* Parsing context for error messages */
   68226   ExprList *pEList,  /* List of expressions to scan */
   68227   Expr *pE           /* Expression we are trying to match */
   68228 ){
   68229   int i;             /* Loop counter */
   68230 
   68231   UNUSED_PARAMETER(pParse);
   68232 
   68233   if( pE->op==TK_ID ){
   68234     char *zCol = pE->u.zToken;
   68235     for(i=0; i<pEList->nExpr; i++){
   68236       char *zAs = pEList->a[i].zName;
   68237       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
   68238         return i+1;
   68239       }
   68240     }
   68241   }
   68242   return 0;
   68243 }
   68244 
   68245 /*
   68246 ** pE is a pointer to an expression which is a single term in the
   68247 ** ORDER BY of a compound SELECT.  The expression has not been
   68248 ** name resolved.
   68249 **
   68250 ** At the point this routine is called, we already know that the
   68251 ** ORDER BY term is not an integer index into the result set.  That
   68252 ** case is handled by the calling routine.
   68253 **
   68254 ** Attempt to match pE against result set columns in the left-most
   68255 ** SELECT statement.  Return the index i of the matching column,
   68256 ** as an indication to the caller that it should sort by the i-th column.
   68257 ** The left-most column is 1.  In other words, the value returned is the
   68258 ** same integer value that would be used in the SQL statement to indicate
   68259 ** the column.
   68260 **
   68261 ** If there is no match, return 0.  Return -1 if an error occurs.
   68262 */
   68263 static int resolveOrderByTermToExprList(
   68264   Parse *pParse,     /* Parsing context for error messages */
   68265   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
   68266   Expr *pE           /* The specific ORDER BY term */
   68267 ){
   68268   int i;             /* Loop counter */
   68269   ExprList *pEList;  /* The columns of the result set */
   68270   NameContext nc;    /* Name context for resolving pE */
   68271   sqlite3 *db;       /* Database connection */
   68272   int rc;            /* Return code from subprocedures */
   68273   u8 savedSuppErr;   /* Saved value of db->suppressErr */
   68274 
   68275   assert( sqlite3ExprIsInteger(pE, &i)==0 );
   68276   pEList = pSelect->pEList;
   68277 
   68278   /* Resolve all names in the ORDER BY term expression
   68279   */
   68280   memset(&nc, 0, sizeof(nc));
   68281   nc.pParse = pParse;
   68282   nc.pSrcList = pSelect->pSrc;
   68283   nc.pEList = pEList;
   68284   nc.allowAgg = 1;
   68285   nc.nErr = 0;
   68286   db = pParse->db;
   68287   savedSuppErr = db->suppressErr;
   68288   db->suppressErr = 1;
   68289   rc = sqlite3ResolveExprNames(&nc, pE);
   68290   db->suppressErr = savedSuppErr;
   68291   if( rc ) return 0;
   68292 
   68293   /* Try to match the ORDER BY expression against an expression
   68294   ** in the result set.  Return an 1-based index of the matching
   68295   ** result-set entry.
   68296   */
   68297   for(i=0; i<pEList->nExpr; i++){
   68298     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
   68299       return i+1;
   68300     }
   68301   }
   68302 
   68303   /* If no match, return 0. */
   68304   return 0;
   68305 }
   68306 
   68307 /*
   68308 ** Generate an ORDER BY or GROUP BY term out-of-range error.
   68309 */
   68310 static void resolveOutOfRangeError(
   68311   Parse *pParse,         /* The error context into which to write the error */
   68312   const char *zType,     /* "ORDER" or "GROUP" */
   68313   int i,                 /* The index (1-based) of the term out of range */
   68314   int mx                 /* Largest permissible value of i */
   68315 ){
   68316   sqlite3ErrorMsg(pParse,
   68317     "%r %s BY term out of range - should be "
   68318     "between 1 and %d", i, zType, mx);
   68319 }
   68320 
   68321 /*
   68322 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
   68323 ** each term of the ORDER BY clause is a constant integer between 1
   68324 ** and N where N is the number of columns in the compound SELECT.
   68325 **
   68326 ** ORDER BY terms that are already an integer between 1 and N are
   68327 ** unmodified.  ORDER BY terms that are integers outside the range of
   68328 ** 1 through N generate an error.  ORDER BY terms that are expressions
   68329 ** are matched against result set expressions of compound SELECT
   68330 ** beginning with the left-most SELECT and working toward the right.
   68331 ** At the first match, the ORDER BY expression is transformed into
   68332 ** the integer column number.
   68333 **
   68334 ** Return the number of errors seen.
   68335 */
   68336 static int resolveCompoundOrderBy(
   68337   Parse *pParse,        /* Parsing context.  Leave error messages here */
   68338   Select *pSelect       /* The SELECT statement containing the ORDER BY */
   68339 ){
   68340   int i;
   68341   ExprList *pOrderBy;
   68342   ExprList *pEList;
   68343   sqlite3 *db;
   68344   int moreToDo = 1;
   68345 
   68346   pOrderBy = pSelect->pOrderBy;
   68347   if( pOrderBy==0 ) return 0;
   68348   db = pParse->db;
   68349 #if SQLITE_MAX_COLUMN
   68350   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   68351     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
   68352     return 1;
   68353   }
   68354 #endif
   68355   for(i=0; i<pOrderBy->nExpr; i++){
   68356     pOrderBy->a[i].done = 0;
   68357   }
   68358   pSelect->pNext = 0;
   68359   while( pSelect->pPrior ){
   68360     pSelect->pPrior->pNext = pSelect;
   68361     pSelect = pSelect->pPrior;
   68362   }
   68363   while( pSelect && moreToDo ){
   68364     struct ExprList_item *pItem;
   68365     moreToDo = 0;
   68366     pEList = pSelect->pEList;
   68367     assert( pEList!=0 );
   68368     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   68369       int iCol = -1;
   68370       Expr *pE, *pDup;
   68371       if( pItem->done ) continue;
   68372       pE = pItem->pExpr;
   68373       if( sqlite3ExprIsInteger(pE, &iCol) ){
   68374         if( iCol<=0 || iCol>pEList->nExpr ){
   68375           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
   68376           return 1;
   68377         }
   68378       }else{
   68379         iCol = resolveAsName(pParse, pEList, pE);
   68380         if( iCol==0 ){
   68381           pDup = sqlite3ExprDup(db, pE, 0);
   68382           if( !db->mallocFailed ){
   68383             assert(pDup);
   68384             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
   68385           }
   68386           sqlite3ExprDelete(db, pDup);
   68387         }
   68388       }
   68389       if( iCol>0 ){
   68390         CollSeq *pColl = pE->pColl;
   68391         int flags = pE->flags & EP_ExpCollate;
   68392         sqlite3ExprDelete(db, pE);
   68393         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
   68394         if( pE==0 ) return 1;
   68395         pE->pColl = pColl;
   68396         pE->flags |= EP_IntValue | flags;
   68397         pE->u.iValue = iCol;
   68398         pItem->iCol = (u16)iCol;
   68399         pItem->done = 1;
   68400       }else{
   68401         moreToDo = 1;
   68402       }
   68403     }
   68404     pSelect = pSelect->pNext;
   68405   }
   68406   for(i=0; i<pOrderBy->nExpr; i++){
   68407     if( pOrderBy->a[i].done==0 ){
   68408       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
   68409             "column in the result set", i+1);
   68410       return 1;
   68411     }
   68412   }
   68413   return 0;
   68414 }
   68415 
   68416 /*
   68417 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   68418 ** the SELECT statement pSelect.  If any term is reference to a
   68419 ** result set expression (as determined by the ExprList.a.iCol field)
   68420 ** then convert that term into a copy of the corresponding result set
   68421 ** column.
   68422 **
   68423 ** If any errors are detected, add an error message to pParse and
   68424 ** return non-zero.  Return zero if no errors are seen.
   68425 */
   68426 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
   68427   Parse *pParse,        /* Parsing context.  Leave error messages here */
   68428   Select *pSelect,      /* The SELECT statement containing the clause */
   68429   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
   68430   const char *zType     /* "ORDER" or "GROUP" */
   68431 ){
   68432   int i;
   68433   sqlite3 *db = pParse->db;
   68434   ExprList *pEList;
   68435   struct ExprList_item *pItem;
   68436 
   68437   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
   68438 #if SQLITE_MAX_COLUMN
   68439   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   68440     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   68441     return 1;
   68442   }
   68443 #endif
   68444   pEList = pSelect->pEList;
   68445   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   68446   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   68447     if( pItem->iCol ){
   68448       if( pItem->iCol>pEList->nExpr ){
   68449         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   68450         return 1;
   68451       }
   68452       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
   68453     }
   68454   }
   68455   return 0;
   68456 }
   68457 
   68458 /*
   68459 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
   68460 ** The Name context of the SELECT statement is pNC.  zType is either
   68461 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
   68462 **
   68463 ** This routine resolves each term of the clause into an expression.
   68464 ** If the order-by term is an integer I between 1 and N (where N is the
   68465 ** number of columns in the result set of the SELECT) then the expression
   68466 ** in the resolution is a copy of the I-th result-set expression.  If
   68467 ** the order-by term is an identify that corresponds to the AS-name of
   68468 ** a result-set expression, then the term resolves to a copy of the
   68469 ** result-set expression.  Otherwise, the expression is resolved in
   68470 ** the usual way - using sqlite3ResolveExprNames().
   68471 **
   68472 ** This routine returns the number of errors.  If errors occur, then
   68473 ** an appropriate error message might be left in pParse.  (OOM errors
   68474 ** excepted.)
   68475 */
   68476 static int resolveOrderGroupBy(
   68477   NameContext *pNC,     /* The name context of the SELECT statement */
   68478   Select *pSelect,      /* The SELECT statement holding pOrderBy */
   68479   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
   68480   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
   68481 ){
   68482   int i;                         /* Loop counter */
   68483   int iCol;                      /* Column number */
   68484   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
   68485   Parse *pParse;                 /* Parsing context */
   68486   int nResult;                   /* Number of terms in the result set */
   68487 
   68488   if( pOrderBy==0 ) return 0;
   68489   nResult = pSelect->pEList->nExpr;
   68490   pParse = pNC->pParse;
   68491   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   68492     Expr *pE = pItem->pExpr;
   68493     iCol = resolveAsName(pParse, pSelect->pEList, pE);
   68494     if( iCol>0 ){
   68495       /* If an AS-name match is found, mark this ORDER BY column as being
   68496       ** a copy of the iCol-th result-set column.  The subsequent call to
   68497       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   68498       ** copy of the iCol-th result-set expression. */
   68499       pItem->iCol = (u16)iCol;
   68500       continue;
   68501     }
   68502     if( sqlite3ExprIsInteger(pE, &iCol) ){
   68503       /* The ORDER BY term is an integer constant.  Again, set the column
   68504       ** number so that sqlite3ResolveOrderGroupBy() will convert the
   68505       ** order-by term to a copy of the result-set expression */
   68506       if( iCol<1 ){
   68507         resolveOutOfRangeError(pParse, zType, i+1, nResult);
   68508         return 1;
   68509       }
   68510       pItem->iCol = (u16)iCol;
   68511       continue;
   68512     }
   68513 
   68514     /* Otherwise, treat the ORDER BY term as an ordinary expression */
   68515     pItem->iCol = 0;
   68516     if( sqlite3ResolveExprNames(pNC, pE) ){
   68517       return 1;
   68518     }
   68519   }
   68520   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   68521 }
   68522 
   68523 /*
   68524 ** Resolve names in the SELECT statement p and all of its descendents.
   68525 */
   68526 static int resolveSelectStep(Walker *pWalker, Select *p){
   68527   NameContext *pOuterNC;  /* Context that contains this SELECT */
   68528   NameContext sNC;        /* Name context of this SELECT */
   68529   int isCompound;         /* True if p is a compound select */
   68530   int nCompound;          /* Number of compound terms processed so far */
   68531   Parse *pParse;          /* Parsing context */
   68532   ExprList *pEList;       /* Result set expression list */
   68533   int i;                  /* Loop counter */
   68534   ExprList *pGroupBy;     /* The GROUP BY clause */
   68535   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   68536   sqlite3 *db;            /* Database connection */
   68537 
   68538 
   68539   assert( p!=0 );
   68540   if( p->selFlags & SF_Resolved ){
   68541     return WRC_Prune;
   68542   }
   68543   pOuterNC = pWalker->u.pNC;
   68544   pParse = pWalker->pParse;
   68545   db = pParse->db;
   68546 
   68547   /* Normally sqlite3SelectExpand() will be called first and will have
   68548   ** already expanded this SELECT.  However, if this is a subquery within
   68549   ** an expression, sqlite3ResolveExprNames() will be called without a
   68550   ** prior call to sqlite3SelectExpand().  When that happens, let
   68551   ** sqlite3SelectPrep() do all of the processing for this SELECT.
   68552   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
   68553   ** this routine in the correct order.
   68554   */
   68555   if( (p->selFlags & SF_Expanded)==0 ){
   68556     sqlite3SelectPrep(pParse, p, pOuterNC);
   68557     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
   68558   }
   68559 
   68560   isCompound = p->pPrior!=0;
   68561   nCompound = 0;
   68562   pLeftmost = p;
   68563   while( p ){
   68564     assert( (p->selFlags & SF_Expanded)!=0 );
   68565     assert( (p->selFlags & SF_Resolved)==0 );
   68566     p->selFlags |= SF_Resolved;
   68567 
   68568     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
   68569     ** are not allowed to refer to any names, so pass an empty NameContext.
   68570     */
   68571     memset(&sNC, 0, sizeof(sNC));
   68572     sNC.pParse = pParse;
   68573     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
   68574         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
   68575       return WRC_Abort;
   68576     }
   68577 
   68578     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
   68579     ** resolve the result-set expression list.
   68580     */
   68581     sNC.allowAgg = 1;
   68582     sNC.pSrcList = p->pSrc;
   68583     sNC.pNext = pOuterNC;
   68584 
   68585     /* Resolve names in the result set. */
   68586     pEList = p->pEList;
   68587     assert( pEList!=0 );
   68588     for(i=0; i<pEList->nExpr; i++){
   68589       Expr *pX = pEList->a[i].pExpr;
   68590       if( sqlite3ResolveExprNames(&sNC, pX) ){
   68591         return WRC_Abort;
   68592       }
   68593     }
   68594 
   68595     /* Recursively resolve names in all subqueries
   68596     */
   68597     for(i=0; i<p->pSrc->nSrc; i++){
   68598       struct SrcList_item *pItem = &p->pSrc->a[i];
   68599       if( pItem->pSelect ){
   68600         const char *zSavedContext = pParse->zAuthContext;
   68601         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
   68602         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
   68603         pParse->zAuthContext = zSavedContext;
   68604         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
   68605       }
   68606     }
   68607 
   68608     /* If there are no aggregate functions in the result-set, and no GROUP BY
   68609     ** expression, do not allow aggregates in any of the other expressions.
   68610     */
   68611     assert( (p->selFlags & SF_Aggregate)==0 );
   68612     pGroupBy = p->pGroupBy;
   68613     if( pGroupBy || sNC.hasAgg ){
   68614       p->selFlags |= SF_Aggregate;
   68615     }else{
   68616       sNC.allowAgg = 0;
   68617     }
   68618 
   68619     /* If a HAVING clause is present, then there must be a GROUP BY clause.
   68620     */
   68621     if( p->pHaving && !pGroupBy ){
   68622       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
   68623       return WRC_Abort;
   68624     }
   68625 
   68626     /* Add the expression list to the name-context before parsing the
   68627     ** other expressions in the SELECT statement. This is so that
   68628     ** expressions in the WHERE clause (etc.) can refer to expressions by
   68629     ** aliases in the result set.
   68630     **
   68631     ** Minor point: If this is the case, then the expression will be
   68632     ** re-evaluated for each reference to it.
   68633     */
   68634     sNC.pEList = p->pEList;
   68635     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
   68636        sqlite3ResolveExprNames(&sNC, p->pHaving)
   68637     ){
   68638       return WRC_Abort;
   68639     }
   68640 
   68641     /* The ORDER BY and GROUP BY clauses may not refer to terms in
   68642     ** outer queries
   68643     */
   68644     sNC.pNext = 0;
   68645     sNC.allowAgg = 1;
   68646 
   68647     /* Process the ORDER BY clause for singleton SELECT statements.
   68648     ** The ORDER BY clause for compounds SELECT statements is handled
   68649     ** below, after all of the result-sets for all of the elements of
   68650     ** the compound have been resolved.
   68651     */
   68652     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
   68653       return WRC_Abort;
   68654     }
   68655     if( db->mallocFailed ){
   68656       return WRC_Abort;
   68657     }
   68658 
   68659     /* Resolve the GROUP BY clause.  At the same time, make sure
   68660     ** the GROUP BY clause does not contain aggregate functions.
   68661     */
   68662     if( pGroupBy ){
   68663       struct ExprList_item *pItem;
   68664 
   68665       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
   68666         return WRC_Abort;
   68667       }
   68668       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
   68669         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
   68670           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
   68671               "the GROUP BY clause");
   68672           return WRC_Abort;
   68673         }
   68674       }
   68675     }
   68676 
   68677     /* Advance to the next term of the compound
   68678     */
   68679     p = p->pPrior;
   68680     nCompound++;
   68681   }
   68682 
   68683   /* Resolve the ORDER BY on a compound SELECT after all terms of
   68684   ** the compound have been resolved.
   68685   */
   68686   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
   68687     return WRC_Abort;
   68688   }
   68689 
   68690   return WRC_Prune;
   68691 }
   68692 
   68693 /*
   68694 ** This routine walks an expression tree and resolves references to
   68695 ** table columns and result-set columns.  At the same time, do error
   68696 ** checking on function usage and set a flag if any aggregate functions
   68697 ** are seen.
   68698 **
   68699 ** To resolve table columns references we look for nodes (or subtrees) of the
   68700 ** form X.Y.Z or Y.Z or just Z where
   68701 **
   68702 **      X:   The name of a database.  Ex:  "main" or "temp" or
   68703 **           the symbolic name assigned to an ATTACH-ed database.
   68704 **
   68705 **      Y:   The name of a table in a FROM clause.  Or in a trigger
   68706 **           one of the special names "old" or "new".
   68707 **
   68708 **      Z:   The name of a column in table Y.
   68709 **
   68710 ** The node at the root of the subtree is modified as follows:
   68711 **
   68712 **    Expr.op        Changed to TK_COLUMN
   68713 **    Expr.pTab      Points to the Table object for X.Y
   68714 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
   68715 **    Expr.iTable    The VDBE cursor number for X.Y
   68716 **
   68717 **
   68718 ** To resolve result-set references, look for expression nodes of the
   68719 ** form Z (with no X and Y prefix) where the Z matches the right-hand
   68720 ** size of an AS clause in the result-set of a SELECT.  The Z expression
   68721 ** is replaced by a copy of the left-hand side of the result-set expression.
   68722 ** Table-name and function resolution occurs on the substituted expression
   68723 ** tree.  For example, in:
   68724 **
   68725 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
   68726 **
   68727 ** The "x" term of the order by is replaced by "a+b" to render:
   68728 **
   68729 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
   68730 **
   68731 ** Function calls are checked to make sure that the function is
   68732 ** defined and that the correct number of arguments are specified.
   68733 ** If the function is an aggregate function, then the pNC->hasAgg is
   68734 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
   68735 ** If an expression contains aggregate functions then the EP_Agg
   68736 ** property on the expression is set.
   68737 **
   68738 ** An error message is left in pParse if anything is amiss.  The number
   68739 ** if errors is returned.
   68740 */
   68741 SQLITE_PRIVATE int sqlite3ResolveExprNames(
   68742   NameContext *pNC,       /* Namespace to resolve expressions in. */
   68743   Expr *pExpr             /* The expression to be analyzed. */
   68744 ){
   68745   int savedHasAgg;
   68746   Walker w;
   68747 
   68748   if( pExpr==0 ) return 0;
   68749 #if SQLITE_MAX_EXPR_DEPTH>0
   68750   {
   68751     Parse *pParse = pNC->pParse;
   68752     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
   68753       return 1;
   68754     }
   68755     pParse->nHeight += pExpr->nHeight;
   68756   }
   68757 #endif
   68758   savedHasAgg = pNC->hasAgg;
   68759   pNC->hasAgg = 0;
   68760   w.xExprCallback = resolveExprStep;
   68761   w.xSelectCallback = resolveSelectStep;
   68762   w.pParse = pNC->pParse;
   68763   w.u.pNC = pNC;
   68764   sqlite3WalkExpr(&w, pExpr);
   68765 #if SQLITE_MAX_EXPR_DEPTH>0
   68766   pNC->pParse->nHeight -= pExpr->nHeight;
   68767 #endif
   68768   if( pNC->nErr>0 || w.pParse->nErr>0 ){
   68769     ExprSetProperty(pExpr, EP_Error);
   68770   }
   68771   if( pNC->hasAgg ){
   68772     ExprSetProperty(pExpr, EP_Agg);
   68773   }else if( savedHasAgg ){
   68774     pNC->hasAgg = 1;
   68775   }
   68776   return ExprHasProperty(pExpr, EP_Error);
   68777 }
   68778 
   68779 
   68780 /*
   68781 ** Resolve all names in all expressions of a SELECT and in all
   68782 ** decendents of the SELECT, including compounds off of p->pPrior,
   68783 ** subqueries in expressions, and subqueries used as FROM clause
   68784 ** terms.
   68785 **
   68786 ** See sqlite3ResolveExprNames() for a description of the kinds of
   68787 ** transformations that occur.
   68788 **
   68789 ** All SELECT statements should have been expanded using
   68790 ** sqlite3SelectExpand() prior to invoking this routine.
   68791 */
   68792 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
   68793   Parse *pParse,         /* The parser context */
   68794   Select *p,             /* The SELECT statement being coded. */
   68795   NameContext *pOuterNC  /* Name context for parent SELECT statement */
   68796 ){
   68797   Walker w;
   68798 
   68799   assert( p!=0 );
   68800   w.xExprCallback = resolveExprStep;
   68801   w.xSelectCallback = resolveSelectStep;
   68802   w.pParse = pParse;
   68803   w.u.pNC = pOuterNC;
   68804   sqlite3WalkSelect(&w, p);
   68805 }
   68806 
   68807 /************** End of resolve.c *********************************************/
   68808 /************** Begin file expr.c ********************************************/
   68809 /*
   68810 ** 2001 September 15
   68811 **
   68812 ** The author disclaims copyright to this source code.  In place of
   68813 ** a legal notice, here is a blessing:
   68814 **
   68815 **    May you do good and not evil.
   68816 **    May you find forgiveness for yourself and forgive others.
   68817 **    May you share freely, never taking more than you give.
   68818 **
   68819 *************************************************************************
   68820 ** This file contains routines used for analyzing expressions and
   68821 ** for generating VDBE code that evaluates expressions in SQLite.
   68822 */
   68823 
   68824 /*
   68825 ** Return the 'affinity' of the expression pExpr if any.
   68826 **
   68827 ** If pExpr is a column, a reference to a column via an 'AS' alias,
   68828 ** or a sub-select with a column as the return value, then the
   68829 ** affinity of that column is returned. Otherwise, 0x00 is returned,
   68830 ** indicating no affinity for the expression.
   68831 **
   68832 ** i.e. the WHERE clause expresssions in the following statements all
   68833 ** have an affinity:
   68834 **
   68835 ** CREATE TABLE t1(a);
   68836 ** SELECT * FROM t1 WHERE a;
   68837 ** SELECT a AS b FROM t1 WHERE b;
   68838 ** SELECT * FROM t1 WHERE (select a from t1);
   68839 */
   68840 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
   68841   int op = pExpr->op;
   68842   if( op==TK_SELECT ){
   68843     assert( pExpr->flags&EP_xIsSelect );
   68844     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   68845   }
   68846 #ifndef SQLITE_OMIT_CAST
   68847   if( op==TK_CAST ){
   68848     assert( !ExprHasProperty(pExpr, EP_IntValue) );
   68849     return sqlite3AffinityType(pExpr->u.zToken);
   68850   }
   68851 #endif
   68852   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
   68853    && pExpr->pTab!=0
   68854   ){
   68855     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
   68856     ** a TK_COLUMN but was previously evaluated and cached in a register */
   68857     int j = pExpr->iColumn;
   68858     if( j<0 ) return SQLITE_AFF_INTEGER;
   68859     assert( pExpr->pTab && j<pExpr->pTab->nCol );
   68860     return pExpr->pTab->aCol[j].affinity;
   68861   }
   68862   return pExpr->affinity;
   68863 }
   68864 
   68865 /*
   68866 ** Set the explicit collating sequence for an expression to the
   68867 ** collating sequence supplied in the second argument.
   68868 */
   68869 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
   68870   if( pExpr && pColl ){
   68871     pExpr->pColl = pColl;
   68872     pExpr->flags |= EP_ExpCollate;
   68873   }
   68874   return pExpr;
   68875 }
   68876 
   68877 /*
   68878 ** Set the collating sequence for expression pExpr to be the collating
   68879 ** sequence named by pToken.   Return a pointer to the revised expression.
   68880 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
   68881 ** flag.  An explicit collating sequence will override implicit
   68882 ** collating sequences.
   68883 */
   68884 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
   68885   char *zColl = 0;            /* Dequoted name of collation sequence */
   68886   CollSeq *pColl;
   68887   sqlite3 *db = pParse->db;
   68888   zColl = sqlite3NameFromToken(db, pCollName);
   68889   pColl = sqlite3LocateCollSeq(pParse, zColl);
   68890   sqlite3ExprSetColl(pExpr, pColl);
   68891   sqlite3DbFree(db, zColl);
   68892   return pExpr;
   68893 }
   68894 
   68895 /*
   68896 ** Return the default collation sequence for the expression pExpr. If
   68897 ** there is no default collation type, return 0.
   68898 */
   68899 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
   68900   CollSeq *pColl = 0;
   68901   Expr *p = pExpr;
   68902   while( ALWAYS(p) ){
   68903     int op;
   68904     pColl = p->pColl;
   68905     if( pColl ) break;
   68906     op = p->op;
   68907     if( p->pTab!=0 && (
   68908         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
   68909     )){
   68910       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
   68911       ** a TK_COLUMN but was previously evaluated and cached in a register */
   68912       const char *zColl;
   68913       int j = p->iColumn;
   68914       if( j>=0 ){
   68915         sqlite3 *db = pParse->db;
   68916         zColl = p->pTab->aCol[j].zColl;
   68917         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   68918         pExpr->pColl = pColl;
   68919       }
   68920       break;
   68921     }
   68922     if( op!=TK_CAST && op!=TK_UPLUS ){
   68923       break;
   68924     }
   68925     p = p->pLeft;
   68926   }
   68927   if( sqlite3CheckCollSeq(pParse, pColl) ){
   68928     pColl = 0;
   68929   }
   68930   return pColl;
   68931 }
   68932 
   68933 /*
   68934 ** pExpr is an operand of a comparison operator.  aff2 is the
   68935 ** type affinity of the other operand.  This routine returns the
   68936 ** type affinity that should be used for the comparison operator.
   68937 */
   68938 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
   68939   char aff1 = sqlite3ExprAffinity(pExpr);
   68940   if( aff1 && aff2 ){
   68941     /* Both sides of the comparison are columns. If one has numeric
   68942     ** affinity, use that. Otherwise use no affinity.
   68943     */
   68944     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
   68945       return SQLITE_AFF_NUMERIC;
   68946     }else{
   68947       return SQLITE_AFF_NONE;
   68948     }
   68949   }else if( !aff1 && !aff2 ){
   68950     /* Neither side of the comparison is a column.  Compare the
   68951     ** results directly.
   68952     */
   68953     return SQLITE_AFF_NONE;
   68954   }else{
   68955     /* One side is a column, the other is not. Use the columns affinity. */
   68956     assert( aff1==0 || aff2==0 );
   68957     return (aff1 + aff2);
   68958   }
   68959 }
   68960 
   68961 /*
   68962 ** pExpr is a comparison operator.  Return the type affinity that should
   68963 ** be applied to both operands prior to doing the comparison.
   68964 */
   68965 static char comparisonAffinity(Expr *pExpr){
   68966   char aff;
   68967   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
   68968           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
   68969           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
   68970   assert( pExpr->pLeft );
   68971   aff = sqlite3ExprAffinity(pExpr->pLeft);
   68972   if( pExpr->pRight ){
   68973     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
   68974   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   68975     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
   68976   }else if( !aff ){
   68977     aff = SQLITE_AFF_NONE;
   68978   }
   68979   return aff;
   68980 }
   68981 
   68982 /*
   68983 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
   68984 ** idx_affinity is the affinity of an indexed column. Return true
   68985 ** if the index with affinity idx_affinity may be used to implement
   68986 ** the comparison in pExpr.
   68987 */
   68988 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
   68989   char aff = comparisonAffinity(pExpr);
   68990   switch( aff ){
   68991     case SQLITE_AFF_NONE:
   68992       return 1;
   68993     case SQLITE_AFF_TEXT:
   68994       return idx_affinity==SQLITE_AFF_TEXT;
   68995     default:
   68996       return sqlite3IsNumericAffinity(idx_affinity);
   68997   }
   68998 }
   68999 
   69000 /*
   69001 ** Return the P5 value that should be used for a binary comparison
   69002 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
   69003 */
   69004 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
   69005   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   69006   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   69007   return aff;
   69008 }
   69009 
   69010 /*
   69011 ** Return a pointer to the collation sequence that should be used by
   69012 ** a binary comparison operator comparing pLeft and pRight.
   69013 **
   69014 ** If the left hand expression has a collating sequence type, then it is
   69015 ** used. Otherwise the collation sequence for the right hand expression
   69016 ** is used, or the default (BINARY) if neither expression has a collating
   69017 ** type.
   69018 **
   69019 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
   69020 ** it is not considered.
   69021 */
   69022 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   69023   Parse *pParse,
   69024   Expr *pLeft,
   69025   Expr *pRight
   69026 ){
   69027   CollSeq *pColl;
   69028   assert( pLeft );
   69029   if( pLeft->flags & EP_ExpCollate ){
   69030     assert( pLeft->pColl );
   69031     pColl = pLeft->pColl;
   69032   }else if( pRight && pRight->flags & EP_ExpCollate ){
   69033     assert( pRight->pColl );
   69034     pColl = pRight->pColl;
   69035   }else{
   69036     pColl = sqlite3ExprCollSeq(pParse, pLeft);
   69037     if( !pColl ){
   69038       pColl = sqlite3ExprCollSeq(pParse, pRight);
   69039     }
   69040   }
   69041   return pColl;
   69042 }
   69043 
   69044 /*
   69045 ** Generate code for a comparison operator.
   69046 */
   69047 static int codeCompare(
   69048   Parse *pParse,    /* The parsing (and code generating) context */
   69049   Expr *pLeft,      /* The left operand */
   69050   Expr *pRight,     /* The right operand */
   69051   int opcode,       /* The comparison opcode */
   69052   int in1, int in2, /* Register holding operands */
   69053   int dest,         /* Jump here if true.  */
   69054   int jumpIfNull    /* If true, jump if either operand is NULL */
   69055 ){
   69056   int p5;
   69057   int addr;
   69058   CollSeq *p4;
   69059 
   69060   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
   69061   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   69062   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
   69063                            (void*)p4, P4_COLLSEQ);
   69064   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
   69065   return addr;
   69066 }
   69067 
   69068 #if SQLITE_MAX_EXPR_DEPTH>0
   69069 /*
   69070 ** Check that argument nHeight is less than or equal to the maximum
   69071 ** expression depth allowed. If it is not, leave an error message in
   69072 ** pParse.
   69073 */
   69074 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   69075   int rc = SQLITE_OK;
   69076   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   69077   if( nHeight>mxHeight ){
   69078     sqlite3ErrorMsg(pParse,
   69079        "Expression tree is too large (maximum depth %d)", mxHeight
   69080     );
   69081     rc = SQLITE_ERROR;
   69082   }
   69083   return rc;
   69084 }
   69085 
   69086 /* The following three functions, heightOfExpr(), heightOfExprList()
   69087 ** and heightOfSelect(), are used to determine the maximum height
   69088 ** of any expression tree referenced by the structure passed as the
   69089 ** first argument.
   69090 **
   69091 ** If this maximum height is greater than the current value pointed
   69092 ** to by pnHeight, the second parameter, then set *pnHeight to that
   69093 ** value.
   69094 */
   69095 static void heightOfExpr(Expr *p, int *pnHeight){
   69096   if( p ){
   69097     if( p->nHeight>*pnHeight ){
   69098       *pnHeight = p->nHeight;
   69099     }
   69100   }
   69101 }
   69102 static void heightOfExprList(ExprList *p, int *pnHeight){
   69103   if( p ){
   69104     int i;
   69105     for(i=0; i<p->nExpr; i++){
   69106       heightOfExpr(p->a[i].pExpr, pnHeight);
   69107     }
   69108   }
   69109 }
   69110 static void heightOfSelect(Select *p, int *pnHeight){
   69111   if( p ){
   69112     heightOfExpr(p->pWhere, pnHeight);
   69113     heightOfExpr(p->pHaving, pnHeight);
   69114     heightOfExpr(p->pLimit, pnHeight);
   69115     heightOfExpr(p->pOffset, pnHeight);
   69116     heightOfExprList(p->pEList, pnHeight);
   69117     heightOfExprList(p->pGroupBy, pnHeight);
   69118     heightOfExprList(p->pOrderBy, pnHeight);
   69119     heightOfSelect(p->pPrior, pnHeight);
   69120   }
   69121 }
   69122 
   69123 /*
   69124 ** Set the Expr.nHeight variable in the structure passed as an
   69125 ** argument. An expression with no children, Expr.pList or
   69126 ** Expr.pSelect member has a height of 1. Any other expression
   69127 ** has a height equal to the maximum height of any other
   69128 ** referenced Expr plus one.
   69129 */
   69130 static void exprSetHeight(Expr *p){
   69131   int nHeight = 0;
   69132   heightOfExpr(p->pLeft, &nHeight);
   69133   heightOfExpr(p->pRight, &nHeight);
   69134   if( ExprHasProperty(p, EP_xIsSelect) ){
   69135     heightOfSelect(p->x.pSelect, &nHeight);
   69136   }else{
   69137     heightOfExprList(p->x.pList, &nHeight);
   69138   }
   69139   p->nHeight = nHeight + 1;
   69140 }
   69141 
   69142 /*
   69143 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
   69144 ** the height is greater than the maximum allowed expression depth,
   69145 ** leave an error in pParse.
   69146 */
   69147 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
   69148   exprSetHeight(p);
   69149   sqlite3ExprCheckHeight(pParse, p->nHeight);
   69150 }
   69151 
   69152 /*
   69153 ** Return the maximum height of any expression tree referenced
   69154 ** by the select statement passed as an argument.
   69155 */
   69156 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
   69157   int nHeight = 0;
   69158   heightOfSelect(p, &nHeight);
   69159   return nHeight;
   69160 }
   69161 #else
   69162   #define exprSetHeight(y)
   69163 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
   69164 
   69165 /*
   69166 ** This routine is the core allocator for Expr nodes.
   69167 **
   69168 ** Construct a new expression node and return a pointer to it.  Memory
   69169 ** for this node and for the pToken argument is a single allocation
   69170 ** obtained from sqlite3DbMalloc().  The calling function
   69171 ** is responsible for making sure the node eventually gets freed.
   69172 **
   69173 ** If dequote is true, then the token (if it exists) is dequoted.
   69174 ** If dequote is false, no dequoting is performance.  The deQuote
   69175 ** parameter is ignored if pToken is NULL or if the token does not
   69176 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
   69177 ** then the EP_DblQuoted flag is set on the expression node.
   69178 **
   69179 ** Special case:  If op==TK_INTEGER and pToken points to a string that
   69180 ** can be translated into a 32-bit integer, then the token is not
   69181 ** stored in u.zToken.  Instead, the integer values is written
   69182 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
   69183 ** is allocated to hold the integer text and the dequote flag is ignored.
   69184 */
   69185 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
   69186   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   69187   int op,                 /* Expression opcode */
   69188   const Token *pToken,    /* Token argument.  Might be NULL */
   69189   int dequote             /* True to dequote */
   69190 ){
   69191   Expr *pNew;
   69192   int nExtra = 0;
   69193   int iValue = 0;
   69194 
   69195   if( pToken ){
   69196     if( op!=TK_INTEGER || pToken->z==0
   69197           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   69198       nExtra = pToken->n+1;
   69199     }
   69200   }
   69201   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
   69202   if( pNew ){
   69203     pNew->op = (u8)op;
   69204     pNew->iAgg = -1;
   69205     if( pToken ){
   69206       if( nExtra==0 ){
   69207         pNew->flags |= EP_IntValue;
   69208         pNew->u.iValue = iValue;
   69209       }else{
   69210         int c;
   69211         pNew->u.zToken = (char*)&pNew[1];
   69212         memcpy(pNew->u.zToken, pToken->z, pToken->n);
   69213         pNew->u.zToken[pToken->n] = 0;
   69214         if( dequote && nExtra>=3
   69215              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
   69216           sqlite3Dequote(pNew->u.zToken);
   69217           if( c=='"' ) pNew->flags |= EP_DblQuoted;
   69218         }
   69219       }
   69220     }
   69221 #if SQLITE_MAX_EXPR_DEPTH>0
   69222     pNew->nHeight = 1;
   69223 #endif
   69224   }
   69225   return pNew;
   69226 }
   69227 
   69228 /*
   69229 ** Allocate a new expression node from a zero-terminated token that has
   69230 ** already been dequoted.
   69231 */
   69232 SQLITE_PRIVATE Expr *sqlite3Expr(
   69233   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
   69234   int op,                 /* Expression opcode */
   69235   const char *zToken      /* Token argument.  Might be NULL */
   69236 ){
   69237   Token x;
   69238   x.z = zToken;
   69239   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
   69240   return sqlite3ExprAlloc(db, op, &x, 0);
   69241 }
   69242 
   69243 /*
   69244 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
   69245 **
   69246 ** If pRoot==NULL that means that a memory allocation error has occurred.
   69247 ** In that case, delete the subtrees pLeft and pRight.
   69248 */
   69249 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
   69250   sqlite3 *db,
   69251   Expr *pRoot,
   69252   Expr *pLeft,
   69253   Expr *pRight
   69254 ){
   69255   if( pRoot==0 ){
   69256     assert( db->mallocFailed );
   69257     sqlite3ExprDelete(db, pLeft);
   69258     sqlite3ExprDelete(db, pRight);
   69259   }else{
   69260     if( pRight ){
   69261       pRoot->pRight = pRight;
   69262       if( pRight->flags & EP_ExpCollate ){
   69263         pRoot->flags |= EP_ExpCollate;
   69264         pRoot->pColl = pRight->pColl;
   69265       }
   69266     }
   69267     if( pLeft ){
   69268       pRoot->pLeft = pLeft;
   69269       if( pLeft->flags & EP_ExpCollate ){
   69270         pRoot->flags |= EP_ExpCollate;
   69271         pRoot->pColl = pLeft->pColl;
   69272       }
   69273     }
   69274     exprSetHeight(pRoot);
   69275   }
   69276 }
   69277 
   69278 /*
   69279 ** Allocate a Expr node which joins as many as two subtrees.
   69280 **
   69281 ** One or both of the subtrees can be NULL.  Return a pointer to the new
   69282 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
   69283 ** free the subtrees and return NULL.
   69284 */
   69285 SQLITE_PRIVATE Expr *sqlite3PExpr(
   69286   Parse *pParse,          /* Parsing context */
   69287   int op,                 /* Expression opcode */
   69288   Expr *pLeft,            /* Left operand */
   69289   Expr *pRight,           /* Right operand */
   69290   const Token *pToken     /* Argument token */
   69291 ){
   69292   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
   69293   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
   69294   if( p ) {
   69295     sqlite3ExprCheckHeight(pParse, p->nHeight);
   69296   }
   69297   return p;
   69298 }
   69299 
   69300 /*
   69301 ** Join two expressions using an AND operator.  If either expression is
   69302 ** NULL, then just return the other expression.
   69303 */
   69304 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
   69305   if( pLeft==0 ){
   69306     return pRight;
   69307   }else if( pRight==0 ){
   69308     return pLeft;
   69309   }else{
   69310     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
   69311     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
   69312     return pNew;
   69313   }
   69314 }
   69315 
   69316 /*
   69317 ** Construct a new expression node for a function with multiple
   69318 ** arguments.
   69319 */
   69320 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
   69321   Expr *pNew;
   69322   sqlite3 *db = pParse->db;
   69323   assert( pToken );
   69324   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
   69325   if( pNew==0 ){
   69326     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
   69327     return 0;
   69328   }
   69329   pNew->x.pList = pList;
   69330   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   69331   sqlite3ExprSetHeight(pParse, pNew);
   69332   return pNew;
   69333 }
   69334 
   69335 /*
   69336 ** Assign a variable number to an expression that encodes a wildcard
   69337 ** in the original SQL statement.
   69338 **
   69339 ** Wildcards consisting of a single "?" are assigned the next sequential
   69340 ** variable number.
   69341 **
   69342 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
   69343 ** sure "nnn" is not too be to avoid a denial of service attack when
   69344 ** the SQL statement comes from an external source.
   69345 **
   69346 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
   69347 ** as the previous instance of the same wildcard.  Or if this is the first
   69348 ** instance of the wildcard, the next sequenial variable number is
   69349 ** assigned.
   69350 */
   69351 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
   69352   sqlite3 *db = pParse->db;
   69353   const char *z;
   69354 
   69355   if( pExpr==0 ) return;
   69356   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
   69357   z = pExpr->u.zToken;
   69358   assert( z!=0 );
   69359   assert( z[0]!=0 );
   69360   if( z[1]==0 ){
   69361     /* Wildcard of the form "?".  Assign the next variable number */
   69362     assert( z[0]=='?' );
   69363     pExpr->iColumn = (ynVar)(++pParse->nVar);
   69364   }else if( z[0]=='?' ){
   69365     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
   69366     ** use it as the variable number */
   69367     i64 i;
   69368     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
   69369     pExpr->iColumn = (ynVar)i;
   69370     testcase( i==0 );
   69371     testcase( i==1 );
   69372     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
   69373     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
   69374     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   69375       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
   69376           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
   69377     }
   69378     if( i>pParse->nVar ){
   69379       pParse->nVar = (int)i;
   69380     }
   69381   }else{
   69382     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
   69383     ** number as the prior appearance of the same name, or if the name
   69384     ** has never appeared before, reuse the same variable number
   69385     */
   69386     int i;
   69387     u32 n;
   69388     n = sqlite3Strlen30(z);
   69389     for(i=0; i<pParse->nVarExpr; i++){
   69390       Expr *pE = pParse->apVarExpr[i];
   69391       assert( pE!=0 );
   69392       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
   69393         pExpr->iColumn = pE->iColumn;
   69394         break;
   69395       }
   69396     }
   69397     if( i>=pParse->nVarExpr ){
   69398       pExpr->iColumn = (ynVar)(++pParse->nVar);
   69399       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
   69400         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
   69401         pParse->apVarExpr =
   69402             sqlite3DbReallocOrFree(
   69403               db,
   69404               pParse->apVarExpr,
   69405               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
   69406             );
   69407       }
   69408       if( !db->mallocFailed ){
   69409         assert( pParse->apVarExpr!=0 );
   69410         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
   69411       }
   69412     }
   69413   }
   69414   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
   69415     sqlite3ErrorMsg(pParse, "too many SQL variables");
   69416   }
   69417 }
   69418 
   69419 /*
   69420 ** Recursively delete an expression tree.
   69421 */
   69422 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
   69423   if( p==0 ) return;
   69424   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   69425     sqlite3ExprDelete(db, p->pLeft);
   69426     sqlite3ExprDelete(db, p->pRight);
   69427     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
   69428       sqlite3DbFree(db, p->u.zToken);
   69429     }
   69430     if( ExprHasProperty(p, EP_xIsSelect) ){
   69431       sqlite3SelectDelete(db, p->x.pSelect);
   69432     }else{
   69433       sqlite3ExprListDelete(db, p->x.pList);
   69434     }
   69435   }
   69436   if( !ExprHasProperty(p, EP_Static) ){
   69437     sqlite3DbFree(db, p);
   69438   }
   69439 }
   69440 
   69441 /*
   69442 ** Return the number of bytes allocated for the expression structure
   69443 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
   69444 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
   69445 */
   69446 static int exprStructSize(Expr *p){
   69447   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
   69448   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
   69449   return EXPR_FULLSIZE;
   69450 }
   69451 
   69452 /*
   69453 ** The dupedExpr*Size() routines each return the number of bytes required
   69454 ** to store a copy of an expression or expression tree.  They differ in
   69455 ** how much of the tree is measured.
   69456 **
   69457 **     dupedExprStructSize()     Size of only the Expr structure
   69458 **     dupedExprNodeSize()       Size of Expr + space for token
   69459 **     dupedExprSize()           Expr + token + subtree components
   69460 **
   69461 ***************************************************************************
   69462 **
   69463 ** The dupedExprStructSize() function returns two values OR-ed together:
   69464 ** (1) the space required for a copy of the Expr structure only and
   69465 ** (2) the EP_xxx flags that indicate what the structure size should be.
   69466 ** The return values is always one of:
   69467 **
   69468 **      EXPR_FULLSIZE
   69469 **      EXPR_REDUCEDSIZE   | EP_Reduced
   69470 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
   69471 **
   69472 ** The size of the structure can be found by masking the return value
   69473 ** of this routine with 0xfff.  The flags can be found by masking the
   69474 ** return value with EP_Reduced|EP_TokenOnly.
   69475 **
   69476 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
   69477 ** (unreduced) Expr objects as they or originally constructed by the parser.
   69478 ** During expression analysis, extra information is computed and moved into
   69479 ** later parts of teh Expr object and that extra information might get chopped
   69480 ** off if the expression is reduced.  Note also that it does not work to
   69481 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
   69482 ** to reduce a pristine expression tree from the parser.  The implementation
   69483 ** of dupedExprStructSize() contain multiple assert() statements that attempt
   69484 ** to enforce this constraint.
   69485 */
   69486 static int dupedExprStructSize(Expr *p, int flags){
   69487   int nSize;
   69488   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   69489   if( 0==(flags&EXPRDUP_REDUCE) ){
   69490     nSize = EXPR_FULLSIZE;
   69491   }else{
   69492     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   69493     assert( !ExprHasProperty(p, EP_FromJoin) );
   69494     assert( (p->flags2 & EP2_MallocedToken)==0 );
   69495     assert( (p->flags2 & EP2_Irreducible)==0 );
   69496     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
   69497       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
   69498     }else{
   69499       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
   69500     }
   69501   }
   69502   return nSize;
   69503 }
   69504 
   69505 /*
   69506 ** This function returns the space in bytes required to store the copy
   69507 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
   69508 ** string is defined.)
   69509 */
   69510 static int dupedExprNodeSize(Expr *p, int flags){
   69511   int nByte = dupedExprStructSize(p, flags) & 0xfff;
   69512   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   69513     nByte += sqlite3Strlen30(p->u.zToken)+1;
   69514   }
   69515   return ROUND8(nByte);
   69516 }
   69517 
   69518 /*
   69519 ** Return the number of bytes required to create a duplicate of the
   69520 ** expression passed as the first argument. The second argument is a
   69521 ** mask containing EXPRDUP_XXX flags.
   69522 **
   69523 ** The value returned includes space to create a copy of the Expr struct
   69524 ** itself and the buffer referred to by Expr.u.zToken, if any.
   69525 **
   69526 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
   69527 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
   69528 ** and Expr.pRight variables (but not for any structures pointed to or
   69529 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
   69530 */
   69531 static int dupedExprSize(Expr *p, int flags){
   69532   int nByte = 0;
   69533   if( p ){
   69534     nByte = dupedExprNodeSize(p, flags);
   69535     if( flags&EXPRDUP_REDUCE ){
   69536       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
   69537     }
   69538   }
   69539   return nByte;
   69540 }
   69541 
   69542 /*
   69543 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
   69544 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
   69545 ** to store the copy of expression p, the copies of p->u.zToken
   69546 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   69547 ** if any. Before returning, *pzBuffer is set to the first byte passed the
   69548 ** portion of the buffer copied into by this function.
   69549 */
   69550 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   69551   Expr *pNew = 0;                      /* Value to return */
   69552   if( p ){
   69553     const int isReduced = (flags&EXPRDUP_REDUCE);
   69554     u8 *zAlloc;
   69555     u32 staticFlag = 0;
   69556 
   69557     assert( pzBuffer==0 || isReduced );
   69558 
   69559     /* Figure out where to write the new Expr structure. */
   69560     if( pzBuffer ){
   69561       zAlloc = *pzBuffer;
   69562       staticFlag = EP_Static;
   69563     }else{
   69564       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
   69565     }
   69566     pNew = (Expr *)zAlloc;
   69567 
   69568     if( pNew ){
   69569       /* Set nNewSize to the size allocated for the structure pointed to
   69570       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   69571       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
   69572       ** by the copy of the p->u.zToken string (if any).
   69573       */
   69574       const unsigned nStructSize = dupedExprStructSize(p, flags);
   69575       const int nNewSize = nStructSize & 0xfff;
   69576       int nToken;
   69577       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   69578         nToken = sqlite3Strlen30(p->u.zToken) + 1;
   69579       }else{
   69580         nToken = 0;
   69581       }
   69582       if( isReduced ){
   69583         assert( ExprHasProperty(p, EP_Reduced)==0 );
   69584         memcpy(zAlloc, p, nNewSize);
   69585       }else{
   69586         int nSize = exprStructSize(p);
   69587         memcpy(zAlloc, p, nSize);
   69588         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
   69589       }
   69590 
   69591       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
   69592       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
   69593       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
   69594       pNew->flags |= staticFlag;
   69595 
   69596       /* Copy the p->u.zToken string, if any. */
   69597       if( nToken ){
   69598         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
   69599         memcpy(zToken, p->u.zToken, nToken);
   69600       }
   69601 
   69602       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
   69603         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
   69604         if( ExprHasProperty(p, EP_xIsSelect) ){
   69605           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
   69606         }else{
   69607           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
   69608         }
   69609       }
   69610 
   69611       /* Fill in pNew->pLeft and pNew->pRight. */
   69612       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
   69613         zAlloc += dupedExprNodeSize(p, flags);
   69614         if( ExprHasProperty(pNew, EP_Reduced) ){
   69615           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
   69616           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
   69617         }
   69618         if( pzBuffer ){
   69619           *pzBuffer = zAlloc;
   69620         }
   69621       }else{
   69622         pNew->flags2 = 0;
   69623         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
   69624           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
   69625           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
   69626         }
   69627       }
   69628 
   69629     }
   69630   }
   69631   return pNew;
   69632 }
   69633 
   69634 /*
   69635 ** The following group of routines make deep copies of expressions,
   69636 ** expression lists, ID lists, and select statements.  The copies can
   69637 ** be deleted (by being passed to their respective ...Delete() routines)
   69638 ** without effecting the originals.
   69639 **
   69640 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
   69641 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
   69642 ** by subsequent calls to sqlite*ListAppend() routines.
   69643 **
   69644 ** Any tables that the SrcList might point to are not duplicated.
   69645 **
   69646 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
   69647 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
   69648 ** truncated version of the usual Expr structure that will be stored as
   69649 ** part of the in-memory representation of the database schema.
   69650 */
   69651 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
   69652   return exprDup(db, p, flags, 0);
   69653 }
   69654 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   69655   ExprList *pNew;
   69656   struct ExprList_item *pItem, *pOldItem;
   69657   int i;
   69658   if( p==0 ) return 0;
   69659   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   69660   if( pNew==0 ) return 0;
   69661   pNew->iECursor = 0;
   69662   pNew->nExpr = pNew->nAlloc = p->nExpr;
   69663   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
   69664   if( pItem==0 ){
   69665     sqlite3DbFree(db, pNew);
   69666     return 0;
   69667   }
   69668   pOldItem = p->a;
   69669   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   69670     Expr *pOldExpr = pOldItem->pExpr;
   69671     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   69672     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   69673     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   69674     pItem->sortOrder = pOldItem->sortOrder;
   69675     pItem->done = 0;
   69676     pItem->iCol = pOldItem->iCol;
   69677     pItem->iAlias = pOldItem->iAlias;
   69678   }
   69679   return pNew;
   69680 }
   69681 
   69682 /*
   69683 ** If cursors, triggers, views and subqueries are all omitted from
   69684 ** the build, then none of the following routines, except for
   69685 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
   69686 ** called with a NULL argument.
   69687 */
   69688 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
   69689  || !defined(SQLITE_OMIT_SUBQUERY)
   69690 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
   69691   SrcList *pNew;
   69692   int i;
   69693   int nByte;
   69694   if( p==0 ) return 0;
   69695   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
   69696   pNew = sqlite3DbMallocRaw(db, nByte );
   69697   if( pNew==0 ) return 0;
   69698   pNew->nSrc = pNew->nAlloc = p->nSrc;
   69699   for(i=0; i<p->nSrc; i++){
   69700     struct SrcList_item *pNewItem = &pNew->a[i];
   69701     struct SrcList_item *pOldItem = &p->a[i];
   69702     Table *pTab;
   69703     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
   69704     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   69705     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
   69706     pNewItem->jointype = pOldItem->jointype;
   69707     pNewItem->iCursor = pOldItem->iCursor;
   69708     pNewItem->isPopulated = pOldItem->isPopulated;
   69709     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
   69710     pNewItem->notIndexed = pOldItem->notIndexed;
   69711     pNewItem->pIndex = pOldItem->pIndex;
   69712     pTab = pNewItem->pTab = pOldItem->pTab;
   69713     if( pTab ){
   69714       pTab->nRef++;
   69715     }
   69716     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
   69717     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
   69718     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
   69719     pNewItem->colUsed = pOldItem->colUsed;
   69720   }
   69721   return pNew;
   69722 }
   69723 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
   69724   IdList *pNew;
   69725   int i;
   69726   if( p==0 ) return 0;
   69727   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
   69728   if( pNew==0 ) return 0;
   69729   pNew->nId = pNew->nAlloc = p->nId;
   69730   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
   69731   if( pNew->a==0 ){
   69732     sqlite3DbFree(db, pNew);
   69733     return 0;
   69734   }
   69735   for(i=0; i<p->nId; i++){
   69736     struct IdList_item *pNewItem = &pNew->a[i];
   69737     struct IdList_item *pOldItem = &p->a[i];
   69738     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   69739     pNewItem->idx = pOldItem->idx;
   69740   }
   69741   return pNew;
   69742 }
   69743 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   69744   Select *pNew;
   69745   if( p==0 ) return 0;
   69746   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   69747   if( pNew==0 ) return 0;
   69748   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   69749   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   69750   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   69751   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   69752   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   69753   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   69754   pNew->op = p->op;
   69755   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
   69756   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   69757   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   69758   pNew->iLimit = 0;
   69759   pNew->iOffset = 0;
   69760   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   69761   pNew->pRightmost = 0;
   69762   pNew->addrOpenEphm[0] = -1;
   69763   pNew->addrOpenEphm[1] = -1;
   69764   pNew->addrOpenEphm[2] = -1;
   69765   return pNew;
   69766 }
   69767 #else
   69768 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   69769   assert( p==0 );
   69770   return 0;
   69771 }
   69772 #endif
   69773 
   69774 
   69775 /*
   69776 ** Add a new element to the end of an expression list.  If pList is
   69777 ** initially NULL, then create a new expression list.
   69778 **
   69779 ** If a memory allocation error occurs, the entire list is freed and
   69780 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
   69781 ** that the new entry was successfully appended.
   69782 */
   69783 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
   69784   Parse *pParse,          /* Parsing context */
   69785   ExprList *pList,        /* List to which to append. Might be NULL */
   69786   Expr *pExpr             /* Expression to be appended. Might be NULL */
   69787 ){
   69788   sqlite3 *db = pParse->db;
   69789   if( pList==0 ){
   69790     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
   69791     if( pList==0 ){
   69792       goto no_mem;
   69793     }
   69794     assert( pList->nAlloc==0 );
   69795   }
   69796   if( pList->nAlloc<=pList->nExpr ){
   69797     struct ExprList_item *a;
   69798     int n = pList->nAlloc*2 + 4;
   69799     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
   69800     if( a==0 ){
   69801       goto no_mem;
   69802     }
   69803     pList->a = a;
   69804     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
   69805   }
   69806   assert( pList->a!=0 );
   69807   if( 1 ){
   69808     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
   69809     memset(pItem, 0, sizeof(*pItem));
   69810     pItem->pExpr = pExpr;
   69811   }
   69812   return pList;
   69813 
   69814 no_mem:
   69815   /* Avoid leaking memory if malloc has failed. */
   69816   sqlite3ExprDelete(db, pExpr);
   69817   sqlite3ExprListDelete(db, pList);
   69818   return 0;
   69819 }
   69820 
   69821 /*
   69822 ** Set the ExprList.a[].zName element of the most recently added item
   69823 ** on the expression list.
   69824 **
   69825 ** pList might be NULL following an OOM error.  But pName should never be
   69826 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   69827 ** is set.
   69828 */
   69829 SQLITE_PRIVATE void sqlite3ExprListSetName(
   69830   Parse *pParse,          /* Parsing context */
   69831   ExprList *pList,        /* List to which to add the span. */
   69832   Token *pName,           /* Name to be added */
   69833   int dequote             /* True to cause the name to be dequoted */
   69834 ){
   69835   assert( pList!=0 || pParse->db->mallocFailed!=0 );
   69836   if( pList ){
   69837     struct ExprList_item *pItem;
   69838     assert( pList->nExpr>0 );
   69839     pItem = &pList->a[pList->nExpr-1];
   69840     assert( pItem->zName==0 );
   69841     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
   69842     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
   69843   }
   69844 }
   69845 
   69846 /*
   69847 ** Set the ExprList.a[].zSpan element of the most recently added item
   69848 ** on the expression list.
   69849 **
   69850 ** pList might be NULL following an OOM error.  But pSpan should never be
   69851 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
   69852 ** is set.
   69853 */
   69854 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   69855   Parse *pParse,          /* Parsing context */
   69856   ExprList *pList,        /* List to which to add the span. */
   69857   ExprSpan *pSpan         /* The span to be added */
   69858 ){
   69859   sqlite3 *db = pParse->db;
   69860   assert( pList!=0 || db->mallocFailed!=0 );
   69861   if( pList ){
   69862     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
   69863     assert( pList->nExpr>0 );
   69864     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
   69865     sqlite3DbFree(db, pItem->zSpan);
   69866     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   69867                                     (int)(pSpan->zEnd - pSpan->zStart));
   69868   }
   69869 }
   69870 
   69871 /*
   69872 ** If the expression list pEList contains more than iLimit elements,
   69873 ** leave an error message in pParse.
   69874 */
   69875 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
   69876   Parse *pParse,
   69877   ExprList *pEList,
   69878   const char *zObject
   69879 ){
   69880   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
   69881   testcase( pEList && pEList->nExpr==mx );
   69882   testcase( pEList && pEList->nExpr==mx+1 );
   69883   if( pEList && pEList->nExpr>mx ){
   69884     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
   69885   }
   69886 }
   69887 
   69888 /*
   69889 ** Delete an entire expression list.
   69890 */
   69891 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
   69892   int i;
   69893   struct ExprList_item *pItem;
   69894   if( pList==0 ) return;
   69895   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
   69896   assert( pList->nExpr<=pList->nAlloc );
   69897   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   69898     sqlite3ExprDelete(db, pItem->pExpr);
   69899     sqlite3DbFree(db, pItem->zName);
   69900     sqlite3DbFree(db, pItem->zSpan);
   69901   }
   69902   sqlite3DbFree(db, pList->a);
   69903   sqlite3DbFree(db, pList);
   69904 }
   69905 
   69906 /*
   69907 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
   69908 ** to an integer.  These routines are checking an expression to see
   69909 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
   69910 ** not constant.
   69911 **
   69912 ** These callback routines are used to implement the following:
   69913 **
   69914 **     sqlite3ExprIsConstant()
   69915 **     sqlite3ExprIsConstantNotJoin()
   69916 **     sqlite3ExprIsConstantOrFunction()
   69917 **
   69918 */
   69919 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
   69920 
   69921   /* If pWalker->u.i is 3 then any term of the expression that comes from
   69922   ** the ON or USING clauses of a join disqualifies the expression
   69923   ** from being considered constant. */
   69924   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
   69925     pWalker->u.i = 0;
   69926     return WRC_Abort;
   69927   }
   69928 
   69929   switch( pExpr->op ){
   69930     /* Consider functions to be constant if all their arguments are constant
   69931     ** and pWalker->u.i==2 */
   69932     case TK_FUNCTION:
   69933       if( pWalker->u.i==2 ) return 0;
   69934       /* Fall through */
   69935     case TK_ID:
   69936     case TK_COLUMN:
   69937     case TK_AGG_FUNCTION:
   69938     case TK_AGG_COLUMN:
   69939       testcase( pExpr->op==TK_ID );
   69940       testcase( pExpr->op==TK_COLUMN );
   69941       testcase( pExpr->op==TK_AGG_FUNCTION );
   69942       testcase( pExpr->op==TK_AGG_COLUMN );
   69943       pWalker->u.i = 0;
   69944       return WRC_Abort;
   69945     default:
   69946       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
   69947       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
   69948       return WRC_Continue;
   69949   }
   69950 }
   69951 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
   69952   UNUSED_PARAMETER(NotUsed);
   69953   pWalker->u.i = 0;
   69954   return WRC_Abort;
   69955 }
   69956 static int exprIsConst(Expr *p, int initFlag){
   69957   Walker w;
   69958   w.u.i = initFlag;
   69959   w.xExprCallback = exprNodeIsConstant;
   69960   w.xSelectCallback = selectNodeIsConstant;
   69961   sqlite3WalkExpr(&w, p);
   69962   return w.u.i;
   69963 }
   69964 
   69965 /*
   69966 ** Walk an expression tree.  Return 1 if the expression is constant
   69967 ** and 0 if it involves variables or function calls.
   69968 **
   69969 ** For the purposes of this function, a double-quoted string (ex: "abc")
   69970 ** is considered a variable but a single-quoted string (ex: 'abc') is
   69971 ** a constant.
   69972 */
   69973 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
   69974   return exprIsConst(p, 1);
   69975 }
   69976 
   69977 /*
   69978 ** Walk an expression tree.  Return 1 if the expression is constant
   69979 ** that does no originate from the ON or USING clauses of a join.
   69980 ** Return 0 if it involves variables or function calls or terms from
   69981 ** an ON or USING clause.
   69982 */
   69983 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   69984   return exprIsConst(p, 3);
   69985 }
   69986 
   69987 /*
   69988 ** Walk an expression tree.  Return 1 if the expression is constant
   69989 ** or a function call with constant arguments.  Return and 0 if there
   69990 ** are any variables.
   69991 **
   69992 ** For the purposes of this function, a double-quoted string (ex: "abc")
   69993 ** is considered a variable but a single-quoted string (ex: 'abc') is
   69994 ** a constant.
   69995 */
   69996 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
   69997   return exprIsConst(p, 2);
   69998 }
   69999 
   70000 /*
   70001 ** If the expression p codes a constant integer that is small enough
   70002 ** to fit in a 32-bit integer, return 1 and put the value of the integer
   70003 ** in *pValue.  If the expression is not an integer or if it is too big
   70004 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
   70005 */
   70006 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
   70007   int rc = 0;
   70008   if( p->flags & EP_IntValue ){
   70009     *pValue = p->u.iValue;
   70010     return 1;
   70011   }
   70012   switch( p->op ){
   70013     case TK_INTEGER: {
   70014       rc = sqlite3GetInt32(p->u.zToken, pValue);
   70015       assert( rc==0 );
   70016       break;
   70017     }
   70018     case TK_UPLUS: {
   70019       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
   70020       break;
   70021     }
   70022     case TK_UMINUS: {
   70023       int v;
   70024       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
   70025         *pValue = -v;
   70026         rc = 1;
   70027       }
   70028       break;
   70029     }
   70030     default: break;
   70031   }
   70032   if( rc ){
   70033     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
   70034                || (p->flags2 & EP2_MallocedToken)==0 );
   70035     p->op = TK_INTEGER;
   70036     p->flags |= EP_IntValue;
   70037     p->u.iValue = *pValue;
   70038   }
   70039   return rc;
   70040 }
   70041 
   70042 /*
   70043 ** Return FALSE if there is no chance that the expression can be NULL.
   70044 **
   70045 ** If the expression might be NULL or if the expression is too complex
   70046 ** to tell return TRUE.
   70047 **
   70048 ** This routine is used as an optimization, to skip OP_IsNull opcodes
   70049 ** when we know that a value cannot be NULL.  Hence, a false positive
   70050 ** (returning TRUE when in fact the expression can never be NULL) might
   70051 ** be a small performance hit but is otherwise harmless.  On the other
   70052 ** hand, a false negative (returning FALSE when the result could be NULL)
   70053 ** will likely result in an incorrect answer.  So when in doubt, return
   70054 ** TRUE.
   70055 */
   70056 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
   70057   u8 op;
   70058   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   70059   op = p->op;
   70060   if( op==TK_REGISTER ) op = p->op2;
   70061   switch( op ){
   70062     case TK_INTEGER:
   70063     case TK_STRING:
   70064     case TK_FLOAT:
   70065     case TK_BLOB:
   70066       return 0;
   70067     default:
   70068       return 1;
   70069   }
   70070 }
   70071 
   70072 /*
   70073 ** Generate an OP_IsNull instruction that tests register iReg and jumps
   70074 ** to location iDest if the value in iReg is NULL.  The value in iReg
   70075 ** was computed by pExpr.  If we can look at pExpr at compile-time and
   70076 ** determine that it can never generate a NULL, then the OP_IsNull operation
   70077 ** can be omitted.
   70078 */
   70079 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
   70080   Vdbe *v,            /* The VDBE under construction */
   70081   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
   70082   int iReg,           /* Test the value in this register for NULL */
   70083   int iDest           /* Jump here if the value is null */
   70084 ){
   70085   if( sqlite3ExprCanBeNull(pExpr) ){
   70086     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
   70087   }
   70088 }
   70089 
   70090 /*
   70091 ** Return TRUE if the given expression is a constant which would be
   70092 ** unchanged by OP_Affinity with the affinity given in the second
   70093 ** argument.
   70094 **
   70095 ** This routine is used to determine if the OP_Affinity operation
   70096 ** can be omitted.  When in doubt return FALSE.  A false negative
   70097 ** is harmless.  A false positive, however, can result in the wrong
   70098 ** answer.
   70099 */
   70100 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
   70101   u8 op;
   70102   if( aff==SQLITE_AFF_NONE ) return 1;
   70103   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
   70104   op = p->op;
   70105   if( op==TK_REGISTER ) op = p->op2;
   70106   switch( op ){
   70107     case TK_INTEGER: {
   70108       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
   70109     }
   70110     case TK_FLOAT: {
   70111       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
   70112     }
   70113     case TK_STRING: {
   70114       return aff==SQLITE_AFF_TEXT;
   70115     }
   70116     case TK_BLOB: {
   70117       return 1;
   70118     }
   70119     case TK_COLUMN: {
   70120       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
   70121       return p->iColumn<0
   70122           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
   70123     }
   70124     default: {
   70125       return 0;
   70126     }
   70127   }
   70128 }
   70129 
   70130 /*
   70131 ** Return TRUE if the given string is a row-id column name.
   70132 */
   70133 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
   70134   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
   70135   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
   70136   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
   70137   return 0;
   70138 }
   70139 
   70140 /*
   70141 ** Return true if we are able to the IN operator optimization on a
   70142 ** query of the form
   70143 **
   70144 **       x IN (SELECT ...)
   70145 **
   70146 ** Where the SELECT... clause is as specified by the parameter to this
   70147 ** routine.
   70148 **
   70149 ** The Select object passed in has already been preprocessed and no
   70150 ** errors have been found.
   70151 */
   70152 #ifndef SQLITE_OMIT_SUBQUERY
   70153 static int isCandidateForInOpt(Select *p){
   70154   SrcList *pSrc;
   70155   ExprList *pEList;
   70156   Table *pTab;
   70157   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
   70158   if( p->pPrior ) return 0;              /* Not a compound SELECT */
   70159   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
   70160     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   70161     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   70162     return 0; /* No DISTINCT keyword and no aggregate functions */
   70163   }
   70164   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
   70165   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
   70166   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
   70167   if( p->pWhere ) return 0;              /* Has no WHERE clause */
   70168   pSrc = p->pSrc;
   70169   assert( pSrc!=0 );
   70170   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
   70171   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
   70172   pTab = pSrc->a[0].pTab;
   70173   if( NEVER(pTab==0) ) return 0;
   70174   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
   70175   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
   70176   pEList = p->pEList;
   70177   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
   70178   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
   70179   return 1;
   70180 }
   70181 #endif /* SQLITE_OMIT_SUBQUERY */
   70182 
   70183 /*
   70184 ** This function is used by the implementation of the IN (...) operator.
   70185 ** It's job is to find or create a b-tree structure that may be used
   70186 ** either to test for membership of the (...) set or to iterate through
   70187 ** its members, skipping duplicates.
   70188 **
   70189 ** The index of the cursor opened on the b-tree (database table, database index
   70190 ** or ephermal table) is stored in pX->iTable before this function returns.
   70191 ** The returned value of this function indicates the b-tree type, as follows:
   70192 **
   70193 **   IN_INDEX_ROWID - The cursor was opened on a database table.
   70194 **   IN_INDEX_INDEX - The cursor was opened on a database index.
   70195 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
   70196 **                    populated epheremal table.
   70197 **
   70198 ** An existing b-tree may only be used if the SELECT is of the simple
   70199 ** form:
   70200 **
   70201 **     SELECT <column> FROM <table>
   70202 **
   70203 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
   70204 ** through the set members, skipping any duplicates. In this case an
   70205 ** epheremal table must be used unless the selected <column> is guaranteed
   70206 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
   70207 ** has a UNIQUE constraint or UNIQUE index.
   70208 **
   70209 ** If the prNotFound parameter is not 0, then the b-tree will be used
   70210 ** for fast set membership tests. In this case an epheremal table must
   70211 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
   70212 ** be found with <column> as its left-most column.
   70213 **
   70214 ** When the b-tree is being used for membership tests, the calling function
   70215 ** needs to know whether or not the structure contains an SQL NULL
   70216 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
   70217 ** If there is any chance that the (...) might contain a NULL value at
   70218 ** runtime, then a register is allocated and the register number written
   70219 ** to *prNotFound. If there is no chance that the (...) contains a
   70220 ** NULL value, then *prNotFound is left unchanged.
   70221 **
   70222 ** If a register is allocated and its location stored in *prNotFound, then
   70223 ** its initial value is NULL.  If the (...) does not remain constant
   70224 ** for the duration of the query (i.e. the SELECT within the (...)
   70225 ** is a correlated subquery) then the value of the allocated register is
   70226 ** reset to NULL each time the subquery is rerun. This allows the
   70227 ** caller to use vdbe code equivalent to the following:
   70228 **
   70229 **   if( register==NULL ){
   70230 **     has_null = <test if data structure contains null>
   70231 **     register = 1
   70232 **   }
   70233 **
   70234 ** in order to avoid running the <test if data structure contains null>
   70235 ** test more often than is necessary.
   70236 */
   70237 #ifndef SQLITE_OMIT_SUBQUERY
   70238 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
   70239   Select *p;                            /* SELECT to the right of IN operator */
   70240   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
   70241   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
   70242   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
   70243 
   70244   assert( pX->op==TK_IN );
   70245 
   70246   /* Check to see if an existing table or index can be used to
   70247   ** satisfy the query.  This is preferable to generating a new
   70248   ** ephemeral table.
   70249   */
   70250   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
   70251   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
   70252     sqlite3 *db = pParse->db;              /* Database connection */
   70253     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
   70254     int iCol = pExpr->iColumn;             /* Index of column <column> */
   70255     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
   70256     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
   70257     int iDb;                               /* Database idx for pTab */
   70258 
   70259     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
   70260     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   70261     sqlite3CodeVerifySchema(pParse, iDb);
   70262     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   70263 
   70264     /* This function is only called from two places. In both cases the vdbe
   70265     ** has already been allocated. So assume sqlite3GetVdbe() is always
   70266     ** successful here.
   70267     */
   70268     assert(v);
   70269     if( iCol<0 ){
   70270       int iMem = ++pParse->nMem;
   70271       int iAddr;
   70272 
   70273       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
   70274       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
   70275 
   70276       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   70277       eType = IN_INDEX_ROWID;
   70278 
   70279       sqlite3VdbeJumpHere(v, iAddr);
   70280     }else{
   70281       Index *pIdx;                         /* Iterator variable */
   70282 
   70283       /* The collation sequence used by the comparison. If an index is to
   70284       ** be used in place of a temp-table, it must be ordered according
   70285       ** to this collation sequence.  */
   70286       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
   70287 
   70288       /* Check that the affinity that will be used to perform the
   70289       ** comparison is the same as the affinity of the column. If
   70290       ** it is not, it is not possible to use any index.
   70291       */
   70292       char aff = comparisonAffinity(pX);
   70293       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
   70294 
   70295       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
   70296         if( (pIdx->aiColumn[0]==iCol)
   70297          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
   70298          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
   70299         ){
   70300           int iMem = ++pParse->nMem;
   70301           int iAddr;
   70302           char *pKey;
   70303 
   70304           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
   70305           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
   70306           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
   70307 
   70308           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
   70309                                pKey,P4_KEYINFO_HANDOFF);
   70310           VdbeComment((v, "%s", pIdx->zName));
   70311           eType = IN_INDEX_INDEX;
   70312 
   70313           sqlite3VdbeJumpHere(v, iAddr);
   70314           if( prNotFound && !pTab->aCol[iCol].notNull ){
   70315             *prNotFound = ++pParse->nMem;
   70316           }
   70317         }
   70318       }
   70319     }
   70320   }
   70321 
   70322   if( eType==0 ){
   70323     /* Could not found an existing table or index to use as the RHS b-tree.
   70324     ** We will have to generate an ephemeral table to do the job.
   70325     */
   70326     double savedNQueryLoop = pParse->nQueryLoop;
   70327     int rMayHaveNull = 0;
   70328     eType = IN_INDEX_EPH;
   70329     if( prNotFound ){
   70330       *prNotFound = rMayHaveNull = ++pParse->nMem;
   70331     }else{
   70332       testcase( pParse->nQueryLoop>(double)1 );
   70333       pParse->nQueryLoop = (double)1;
   70334       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
   70335         eType = IN_INDEX_ROWID;
   70336       }
   70337     }
   70338     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
   70339     pParse->nQueryLoop = savedNQueryLoop;
   70340   }else{
   70341     pX->iTable = iTab;
   70342   }
   70343   return eType;
   70344 }
   70345 #endif
   70346 
   70347 /*
   70348 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
   70349 ** or IN operators.  Examples:
   70350 **
   70351 **     (SELECT a FROM b)          -- subquery
   70352 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
   70353 **     x IN (4,5,11)              -- IN operator with list on right-hand side
   70354 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
   70355 **
   70356 ** The pExpr parameter describes the expression that contains the IN
   70357 ** operator or subquery.
   70358 **
   70359 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
   70360 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
   70361 ** to some integer key column of a table B-Tree. In this case, use an
   70362 ** intkey B-Tree to store the set of IN(...) values instead of the usual
   70363 ** (slower) variable length keys B-Tree.
   70364 **
   70365 ** If rMayHaveNull is non-zero, that means that the operation is an IN
   70366 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
   70367 ** Furthermore, the IN is in a WHERE clause and that we really want
   70368 ** to iterate over the RHS of the IN operator in order to quickly locate
   70369 ** all corresponding LHS elements.  All this routine does is initialize
   70370 ** the register given by rMayHaveNull to NULL.  Calling routines will take
   70371 ** care of changing this register value to non-NULL if the RHS is NULL-free.
   70372 **
   70373 ** If rMayHaveNull is zero, that means that the subquery is being used
   70374 ** for membership testing only.  There is no need to initialize any
   70375 ** registers to indicate the presense or absence of NULLs on the RHS.
   70376 **
   70377 ** For a SELECT or EXISTS operator, return the register that holds the
   70378 ** result.  For IN operators or if an error occurs, the return value is 0.
   70379 */
   70380 #ifndef SQLITE_OMIT_SUBQUERY
   70381 SQLITE_PRIVATE int sqlite3CodeSubselect(
   70382   Parse *pParse,          /* Parsing context */
   70383   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
   70384   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
   70385   int isRowid             /* If true, LHS of IN operator is a rowid */
   70386 ){
   70387   int testAddr = 0;                       /* One-time test address */
   70388   int rReg = 0;                           /* Register storing resulting */
   70389   Vdbe *v = sqlite3GetVdbe(pParse);
   70390   if( NEVER(v==0) ) return 0;
   70391   sqlite3ExprCachePush(pParse);
   70392 
   70393   /* This code must be run in its entirety every time it is encountered
   70394   ** if any of the following is true:
   70395   **
   70396   **    *  The right-hand side is a correlated subquery
   70397   **    *  The right-hand side is an expression list containing variables
   70398   **    *  We are inside a trigger
   70399   **
   70400   ** If all of the above are false, then we can run this code just once
   70401   ** save the results, and reuse the same result on subsequent invocations.
   70402   */
   70403   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
   70404     int mem = ++pParse->nMem;
   70405     sqlite3VdbeAddOp1(v, OP_If, mem);
   70406     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
   70407     assert( testAddr>0 || pParse->db->mallocFailed );
   70408   }
   70409 
   70410 #ifndef SQLITE_OMIT_EXPLAIN
   70411   if( pParse->explain==2 ){
   70412     char *zMsg = sqlite3MPrintf(
   70413         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
   70414         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
   70415     );
   70416     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   70417   }
   70418 #endif
   70419 
   70420   switch( pExpr->op ){
   70421     case TK_IN: {
   70422       char affinity;              /* Affinity of the LHS of the IN */
   70423       KeyInfo keyInfo;            /* Keyinfo for the generated table */
   70424       int addr;                   /* Address of OP_OpenEphemeral instruction */
   70425       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
   70426 
   70427       if( rMayHaveNull ){
   70428         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
   70429       }
   70430 
   70431       affinity = sqlite3ExprAffinity(pLeft);
   70432 
   70433       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
   70434       ** expression it is handled the same way.  An ephemeral table is
   70435       ** filled with single-field index keys representing the results
   70436       ** from the SELECT or the <exprlist>.
   70437       **
   70438       ** If the 'x' expression is a column value, or the SELECT...
   70439       ** statement returns a column value, then the affinity of that
   70440       ** column is used to build the index keys. If both 'x' and the
   70441       ** SELECT... statement are columns, then numeric affinity is used
   70442       ** if either column has NUMERIC or INTEGER affinity. If neither
   70443       ** 'x' nor the SELECT... statement are columns, then numeric affinity
   70444       ** is used.
   70445       */
   70446       pExpr->iTable = pParse->nTab++;
   70447       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
   70448       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   70449       memset(&keyInfo, 0, sizeof(keyInfo));
   70450       keyInfo.nField = 1;
   70451 
   70452       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   70453         /* Case 1:     expr IN (SELECT ...)
   70454         **
   70455         ** Generate code to write the results of the select into the temporary
   70456         ** table allocated and opened above.
   70457         */
   70458         SelectDest dest;
   70459         ExprList *pEList;
   70460 
   70461         assert( !isRowid );
   70462         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
   70463         dest.affinity = (u8)affinity;
   70464         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
   70465         pExpr->x.pSelect->iLimit = 0;
   70466         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
   70467           return 0;
   70468         }
   70469         pEList = pExpr->x.pSelect->pEList;
   70470         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
   70471           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
   70472               pEList->a[0].pExpr);
   70473         }
   70474       }else if( ALWAYS(pExpr->x.pList!=0) ){
   70475         /* Case 2:     expr IN (exprlist)
   70476         **
   70477         ** For each expression, build an index key from the evaluation and
   70478         ** store it in the temporary table. If <expr> is a column, then use
   70479         ** that columns affinity when building index keys. If <expr> is not
   70480         ** a column, use numeric affinity.
   70481         */
   70482         int i;
   70483         ExprList *pList = pExpr->x.pList;
   70484         struct ExprList_item *pItem;
   70485         int r1, r2, r3;
   70486 
   70487         if( !affinity ){
   70488           affinity = SQLITE_AFF_NONE;
   70489         }
   70490         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   70491 
   70492         /* Loop through each expression in <exprlist>. */
   70493         r1 = sqlite3GetTempReg(pParse);
   70494         r2 = sqlite3GetTempReg(pParse);
   70495         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
   70496         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
   70497           Expr *pE2 = pItem->pExpr;
   70498           int iValToIns;
   70499 
   70500           /* If the expression is not constant then we will need to
   70501           ** disable the test that was generated above that makes sure
   70502           ** this code only executes once.  Because for a non-constant
   70503           ** expression we need to rerun this code each time.
   70504           */
   70505           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
   70506             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
   70507             testAddr = 0;
   70508           }
   70509 
   70510           /* Evaluate the expression and insert it into the temp table */
   70511           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
   70512             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
   70513           }else{
   70514             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
   70515             if( isRowid ){
   70516               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
   70517                                 sqlite3VdbeCurrentAddr(v)+2);
   70518               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
   70519             }else{
   70520               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
   70521               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
   70522               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
   70523             }
   70524           }
   70525         }
   70526         sqlite3ReleaseTempReg(pParse, r1);
   70527         sqlite3ReleaseTempReg(pParse, r2);
   70528       }
   70529       if( !isRowid ){
   70530         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
   70531       }
   70532       break;
   70533     }
   70534 
   70535     case TK_EXISTS:
   70536     case TK_SELECT:
   70537     default: {
   70538       /* If this has to be a scalar SELECT.  Generate code to put the
   70539       ** value of this select in a memory cell and record the number
   70540       ** of the memory cell in iColumn.  If this is an EXISTS, write
   70541       ** an integer 0 (not exists) or 1 (exists) into a memory cell
   70542       ** and record that memory cell in iColumn.
   70543       */
   70544       Select *pSel;                         /* SELECT statement to encode */
   70545       SelectDest dest;                      /* How to deal with SELECt result */
   70546 
   70547       testcase( pExpr->op==TK_EXISTS );
   70548       testcase( pExpr->op==TK_SELECT );
   70549       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
   70550 
   70551       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   70552       pSel = pExpr->x.pSelect;
   70553       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
   70554       if( pExpr->op==TK_SELECT ){
   70555         dest.eDest = SRT_Mem;
   70556         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
   70557         VdbeComment((v, "Init subquery result"));
   70558       }else{
   70559         dest.eDest = SRT_Exists;
   70560         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
   70561         VdbeComment((v, "Init EXISTS result"));
   70562       }
   70563       sqlite3ExprDelete(pParse->db, pSel->pLimit);
   70564       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
   70565                                   &sqlite3IntTokens[1]);
   70566       pSel->iLimit = 0;
   70567       if( sqlite3Select(pParse, pSel, &dest) ){
   70568         return 0;
   70569       }
   70570       rReg = dest.iParm;
   70571       ExprSetIrreducible(pExpr);
   70572       break;
   70573     }
   70574   }
   70575 
   70576   if( testAddr ){
   70577     sqlite3VdbeJumpHere(v, testAddr-1);
   70578   }
   70579   sqlite3ExprCachePop(pParse, 1);
   70580 
   70581   return rReg;
   70582 }
   70583 #endif /* SQLITE_OMIT_SUBQUERY */
   70584 
   70585 #ifndef SQLITE_OMIT_SUBQUERY
   70586 /*
   70587 ** Generate code for an IN expression.
   70588 **
   70589 **      x IN (SELECT ...)
   70590 **      x IN (value, value, ...)
   70591 **
   70592 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
   70593 ** is an array of zero or more values.  The expression is true if the LHS is
   70594 ** contained within the RHS.  The value of the expression is unknown (NULL)
   70595 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
   70596 ** RHS contains one or more NULL values.
   70597 **
   70598 ** This routine generates code will jump to destIfFalse if the LHS is not
   70599 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
   70600 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
   70601 ** within the RHS then fall through.
   70602 */
   70603 static void sqlite3ExprCodeIN(
   70604   Parse *pParse,        /* Parsing and code generating context */
   70605   Expr *pExpr,          /* The IN expression */
   70606   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
   70607   int destIfNull        /* Jump here if the results are unknown due to NULLs */
   70608 ){
   70609   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
   70610   char affinity;        /* Comparison affinity to use */
   70611   int eType;            /* Type of the RHS */
   70612   int r1;               /* Temporary use register */
   70613   Vdbe *v;              /* Statement under construction */
   70614 
   70615   /* Compute the RHS.   After this step, the table with cursor
   70616   ** pExpr->iTable will contains the values that make up the RHS.
   70617   */
   70618   v = pParse->pVdbe;
   70619   assert( v!=0 );       /* OOM detected prior to this routine */
   70620   VdbeNoopComment((v, "begin IN expr"));
   70621   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
   70622 
   70623   /* Figure out the affinity to use to create a key from the results
   70624   ** of the expression. affinityStr stores a static string suitable for
   70625   ** P4 of OP_MakeRecord.
   70626   */
   70627   affinity = comparisonAffinity(pExpr);
   70628 
   70629   /* Code the LHS, the <expr> from "<expr> IN (...)".
   70630   */
   70631   sqlite3ExprCachePush(pParse);
   70632   r1 = sqlite3GetTempReg(pParse);
   70633   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
   70634 
   70635   /* If the LHS is NULL, then the result is either false or NULL depending
   70636   ** on whether the RHS is empty or not, respectively.
   70637   */
   70638   if( destIfNull==destIfFalse ){
   70639     /* Shortcut for the common case where the false and NULL outcomes are
   70640     ** the same. */
   70641     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
   70642   }else{
   70643     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
   70644     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
   70645     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
   70646     sqlite3VdbeJumpHere(v, addr1);
   70647   }
   70648 
   70649   if( eType==IN_INDEX_ROWID ){
   70650     /* In this case, the RHS is the ROWID of table b-tree
   70651     */
   70652     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
   70653     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
   70654   }else{
   70655     /* In this case, the RHS is an index b-tree.
   70656     */
   70657     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
   70658 
   70659     /* If the set membership test fails, then the result of the
   70660     ** "x IN (...)" expression must be either 0 or NULL. If the set
   70661     ** contains no NULL values, then the result is 0. If the set
   70662     ** contains one or more NULL values, then the result of the
   70663     ** expression is also NULL.
   70664     */
   70665     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
   70666       /* This branch runs if it is known at compile time that the RHS
   70667       ** cannot contain NULL values. This happens as the result
   70668       ** of a "NOT NULL" constraint in the database schema.
   70669       **
   70670       ** Also run this branch if NULL is equivalent to FALSE
   70671       ** for this particular IN operator.
   70672       */
   70673       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
   70674 
   70675     }else{
   70676       /* In this branch, the RHS of the IN might contain a NULL and
   70677       ** the presence of a NULL on the RHS makes a difference in the
   70678       ** outcome.
   70679       */
   70680       int j1, j2, j3;
   70681 
   70682       /* First check to see if the LHS is contained in the RHS.  If so,
   70683       ** then the presence of NULLs in the RHS does not matter, so jump
   70684       ** over all of the code that follows.
   70685       */
   70686       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
   70687 
   70688       /* Here we begin generating code that runs if the LHS is not
   70689       ** contained within the RHS.  Generate additional code that
   70690       ** tests the RHS for NULLs.  If the RHS contains a NULL then
   70691       ** jump to destIfNull.  If there are no NULLs in the RHS then
   70692       ** jump to destIfFalse.
   70693       */
   70694       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
   70695       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
   70696       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
   70697       sqlite3VdbeJumpHere(v, j3);
   70698       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
   70699       sqlite3VdbeJumpHere(v, j2);
   70700 
   70701       /* Jump to the appropriate target depending on whether or not
   70702       ** the RHS contains a NULL
   70703       */
   70704       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
   70705       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
   70706 
   70707       /* The OP_Found at the top of this branch jumps here when true,
   70708       ** causing the overall IN expression evaluation to fall through.
   70709       */
   70710       sqlite3VdbeJumpHere(v, j1);
   70711     }
   70712   }
   70713   sqlite3ReleaseTempReg(pParse, r1);
   70714   sqlite3ExprCachePop(pParse, 1);
   70715   VdbeComment((v, "end IN expr"));
   70716 }
   70717 #endif /* SQLITE_OMIT_SUBQUERY */
   70718 
   70719 /*
   70720 ** Duplicate an 8-byte value
   70721 */
   70722 static char *dup8bytes(Vdbe *v, const char *in){
   70723   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
   70724   if( out ){
   70725     memcpy(out, in, 8);
   70726   }
   70727   return out;
   70728 }
   70729 
   70730 #ifndef SQLITE_OMIT_FLOATING_POINT
   70731 /*
   70732 ** Generate an instruction that will put the floating point
   70733 ** value described by z[0..n-1] into register iMem.
   70734 **
   70735 ** The z[] string will probably not be zero-terminated.  But the
   70736 ** z[n] character is guaranteed to be something that does not look
   70737 ** like the continuation of the number.
   70738 */
   70739 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
   70740   if( ALWAYS(z!=0) ){
   70741     double value;
   70742     char *zV;
   70743     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   70744     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
   70745     if( negateFlag ) value = -value;
   70746     zV = dup8bytes(v, (char*)&value);
   70747     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
   70748   }
   70749 }
   70750 #endif
   70751 
   70752 
   70753 /*
   70754 ** Generate an instruction that will put the integer describe by
   70755 ** text z[0..n-1] into register iMem.
   70756 **
   70757 ** Expr.u.zToken is always UTF8 and zero-terminated.
   70758 */
   70759 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
   70760   Vdbe *v = pParse->pVdbe;
   70761   if( pExpr->flags & EP_IntValue ){
   70762     int i = pExpr->u.iValue;
   70763     if( negFlag ) i = -i;
   70764     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
   70765   }else{
   70766     int c;
   70767     i64 value;
   70768     const char *z = pExpr->u.zToken;
   70769     assert( z!=0 );
   70770     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
   70771     if( c==0 || (c==2 && negFlag) ){
   70772       char *zV;
   70773       if( negFlag ){ value = -value; }
   70774       zV = dup8bytes(v, (char*)&value);
   70775       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
   70776     }else{
   70777 #ifdef SQLITE_OMIT_FLOATING_POINT
   70778       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
   70779 #else
   70780       codeReal(v, z, negFlag, iMem);
   70781 #endif
   70782     }
   70783   }
   70784 }
   70785 
   70786 /*
   70787 ** Clear a cache entry.
   70788 */
   70789 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
   70790   if( p->tempReg ){
   70791     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   70792       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
   70793     }
   70794     p->tempReg = 0;
   70795   }
   70796 }
   70797 
   70798 
   70799 /*
   70800 ** Record in the column cache that a particular column from a
   70801 ** particular table is stored in a particular register.
   70802 */
   70803 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
   70804   int i;
   70805   int minLru;
   70806   int idxLru;
   70807   struct yColCache *p;
   70808 
   70809   assert( iReg>0 );  /* Register numbers are always positive */
   70810   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
   70811 
   70812   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
   70813   ** for testing only - to verify that SQLite always gets the same answer
   70814   ** with and without the column cache.
   70815   */
   70816   if( pParse->db->flags & SQLITE_ColumnCache ) return;
   70817 
   70818   /* First replace any existing entry.
   70819   **
   70820   ** Actually, the way the column cache is currently used, we are guaranteed
   70821   ** that the object will never already be in cache.  Verify this guarantee.
   70822   */
   70823 #ifndef NDEBUG
   70824   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70825 #if 0 /* This code wold remove the entry from the cache if it existed */
   70826     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
   70827       cacheEntryClear(pParse, p);
   70828       p->iLevel = pParse->iCacheLevel;
   70829       p->iReg = iReg;
   70830       p->lru = pParse->iCacheCnt++;
   70831       return;
   70832     }
   70833 #endif
   70834     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
   70835   }
   70836 #endif
   70837 
   70838   /* Find an empty slot and replace it */
   70839   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70840     if( p->iReg==0 ){
   70841       p->iLevel = pParse->iCacheLevel;
   70842       p->iTable = iTab;
   70843       p->iColumn = iCol;
   70844       p->iReg = iReg;
   70845       p->tempReg = 0;
   70846       p->lru = pParse->iCacheCnt++;
   70847       return;
   70848     }
   70849   }
   70850 
   70851   /* Replace the last recently used */
   70852   minLru = 0x7fffffff;
   70853   idxLru = -1;
   70854   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70855     if( p->lru<minLru ){
   70856       idxLru = i;
   70857       minLru = p->lru;
   70858     }
   70859   }
   70860   if( ALWAYS(idxLru>=0) ){
   70861     p = &pParse->aColCache[idxLru];
   70862     p->iLevel = pParse->iCacheLevel;
   70863     p->iTable = iTab;
   70864     p->iColumn = iCol;
   70865     p->iReg = iReg;
   70866     p->tempReg = 0;
   70867     p->lru = pParse->iCacheCnt++;
   70868     return;
   70869   }
   70870 }
   70871 
   70872 /*
   70873 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
   70874 ** Purge the range of registers from the column cache.
   70875 */
   70876 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
   70877   int i;
   70878   int iLast = iReg + nReg - 1;
   70879   struct yColCache *p;
   70880   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70881     int r = p->iReg;
   70882     if( r>=iReg && r<=iLast ){
   70883       cacheEntryClear(pParse, p);
   70884       p->iReg = 0;
   70885     }
   70886   }
   70887 }
   70888 
   70889 /*
   70890 ** Remember the current column cache context.  Any new entries added
   70891 ** added to the column cache after this call are removed when the
   70892 ** corresponding pop occurs.
   70893 */
   70894 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
   70895   pParse->iCacheLevel++;
   70896 }
   70897 
   70898 /*
   70899 ** Remove from the column cache any entries that were added since the
   70900 ** the previous N Push operations.  In other words, restore the cache
   70901 ** to the state it was in N Pushes ago.
   70902 */
   70903 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
   70904   int i;
   70905   struct yColCache *p;
   70906   assert( N>0 );
   70907   assert( pParse->iCacheLevel>=N );
   70908   pParse->iCacheLevel -= N;
   70909   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70910     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
   70911       cacheEntryClear(pParse, p);
   70912       p->iReg = 0;
   70913     }
   70914   }
   70915 }
   70916 
   70917 /*
   70918 ** When a cached column is reused, make sure that its register is
   70919 ** no longer available as a temp register.  ticket #3879:  that same
   70920 ** register might be in the cache in multiple places, so be sure to
   70921 ** get them all.
   70922 */
   70923 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
   70924   int i;
   70925   struct yColCache *p;
   70926   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70927     if( p->iReg==iReg ){
   70928       p->tempReg = 0;
   70929     }
   70930   }
   70931 }
   70932 
   70933 /*
   70934 ** Generate code to extract the value of the iCol-th column of a table.
   70935 */
   70936 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   70937   Vdbe *v,        /* The VDBE under construction */
   70938   Table *pTab,    /* The table containing the value */
   70939   int iTabCur,    /* The cursor for this table */
   70940   int iCol,       /* Index of the column to extract */
   70941   int regOut      /* Extract the valud into this register */
   70942 ){
   70943   if( iCol<0 || iCol==pTab->iPKey ){
   70944     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   70945   }else{
   70946     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
   70947     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
   70948   }
   70949   if( iCol>=0 ){
   70950     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   70951   }
   70952 }
   70953 
   70954 /*
   70955 ** Generate code that will extract the iColumn-th column from
   70956 ** table pTab and store the column value in a register.  An effort
   70957 ** is made to store the column value in register iReg, but this is
   70958 ** not guaranteed.  The location of the column value is returned.
   70959 **
   70960 ** There must be an open cursor to pTab in iTable when this routine
   70961 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
   70962 */
   70963 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   70964   Parse *pParse,   /* Parsing and code generating context */
   70965   Table *pTab,     /* Description of the table we are reading from */
   70966   int iColumn,     /* Index of the table column */
   70967   int iTable,      /* The cursor pointing to the table */
   70968   int iReg         /* Store results here */
   70969 ){
   70970   Vdbe *v = pParse->pVdbe;
   70971   int i;
   70972   struct yColCache *p;
   70973 
   70974   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70975     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
   70976       p->lru = pParse->iCacheCnt++;
   70977       sqlite3ExprCachePinRegister(pParse, p->iReg);
   70978       return p->iReg;
   70979     }
   70980   }
   70981   assert( v!=0 );
   70982   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
   70983   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
   70984   return iReg;
   70985 }
   70986 
   70987 /*
   70988 ** Clear all column cache entries.
   70989 */
   70990 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
   70991   int i;
   70992   struct yColCache *p;
   70993 
   70994   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   70995     if( p->iReg ){
   70996       cacheEntryClear(pParse, p);
   70997       p->iReg = 0;
   70998     }
   70999   }
   71000 }
   71001 
   71002 /*
   71003 ** Record the fact that an affinity change has occurred on iCount
   71004 ** registers starting with iStart.
   71005 */
   71006 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
   71007   sqlite3ExprCacheRemove(pParse, iStart, iCount);
   71008 }
   71009 
   71010 /*
   71011 ** Generate code to move content from registers iFrom...iFrom+nReg-1
   71012 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
   71013 */
   71014 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
   71015   int i;
   71016   struct yColCache *p;
   71017   if( NEVER(iFrom==iTo) ) return;
   71018   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
   71019   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   71020     int x = p->iReg;
   71021     if( x>=iFrom && x<iFrom+nReg ){
   71022       p->iReg += iTo-iFrom;
   71023     }
   71024   }
   71025 }
   71026 
   71027 /*
   71028 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
   71029 ** over to iTo..iTo+nReg-1.
   71030 */
   71031 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
   71032   int i;
   71033   if( NEVER(iFrom==iTo) ) return;
   71034   for(i=0; i<nReg; i++){
   71035     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
   71036   }
   71037 }
   71038 
   71039 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
   71040 /*
   71041 ** Return true if any register in the range iFrom..iTo (inclusive)
   71042 ** is used as part of the column cache.
   71043 **
   71044 ** This routine is used within assert() and testcase() macros only
   71045 ** and does not appear in a normal build.
   71046 */
   71047 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
   71048   int i;
   71049   struct yColCache *p;
   71050   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   71051     int r = p->iReg;
   71052     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
   71053   }
   71054   return 0;
   71055 }
   71056 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
   71057 
   71058 /*
   71059 ** Generate code into the current Vdbe to evaluate the given
   71060 ** expression.  Attempt to store the results in register "target".
   71061 ** Return the register where results are stored.
   71062 **
   71063 ** With this routine, there is no guarantee that results will
   71064 ** be stored in target.  The result might be stored in some other
   71065 ** register if it is convenient to do so.  The calling function
   71066 ** must check the return code and move the results to the desired
   71067 ** register.
   71068 */
   71069 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
   71070   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
   71071   int op;                   /* The opcode being coded */
   71072   int inReg = target;       /* Results stored in register inReg */
   71073   int regFree1 = 0;         /* If non-zero free this temporary register */
   71074   int regFree2 = 0;         /* If non-zero free this temporary register */
   71075   int r1, r2, r3, r4;       /* Various register numbers */
   71076   sqlite3 *db = pParse->db; /* The database connection */
   71077 
   71078   assert( target>0 && target<=pParse->nMem );
   71079   if( v==0 ){
   71080     assert( pParse->db->mallocFailed );
   71081     return 0;
   71082   }
   71083 
   71084   if( pExpr==0 ){
   71085     op = TK_NULL;
   71086   }else{
   71087     op = pExpr->op;
   71088   }
   71089   switch( op ){
   71090     case TK_AGG_COLUMN: {
   71091       AggInfo *pAggInfo = pExpr->pAggInfo;
   71092       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
   71093       if( !pAggInfo->directMode ){
   71094         assert( pCol->iMem>0 );
   71095         inReg = pCol->iMem;
   71096         break;
   71097       }else if( pAggInfo->useSortingIdx ){
   71098         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
   71099                               pCol->iSorterColumn, target);
   71100         break;
   71101       }
   71102       /* Otherwise, fall thru into the TK_COLUMN case */
   71103     }
   71104     case TK_COLUMN: {
   71105       if( pExpr->iTable<0 ){
   71106         /* This only happens when coding check constraints */
   71107         assert( pParse->ckBase>0 );
   71108         inReg = pExpr->iColumn + pParse->ckBase;
   71109       }else{
   71110         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
   71111                                  pExpr->iColumn, pExpr->iTable, target);
   71112       }
   71113       break;
   71114     }
   71115     case TK_INTEGER: {
   71116       codeInteger(pParse, pExpr, 0, target);
   71117       break;
   71118     }
   71119 #ifndef SQLITE_OMIT_FLOATING_POINT
   71120     case TK_FLOAT: {
   71121       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71122       codeReal(v, pExpr->u.zToken, 0, target);
   71123       break;
   71124     }
   71125 #endif
   71126     case TK_STRING: {
   71127       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71128       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
   71129       break;
   71130     }
   71131     case TK_NULL: {
   71132       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   71133       break;
   71134     }
   71135 #ifndef SQLITE_OMIT_BLOB_LITERAL
   71136     case TK_BLOB: {
   71137       int n;
   71138       const char *z;
   71139       char *zBlob;
   71140       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71141       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
   71142       assert( pExpr->u.zToken[1]=='\'' );
   71143       z = &pExpr->u.zToken[2];
   71144       n = sqlite3Strlen30(z) - 1;
   71145       assert( z[n]=='\'' );
   71146       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
   71147       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
   71148       break;
   71149     }
   71150 #endif
   71151     case TK_VARIABLE: {
   71152       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71153       assert( pExpr->u.zToken!=0 );
   71154       assert( pExpr->u.zToken[0]!=0 );
   71155       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
   71156       if( pExpr->u.zToken[1]!=0 ){
   71157         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
   71158       }
   71159       break;
   71160     }
   71161     case TK_REGISTER: {
   71162       inReg = pExpr->iTable;
   71163       break;
   71164     }
   71165     case TK_AS: {
   71166       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   71167       break;
   71168     }
   71169 #ifndef SQLITE_OMIT_CAST
   71170     case TK_CAST: {
   71171       /* Expressions of the form:   CAST(pLeft AS token) */
   71172       int aff, to_op;
   71173       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   71174       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71175       aff = sqlite3AffinityType(pExpr->u.zToken);
   71176       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
   71177       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
   71178       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
   71179       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
   71180       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
   71181       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
   71182       testcase( to_op==OP_ToText );
   71183       testcase( to_op==OP_ToBlob );
   71184       testcase( to_op==OP_ToNumeric );
   71185       testcase( to_op==OP_ToInt );
   71186       testcase( to_op==OP_ToReal );
   71187       if( inReg!=target ){
   71188         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
   71189         inReg = target;
   71190       }
   71191       sqlite3VdbeAddOp1(v, to_op, inReg);
   71192       testcase( usedAsColumnCache(pParse, inReg, inReg) );
   71193       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
   71194       break;
   71195     }
   71196 #endif /* SQLITE_OMIT_CAST */
   71197     case TK_LT:
   71198     case TK_LE:
   71199     case TK_GT:
   71200     case TK_GE:
   71201     case TK_NE:
   71202     case TK_EQ: {
   71203       assert( TK_LT==OP_Lt );
   71204       assert( TK_LE==OP_Le );
   71205       assert( TK_GT==OP_Gt );
   71206       assert( TK_GE==OP_Ge );
   71207       assert( TK_EQ==OP_Eq );
   71208       assert( TK_NE==OP_Ne );
   71209       testcase( op==TK_LT );
   71210       testcase( op==TK_LE );
   71211       testcase( op==TK_GT );
   71212       testcase( op==TK_GE );
   71213       testcase( op==TK_EQ );
   71214       testcase( op==TK_NE );
   71215       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   71216       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   71217       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   71218                   r1, r2, inReg, SQLITE_STOREP2);
   71219       testcase( regFree1==0 );
   71220       testcase( regFree2==0 );
   71221       break;
   71222     }
   71223     case TK_IS:
   71224     case TK_ISNOT: {
   71225       testcase( op==TK_IS );
   71226       testcase( op==TK_ISNOT );
   71227       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   71228       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   71229       op = (op==TK_IS) ? TK_EQ : TK_NE;
   71230       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   71231                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
   71232       testcase( regFree1==0 );
   71233       testcase( regFree2==0 );
   71234       break;
   71235     }
   71236     case TK_AND:
   71237     case TK_OR:
   71238     case TK_PLUS:
   71239     case TK_STAR:
   71240     case TK_MINUS:
   71241     case TK_REM:
   71242     case TK_BITAND:
   71243     case TK_BITOR:
   71244     case TK_SLASH:
   71245     case TK_LSHIFT:
   71246     case TK_RSHIFT:
   71247     case TK_CONCAT: {
   71248       assert( TK_AND==OP_And );
   71249       assert( TK_OR==OP_Or );
   71250       assert( TK_PLUS==OP_Add );
   71251       assert( TK_MINUS==OP_Subtract );
   71252       assert( TK_REM==OP_Remainder );
   71253       assert( TK_BITAND==OP_BitAnd );
   71254       assert( TK_BITOR==OP_BitOr );
   71255       assert( TK_SLASH==OP_Divide );
   71256       assert( TK_LSHIFT==OP_ShiftLeft );
   71257       assert( TK_RSHIFT==OP_ShiftRight );
   71258       assert( TK_CONCAT==OP_Concat );
   71259       testcase( op==TK_AND );
   71260       testcase( op==TK_OR );
   71261       testcase( op==TK_PLUS );
   71262       testcase( op==TK_MINUS );
   71263       testcase( op==TK_REM );
   71264       testcase( op==TK_BITAND );
   71265       testcase( op==TK_BITOR );
   71266       testcase( op==TK_SLASH );
   71267       testcase( op==TK_LSHIFT );
   71268       testcase( op==TK_RSHIFT );
   71269       testcase( op==TK_CONCAT );
   71270       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   71271       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   71272       sqlite3VdbeAddOp3(v, op, r2, r1, target);
   71273       testcase( regFree1==0 );
   71274       testcase( regFree2==0 );
   71275       break;
   71276     }
   71277     case TK_UMINUS: {
   71278       Expr *pLeft = pExpr->pLeft;
   71279       assert( pLeft );
   71280       if( pLeft->op==TK_INTEGER ){
   71281         codeInteger(pParse, pLeft, 1, target);
   71282 #ifndef SQLITE_OMIT_FLOATING_POINT
   71283       }else if( pLeft->op==TK_FLOAT ){
   71284         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71285         codeReal(v, pLeft->u.zToken, 1, target);
   71286 #endif
   71287       }else{
   71288         regFree1 = r1 = sqlite3GetTempReg(pParse);
   71289         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
   71290         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
   71291         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
   71292         testcase( regFree2==0 );
   71293       }
   71294       inReg = target;
   71295       break;
   71296     }
   71297     case TK_BITNOT:
   71298     case TK_NOT: {
   71299       assert( TK_BITNOT==OP_BitNot );
   71300       assert( TK_NOT==OP_Not );
   71301       testcase( op==TK_BITNOT );
   71302       testcase( op==TK_NOT );
   71303       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   71304       testcase( regFree1==0 );
   71305       inReg = target;
   71306       sqlite3VdbeAddOp2(v, op, r1, inReg);
   71307       break;
   71308     }
   71309     case TK_ISNULL:
   71310     case TK_NOTNULL: {
   71311       int addr;
   71312       assert( TK_ISNULL==OP_IsNull );
   71313       assert( TK_NOTNULL==OP_NotNull );
   71314       testcase( op==TK_ISNULL );
   71315       testcase( op==TK_NOTNULL );
   71316       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   71317       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   71318       testcase( regFree1==0 );
   71319       addr = sqlite3VdbeAddOp1(v, op, r1);
   71320       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
   71321       sqlite3VdbeJumpHere(v, addr);
   71322       break;
   71323     }
   71324     case TK_AGG_FUNCTION: {
   71325       AggInfo *pInfo = pExpr->pAggInfo;
   71326       if( pInfo==0 ){
   71327         assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71328         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
   71329       }else{
   71330         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
   71331       }
   71332       break;
   71333     }
   71334     case TK_CONST_FUNC:
   71335     case TK_FUNCTION: {
   71336       ExprList *pFarg;       /* List of function arguments */
   71337       int nFarg;             /* Number of function arguments */
   71338       FuncDef *pDef;         /* The function definition object */
   71339       int nId;               /* Length of the function name in bytes */
   71340       const char *zId;       /* The function name */
   71341       int constMask = 0;     /* Mask of function arguments that are constant */
   71342       int i;                 /* Loop counter */
   71343       u8 enc = ENC(db);      /* The text encoding used by this database */
   71344       CollSeq *pColl = 0;    /* A collating sequence */
   71345 
   71346       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   71347       testcase( op==TK_CONST_FUNC );
   71348       testcase( op==TK_FUNCTION );
   71349       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
   71350         pFarg = 0;
   71351       }else{
   71352         pFarg = pExpr->x.pList;
   71353       }
   71354       nFarg = pFarg ? pFarg->nExpr : 0;
   71355       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71356       zId = pExpr->u.zToken;
   71357       nId = sqlite3Strlen30(zId);
   71358       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
   71359       if( pDef==0 ){
   71360         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
   71361         break;
   71362       }
   71363 
   71364       /* Attempt a direct implementation of the built-in COALESCE() and
   71365       ** IFNULL() functions.  This avoids unnecessary evalation of
   71366       ** arguments past the first non-NULL argument.
   71367       */
   71368       if( pDef->flags & SQLITE_FUNC_COALESCE ){
   71369         int endCoalesce = sqlite3VdbeMakeLabel(v);
   71370         assert( nFarg>=2 );
   71371         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
   71372         for(i=1; i<nFarg; i++){
   71373           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
   71374           sqlite3ExprCacheRemove(pParse, target, 1);
   71375           sqlite3ExprCachePush(pParse);
   71376           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
   71377           sqlite3ExprCachePop(pParse, 1);
   71378         }
   71379         sqlite3VdbeResolveLabel(v, endCoalesce);
   71380         break;
   71381       }
   71382 
   71383 
   71384       if( pFarg ){
   71385         r1 = sqlite3GetTempRange(pParse, nFarg);
   71386         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
   71387         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
   71388         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
   71389       }else{
   71390         r1 = 0;
   71391       }
   71392 #ifndef SQLITE_OMIT_VIRTUALTABLE
   71393       /* Possibly overload the function if the first argument is
   71394       ** a virtual table column.
   71395       **
   71396       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
   71397       ** second argument, not the first, as the argument to test to
   71398       ** see if it is a column in a virtual table.  This is done because
   71399       ** the left operand of infix functions (the operand we want to
   71400       ** control overloading) ends up as the second argument to the
   71401       ** function.  The expression "A glob B" is equivalent to
   71402       ** "glob(B,A).  We want to use the A in "A glob B" to test
   71403       ** for function overloading.  But we use the B term in "glob(B,A)".
   71404       */
   71405       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
   71406         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
   71407       }else if( nFarg>0 ){
   71408         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
   71409       }
   71410 #endif
   71411       for(i=0; i<nFarg; i++){
   71412         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
   71413           constMask |= (1<<i);
   71414         }
   71415         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
   71416           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
   71417         }
   71418       }
   71419       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
   71420         if( !pColl ) pColl = db->pDfltColl;
   71421         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   71422       }
   71423       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
   71424                         (char*)pDef, P4_FUNCDEF);
   71425       sqlite3VdbeChangeP5(v, (u8)nFarg);
   71426       if( nFarg ){
   71427         sqlite3ReleaseTempRange(pParse, r1, nFarg);
   71428       }
   71429       break;
   71430     }
   71431 #ifndef SQLITE_OMIT_SUBQUERY
   71432     case TK_EXISTS:
   71433     case TK_SELECT: {
   71434       testcase( op==TK_EXISTS );
   71435       testcase( op==TK_SELECT );
   71436       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
   71437       break;
   71438     }
   71439     case TK_IN: {
   71440       int destIfFalse = sqlite3VdbeMakeLabel(v);
   71441       int destIfNull = sqlite3VdbeMakeLabel(v);
   71442       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   71443       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   71444       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
   71445       sqlite3VdbeResolveLabel(v, destIfFalse);
   71446       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
   71447       sqlite3VdbeResolveLabel(v, destIfNull);
   71448       break;
   71449     }
   71450 #endif /* SQLITE_OMIT_SUBQUERY */
   71451 
   71452 
   71453     /*
   71454     **    x BETWEEN y AND z
   71455     **
   71456     ** This is equivalent to
   71457     **
   71458     **    x>=y AND x<=z
   71459     **
   71460     ** X is stored in pExpr->pLeft.
   71461     ** Y is stored in pExpr->pList->a[0].pExpr.
   71462     ** Z is stored in pExpr->pList->a[1].pExpr.
   71463     */
   71464     case TK_BETWEEN: {
   71465       Expr *pLeft = pExpr->pLeft;
   71466       struct ExprList_item *pLItem = pExpr->x.pList->a;
   71467       Expr *pRight = pLItem->pExpr;
   71468 
   71469       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
   71470       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   71471       testcase( regFree1==0 );
   71472       testcase( regFree2==0 );
   71473       r3 = sqlite3GetTempReg(pParse);
   71474       r4 = sqlite3GetTempReg(pParse);
   71475       codeCompare(pParse, pLeft, pRight, OP_Ge,
   71476                   r1, r2, r3, SQLITE_STOREP2);
   71477       pLItem++;
   71478       pRight = pLItem->pExpr;
   71479       sqlite3ReleaseTempReg(pParse, regFree2);
   71480       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
   71481       testcase( regFree2==0 );
   71482       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
   71483       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
   71484       sqlite3ReleaseTempReg(pParse, r3);
   71485       sqlite3ReleaseTempReg(pParse, r4);
   71486       break;
   71487     }
   71488     case TK_UPLUS: {
   71489       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
   71490       break;
   71491     }
   71492 
   71493     case TK_TRIGGER: {
   71494       /* If the opcode is TK_TRIGGER, then the expression is a reference
   71495       ** to a column in the new.* or old.* pseudo-tables available to
   71496       ** trigger programs. In this case Expr.iTable is set to 1 for the
   71497       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
   71498       ** is set to the column of the pseudo-table to read, or to -1 to
   71499       ** read the rowid field.
   71500       **
   71501       ** The expression is implemented using an OP_Param opcode. The p1
   71502       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
   71503       ** to reference another column of the old.* pseudo-table, where
   71504       ** i is the index of the column. For a new.rowid reference, p1 is
   71505       ** set to (n+1), where n is the number of columns in each pseudo-table.
   71506       ** For a reference to any other column in the new.* pseudo-table, p1
   71507       ** is set to (n+2+i), where n and i are as defined previously. For
   71508       ** example, if the table on which triggers are being fired is
   71509       ** declared as:
   71510       **
   71511       **   CREATE TABLE t1(a, b);
   71512       **
   71513       ** Then p1 is interpreted as follows:
   71514       **
   71515       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
   71516       **   p1==1   ->    old.a         p1==4   ->    new.a
   71517       **   p1==2   ->    old.b         p1==5   ->    new.b
   71518       */
   71519       Table *pTab = pExpr->pTab;
   71520       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
   71521 
   71522       assert( pExpr->iTable==0 || pExpr->iTable==1 );
   71523       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
   71524       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
   71525       assert( p1>=0 && p1<(pTab->nCol*2+2) );
   71526 
   71527       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
   71528       VdbeComment((v, "%s.%s -> $%d",
   71529         (pExpr->iTable ? "new" : "old"),
   71530         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
   71531         target
   71532       ));
   71533 
   71534 #ifndef SQLITE_OMIT_FLOATING_POINT
   71535       /* If the column has REAL affinity, it may currently be stored as an
   71536       ** integer. Use OP_RealAffinity to make sure it is really real.  */
   71537       if( pExpr->iColumn>=0
   71538        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
   71539       ){
   71540         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
   71541       }
   71542 #endif
   71543       break;
   71544     }
   71545 
   71546 
   71547     /*
   71548     ** Form A:
   71549     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   71550     **
   71551     ** Form B:
   71552     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
   71553     **
   71554     ** Form A is can be transformed into the equivalent form B as follows:
   71555     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
   71556     **        WHEN x=eN THEN rN ELSE y END
   71557     **
   71558     ** X (if it exists) is in pExpr->pLeft.
   71559     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
   71560     ** ELSE clause and no other term matches, then the result of the
   71561     ** exprssion is NULL.
   71562     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
   71563     **
   71564     ** The result of the expression is the Ri for the first matching Ei,
   71565     ** or if there is no matching Ei, the ELSE term Y, or if there is
   71566     ** no ELSE term, NULL.
   71567     */
   71568     default: assert( op==TK_CASE ); {
   71569       int endLabel;                     /* GOTO label for end of CASE stmt */
   71570       int nextCase;                     /* GOTO label for next WHEN clause */
   71571       int nExpr;                        /* 2x number of WHEN terms */
   71572       int i;                            /* Loop counter */
   71573       ExprList *pEList;                 /* List of WHEN terms */
   71574       struct ExprList_item *aListelem;  /* Array of WHEN terms */
   71575       Expr opCompare;                   /* The X==Ei expression */
   71576       Expr cacheX;                      /* Cached expression X */
   71577       Expr *pX;                         /* The X expression */
   71578       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
   71579       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
   71580 
   71581       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
   71582       assert((pExpr->x.pList->nExpr % 2) == 0);
   71583       assert(pExpr->x.pList->nExpr > 0);
   71584       pEList = pExpr->x.pList;
   71585       aListelem = pEList->a;
   71586       nExpr = pEList->nExpr;
   71587       endLabel = sqlite3VdbeMakeLabel(v);
   71588       if( (pX = pExpr->pLeft)!=0 ){
   71589         cacheX = *pX;
   71590         testcase( pX->op==TK_COLUMN );
   71591         testcase( pX->op==TK_REGISTER );
   71592         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
   71593         testcase( regFree1==0 );
   71594         cacheX.op = TK_REGISTER;
   71595         opCompare.op = TK_EQ;
   71596         opCompare.pLeft = &cacheX;
   71597         pTest = &opCompare;
   71598         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
   71599         ** The value in regFree1 might get SCopy-ed into the file result.
   71600         ** So make sure that the regFree1 register is not reused for other
   71601         ** purposes and possibly overwritten.  */
   71602         regFree1 = 0;
   71603       }
   71604       for(i=0; i<nExpr; i=i+2){
   71605         sqlite3ExprCachePush(pParse);
   71606         if( pX ){
   71607           assert( pTest!=0 );
   71608           opCompare.pRight = aListelem[i].pExpr;
   71609         }else{
   71610           pTest = aListelem[i].pExpr;
   71611         }
   71612         nextCase = sqlite3VdbeMakeLabel(v);
   71613         testcase( pTest->op==TK_COLUMN );
   71614         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
   71615         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
   71616         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
   71617         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
   71618         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
   71619         sqlite3ExprCachePop(pParse, 1);
   71620         sqlite3VdbeResolveLabel(v, nextCase);
   71621       }
   71622       if( pExpr->pRight ){
   71623         sqlite3ExprCachePush(pParse);
   71624         sqlite3ExprCode(pParse, pExpr->pRight, target);
   71625         sqlite3ExprCachePop(pParse, 1);
   71626       }else{
   71627         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
   71628       }
   71629       assert( db->mallocFailed || pParse->nErr>0
   71630            || pParse->iCacheLevel==iCacheLevel );
   71631       sqlite3VdbeResolveLabel(v, endLabel);
   71632       break;
   71633     }
   71634 #ifndef SQLITE_OMIT_TRIGGER
   71635     case TK_RAISE: {
   71636       assert( pExpr->affinity==OE_Rollback
   71637            || pExpr->affinity==OE_Abort
   71638            || pExpr->affinity==OE_Fail
   71639            || pExpr->affinity==OE_Ignore
   71640       );
   71641       if( !pParse->pTriggerTab ){
   71642         sqlite3ErrorMsg(pParse,
   71643                        "RAISE() may only be used within a trigger-program");
   71644         return 0;
   71645       }
   71646       if( pExpr->affinity==OE_Abort ){
   71647         sqlite3MayAbort(pParse);
   71648       }
   71649       assert( !ExprHasProperty(pExpr, EP_IntValue) );
   71650       if( pExpr->affinity==OE_Ignore ){
   71651         sqlite3VdbeAddOp4(
   71652             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
   71653       }else{
   71654         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
   71655       }
   71656 
   71657       break;
   71658     }
   71659 #endif
   71660   }
   71661   sqlite3ReleaseTempReg(pParse, regFree1);
   71662   sqlite3ReleaseTempReg(pParse, regFree2);
   71663   return inReg;
   71664 }
   71665 
   71666 /*
   71667 ** Generate code to evaluate an expression and store the results
   71668 ** into a register.  Return the register number where the results
   71669 ** are stored.
   71670 **
   71671 ** If the register is a temporary register that can be deallocated,
   71672 ** then write its number into *pReg.  If the result register is not
   71673 ** a temporary, then set *pReg to zero.
   71674 */
   71675 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   71676   int r1 = sqlite3GetTempReg(pParse);
   71677   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   71678   if( r2==r1 ){
   71679     *pReg = r1;
   71680   }else{
   71681     sqlite3ReleaseTempReg(pParse, r1);
   71682     *pReg = 0;
   71683   }
   71684   return r2;
   71685 }
   71686 
   71687 /*
   71688 ** Generate code that will evaluate expression pExpr and store the
   71689 ** results in register target.  The results are guaranteed to appear
   71690 ** in register target.
   71691 */
   71692 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   71693   int inReg;
   71694 
   71695   assert( target>0 && target<=pParse->nMem );
   71696   if( pExpr && pExpr->op==TK_REGISTER ){
   71697     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
   71698   }else{
   71699     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
   71700     assert( pParse->pVdbe || pParse->db->mallocFailed );
   71701     if( inReg!=target && pParse->pVdbe ){
   71702       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
   71703     }
   71704   }
   71705   return target;
   71706 }
   71707 
   71708 /*
   71709 ** Generate code that evalutes the given expression and puts the result
   71710 ** in register target.
   71711 **
   71712 ** Also make a copy of the expression results into another "cache" register
   71713 ** and modify the expression so that the next time it is evaluated,
   71714 ** the result is a copy of the cache register.
   71715 **
   71716 ** This routine is used for expressions that are used multiple
   71717 ** times.  They are evaluated once and the results of the expression
   71718 ** are reused.
   71719 */
   71720 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
   71721   Vdbe *v = pParse->pVdbe;
   71722   int inReg;
   71723   inReg = sqlite3ExprCode(pParse, pExpr, target);
   71724   assert( target>0 );
   71725   /* This routine is called for terms to INSERT or UPDATE.  And the only
   71726   ** other place where expressions can be converted into TK_REGISTER is
   71727   ** in WHERE clause processing.  So as currently implemented, there is
   71728   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
   71729   ** keep the ALWAYS() in case the conditions above change with future
   71730   ** modifications or enhancements. */
   71731   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
   71732     int iMem;
   71733     iMem = ++pParse->nMem;
   71734     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
   71735     pExpr->iTable = iMem;
   71736     pExpr->op2 = pExpr->op;
   71737     pExpr->op = TK_REGISTER;
   71738   }
   71739   return inReg;
   71740 }
   71741 
   71742 /*
   71743 ** Return TRUE if pExpr is an constant expression that is appropriate
   71744 ** for factoring out of a loop.  Appropriate expressions are:
   71745 **
   71746 **    *  Any expression that evaluates to two or more opcodes.
   71747 **
   71748 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
   71749 **       or OP_Variable that does not need to be placed in a
   71750 **       specific register.
   71751 **
   71752 ** There is no point in factoring out single-instruction constant
   71753 ** expressions that need to be placed in a particular register.
   71754 ** We could factor them out, but then we would end up adding an
   71755 ** OP_SCopy instruction to move the value into the correct register
   71756 ** later.  We might as well just use the original instruction and
   71757 ** avoid the OP_SCopy.
   71758 */
   71759 static int isAppropriateForFactoring(Expr *p){
   71760   if( !sqlite3ExprIsConstantNotJoin(p) ){
   71761     return 0;  /* Only constant expressions are appropriate for factoring */
   71762   }
   71763   if( (p->flags & EP_FixedDest)==0 ){
   71764     return 1;  /* Any constant without a fixed destination is appropriate */
   71765   }
   71766   while( p->op==TK_UPLUS ) p = p->pLeft;
   71767   switch( p->op ){
   71768 #ifndef SQLITE_OMIT_BLOB_LITERAL
   71769     case TK_BLOB:
   71770 #endif
   71771     case TK_VARIABLE:
   71772     case TK_INTEGER:
   71773     case TK_FLOAT:
   71774     case TK_NULL:
   71775     case TK_STRING: {
   71776       testcase( p->op==TK_BLOB );
   71777       testcase( p->op==TK_VARIABLE );
   71778       testcase( p->op==TK_INTEGER );
   71779       testcase( p->op==TK_FLOAT );
   71780       testcase( p->op==TK_NULL );
   71781       testcase( p->op==TK_STRING );
   71782       /* Single-instruction constants with a fixed destination are
   71783       ** better done in-line.  If we factor them, they will just end
   71784       ** up generating an OP_SCopy to move the value to the destination
   71785       ** register. */
   71786       return 0;
   71787     }
   71788     case TK_UMINUS: {
   71789       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
   71790         return 0;
   71791       }
   71792       break;
   71793     }
   71794     default: {
   71795       break;
   71796     }
   71797   }
   71798   return 1;
   71799 }
   71800 
   71801 /*
   71802 ** If pExpr is a constant expression that is appropriate for
   71803 ** factoring out of a loop, then evaluate the expression
   71804 ** into a register and convert the expression into a TK_REGISTER
   71805 ** expression.
   71806 */
   71807 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
   71808   Parse *pParse = pWalker->pParse;
   71809   switch( pExpr->op ){
   71810     case TK_IN:
   71811     case TK_REGISTER: {
   71812       return WRC_Prune;
   71813     }
   71814     case TK_FUNCTION:
   71815     case TK_AGG_FUNCTION:
   71816     case TK_CONST_FUNC: {
   71817       /* The arguments to a function have a fixed destination.
   71818       ** Mark them this way to avoid generated unneeded OP_SCopy
   71819       ** instructions.
   71820       */
   71821       ExprList *pList = pExpr->x.pList;
   71822       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   71823       if( pList ){
   71824         int i = pList->nExpr;
   71825         struct ExprList_item *pItem = pList->a;
   71826         for(; i>0; i--, pItem++){
   71827           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
   71828         }
   71829       }
   71830       break;
   71831     }
   71832   }
   71833   if( isAppropriateForFactoring(pExpr) ){
   71834     int r1 = ++pParse->nMem;
   71835     int r2;
   71836     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
   71837     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
   71838     pExpr->op2 = pExpr->op;
   71839     pExpr->op = TK_REGISTER;
   71840     pExpr->iTable = r2;
   71841     return WRC_Prune;
   71842   }
   71843   return WRC_Continue;
   71844 }
   71845 
   71846 /*
   71847 ** Preevaluate constant subexpressions within pExpr and store the
   71848 ** results in registers.  Modify pExpr so that the constant subexpresions
   71849 ** are TK_REGISTER opcodes that refer to the precomputed values.
   71850 **
   71851 ** This routine is a no-op if the jump to the cookie-check code has
   71852 ** already occur.  Since the cookie-check jump is generated prior to
   71853 ** any other serious processing, this check ensures that there is no
   71854 ** way to accidently bypass the constant initializations.
   71855 **
   71856 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
   71857 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
   71858 ** interface.  This allows test logic to verify that the same answer is
   71859 ** obtained for queries regardless of whether or not constants are
   71860 ** precomputed into registers or if they are inserted in-line.
   71861 */
   71862 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
   71863   Walker w;
   71864   if( pParse->cookieGoto ) return;
   71865   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
   71866   w.xExprCallback = evalConstExpr;
   71867   w.xSelectCallback = 0;
   71868   w.pParse = pParse;
   71869   sqlite3WalkExpr(&w, pExpr);
   71870 }
   71871 
   71872 
   71873 /*
   71874 ** Generate code that pushes the value of every element of the given
   71875 ** expression list into a sequence of registers beginning at target.
   71876 **
   71877 ** Return the number of elements evaluated.
   71878 */
   71879 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
   71880   Parse *pParse,     /* Parsing context */
   71881   ExprList *pList,   /* The expression list to be coded */
   71882   int target,        /* Where to write results */
   71883   int doHardCopy     /* Make a hard copy of every element */
   71884 ){
   71885   struct ExprList_item *pItem;
   71886   int i, n;
   71887   assert( pList!=0 );
   71888   assert( target>0 );
   71889   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
   71890   n = pList->nExpr;
   71891   for(pItem=pList->a, i=0; i<n; i++, pItem++){
   71892     Expr *pExpr = pItem->pExpr;
   71893     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
   71894     if( inReg!=target+i ){
   71895       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
   71896                         inReg, target+i);
   71897     }
   71898   }
   71899   return n;
   71900 }
   71901 
   71902 /*
   71903 ** Generate code for a BETWEEN operator.
   71904 **
   71905 **    x BETWEEN y AND z
   71906 **
   71907 ** The above is equivalent to
   71908 **
   71909 **    x>=y AND x<=z
   71910 **
   71911 ** Code it as such, taking care to do the common subexpression
   71912 ** elementation of x.
   71913 */
   71914 static void exprCodeBetween(
   71915   Parse *pParse,    /* Parsing and code generating context */
   71916   Expr *pExpr,      /* The BETWEEN expression */
   71917   int dest,         /* Jump here if the jump is taken */
   71918   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
   71919   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
   71920 ){
   71921   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
   71922   Expr compLeft;    /* The  x>=y  term */
   71923   Expr compRight;   /* The  x<=z  term */
   71924   Expr exprX;       /* The  x  subexpression */
   71925   int regFree1 = 0; /* Temporary use register */
   71926 
   71927   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   71928   exprX = *pExpr->pLeft;
   71929   exprAnd.op = TK_AND;
   71930   exprAnd.pLeft = &compLeft;
   71931   exprAnd.pRight = &compRight;
   71932   compLeft.op = TK_GE;
   71933   compLeft.pLeft = &exprX;
   71934   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
   71935   compRight.op = TK_LE;
   71936   compRight.pLeft = &exprX;
   71937   compRight.pRight = pExpr->x.pList->a[1].pExpr;
   71938   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
   71939   exprX.op = TK_REGISTER;
   71940   if( jumpIfTrue ){
   71941     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
   71942   }else{
   71943     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
   71944   }
   71945   sqlite3ReleaseTempReg(pParse, regFree1);
   71946 
   71947   /* Ensure adequate test coverage */
   71948   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
   71949   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
   71950   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
   71951   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
   71952   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
   71953   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
   71954   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
   71955   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
   71956 }
   71957 
   71958 /*
   71959 ** Generate code for a boolean expression such that a jump is made
   71960 ** to the label "dest" if the expression is true but execution
   71961 ** continues straight thru if the expression is false.
   71962 **
   71963 ** If the expression evaluates to NULL (neither true nor false), then
   71964 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
   71965 **
   71966 ** This code depends on the fact that certain token values (ex: TK_EQ)
   71967 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
   71968 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
   71969 ** the make process cause these values to align.  Assert()s in the code
   71970 ** below verify that the numbers are aligned correctly.
   71971 */
   71972 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   71973   Vdbe *v = pParse->pVdbe;
   71974   int op = 0;
   71975   int regFree1 = 0;
   71976   int regFree2 = 0;
   71977   int r1, r2;
   71978 
   71979   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   71980   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
   71981   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
   71982   op = pExpr->op;
   71983   switch( op ){
   71984     case TK_AND: {
   71985       int d2 = sqlite3VdbeMakeLabel(v);
   71986       testcase( jumpIfNull==0 );
   71987       sqlite3ExprCachePush(pParse);
   71988       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
   71989       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   71990       sqlite3VdbeResolveLabel(v, d2);
   71991       sqlite3ExprCachePop(pParse, 1);
   71992       break;
   71993     }
   71994     case TK_OR: {
   71995       testcase( jumpIfNull==0 );
   71996       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   71997       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
   71998       break;
   71999     }
   72000     case TK_NOT: {
   72001       testcase( jumpIfNull==0 );
   72002       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   72003       break;
   72004     }
   72005     case TK_LT:
   72006     case TK_LE:
   72007     case TK_GT:
   72008     case TK_GE:
   72009     case TK_NE:
   72010     case TK_EQ: {
   72011       assert( TK_LT==OP_Lt );
   72012       assert( TK_LE==OP_Le );
   72013       assert( TK_GT==OP_Gt );
   72014       assert( TK_GE==OP_Ge );
   72015       assert( TK_EQ==OP_Eq );
   72016       assert( TK_NE==OP_Ne );
   72017       testcase( op==TK_LT );
   72018       testcase( op==TK_LE );
   72019       testcase( op==TK_GT );
   72020       testcase( op==TK_GE );
   72021       testcase( op==TK_EQ );
   72022       testcase( op==TK_NE );
   72023       testcase( jumpIfNull==0 );
   72024       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72025       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   72026       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   72027                   r1, r2, dest, jumpIfNull);
   72028       testcase( regFree1==0 );
   72029       testcase( regFree2==0 );
   72030       break;
   72031     }
   72032     case TK_IS:
   72033     case TK_ISNOT: {
   72034       testcase( op==TK_IS );
   72035       testcase( op==TK_ISNOT );
   72036       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72037       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   72038       op = (op==TK_IS) ? TK_EQ : TK_NE;
   72039       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   72040                   r1, r2, dest, SQLITE_NULLEQ);
   72041       testcase( regFree1==0 );
   72042       testcase( regFree2==0 );
   72043       break;
   72044     }
   72045     case TK_ISNULL:
   72046     case TK_NOTNULL: {
   72047       assert( TK_ISNULL==OP_IsNull );
   72048       assert( TK_NOTNULL==OP_NotNull );
   72049       testcase( op==TK_ISNULL );
   72050       testcase( op==TK_NOTNULL );
   72051       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72052       sqlite3VdbeAddOp2(v, op, r1, dest);
   72053       testcase( regFree1==0 );
   72054       break;
   72055     }
   72056     case TK_BETWEEN: {
   72057       testcase( jumpIfNull==0 );
   72058       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
   72059       break;
   72060     }
   72061     case TK_IN: {
   72062       int destIfFalse = sqlite3VdbeMakeLabel(v);
   72063       int destIfNull = jumpIfNull ? dest : destIfFalse;
   72064       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
   72065       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
   72066       sqlite3VdbeResolveLabel(v, destIfFalse);
   72067       break;
   72068     }
   72069     default: {
   72070       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   72071       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
   72072       testcase( regFree1==0 );
   72073       testcase( jumpIfNull==0 );
   72074       break;
   72075     }
   72076   }
   72077   sqlite3ReleaseTempReg(pParse, regFree1);
   72078   sqlite3ReleaseTempReg(pParse, regFree2);
   72079 }
   72080 
   72081 /*
   72082 ** Generate code for a boolean expression such that a jump is made
   72083 ** to the label "dest" if the expression is false but execution
   72084 ** continues straight thru if the expression is true.
   72085 **
   72086 ** If the expression evaluates to NULL (neither true nor false) then
   72087 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
   72088 ** is 0.
   72089 */
   72090 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
   72091   Vdbe *v = pParse->pVdbe;
   72092   int op = 0;
   72093   int regFree1 = 0;
   72094   int regFree2 = 0;
   72095   int r1, r2;
   72096 
   72097   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   72098   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
   72099   if( pExpr==0 )    return;
   72100 
   72101   /* The value of pExpr->op and op are related as follows:
   72102   **
   72103   **       pExpr->op            op
   72104   **       ---------          ----------
   72105   **       TK_ISNULL          OP_NotNull
   72106   **       TK_NOTNULL         OP_IsNull
   72107   **       TK_NE              OP_Eq
   72108   **       TK_EQ              OP_Ne
   72109   **       TK_GT              OP_Le
   72110   **       TK_LE              OP_Gt
   72111   **       TK_GE              OP_Lt
   72112   **       TK_LT              OP_Ge
   72113   **
   72114   ** For other values of pExpr->op, op is undefined and unused.
   72115   ** The value of TK_ and OP_ constants are arranged such that we
   72116   ** can compute the mapping above using the following expression.
   72117   ** Assert()s verify that the computation is correct.
   72118   */
   72119   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
   72120 
   72121   /* Verify correct alignment of TK_ and OP_ constants
   72122   */
   72123   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
   72124   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
   72125   assert( pExpr->op!=TK_NE || op==OP_Eq );
   72126   assert( pExpr->op!=TK_EQ || op==OP_Ne );
   72127   assert( pExpr->op!=TK_LT || op==OP_Ge );
   72128   assert( pExpr->op!=TK_LE || op==OP_Gt );
   72129   assert( pExpr->op!=TK_GT || op==OP_Le );
   72130   assert( pExpr->op!=TK_GE || op==OP_Lt );
   72131 
   72132   switch( pExpr->op ){
   72133     case TK_AND: {
   72134       testcase( jumpIfNull==0 );
   72135       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
   72136       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   72137       break;
   72138     }
   72139     case TK_OR: {
   72140       int d2 = sqlite3VdbeMakeLabel(v);
   72141       testcase( jumpIfNull==0 );
   72142       sqlite3ExprCachePush(pParse);
   72143       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
   72144       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
   72145       sqlite3VdbeResolveLabel(v, d2);
   72146       sqlite3ExprCachePop(pParse, 1);
   72147       break;
   72148     }
   72149     case TK_NOT: {
   72150       testcase( jumpIfNull==0 );
   72151       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
   72152       break;
   72153     }
   72154     case TK_LT:
   72155     case TK_LE:
   72156     case TK_GT:
   72157     case TK_GE:
   72158     case TK_NE:
   72159     case TK_EQ: {
   72160       testcase( op==TK_LT );
   72161       testcase( op==TK_LE );
   72162       testcase( op==TK_GT );
   72163       testcase( op==TK_GE );
   72164       testcase( op==TK_EQ );
   72165       testcase( op==TK_NE );
   72166       testcase( jumpIfNull==0 );
   72167       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72168       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   72169       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   72170                   r1, r2, dest, jumpIfNull);
   72171       testcase( regFree1==0 );
   72172       testcase( regFree2==0 );
   72173       break;
   72174     }
   72175     case TK_IS:
   72176     case TK_ISNOT: {
   72177       testcase( pExpr->op==TK_IS );
   72178       testcase( pExpr->op==TK_ISNOT );
   72179       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72180       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
   72181       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
   72182       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
   72183                   r1, r2, dest, SQLITE_NULLEQ);
   72184       testcase( regFree1==0 );
   72185       testcase( regFree2==0 );
   72186       break;
   72187     }
   72188     case TK_ISNULL:
   72189     case TK_NOTNULL: {
   72190       testcase( op==TK_ISNULL );
   72191       testcase( op==TK_NOTNULL );
   72192       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
   72193       sqlite3VdbeAddOp2(v, op, r1, dest);
   72194       testcase( regFree1==0 );
   72195       break;
   72196     }
   72197     case TK_BETWEEN: {
   72198       testcase( jumpIfNull==0 );
   72199       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
   72200       break;
   72201     }
   72202     case TK_IN: {
   72203       if( jumpIfNull ){
   72204         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
   72205       }else{
   72206         int destIfNull = sqlite3VdbeMakeLabel(v);
   72207         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
   72208         sqlite3VdbeResolveLabel(v, destIfNull);
   72209       }
   72210       break;
   72211     }
   72212     default: {
   72213       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
   72214       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
   72215       testcase( regFree1==0 );
   72216       testcase( jumpIfNull==0 );
   72217       break;
   72218     }
   72219   }
   72220   sqlite3ReleaseTempReg(pParse, regFree1);
   72221   sqlite3ReleaseTempReg(pParse, regFree2);
   72222 }
   72223 
   72224 /*
   72225 ** Do a deep comparison of two expression trees.  Return 0 if the two
   72226 ** expressions are completely identical.  Return 1 if they differ only
   72227 ** by a COLLATE operator at the top level.  Return 2 if there are differences
   72228 ** other than the top-level COLLATE operator.
   72229 **
   72230 ** Sometimes this routine will return 2 even if the two expressions
   72231 ** really are equivalent.  If we cannot prove that the expressions are
   72232 ** identical, we return 2 just to be safe.  So if this routine
   72233 ** returns 2, then you do not really know for certain if the two
   72234 ** expressions are the same.  But if you get a 0 or 1 return, then you
   72235 ** can be sure the expressions are the same.  In the places where
   72236 ** this routine is used, it does not hurt to get an extra 2 - that
   72237 ** just might result in some slightly slower code.  But returning
   72238 ** an incorrect 0 or 1 could lead to a malfunction.
   72239 */
   72240 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
   72241   if( pA==0||pB==0 ){
   72242     return pB==pA ? 0 : 2;
   72243   }
   72244   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
   72245   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
   72246   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
   72247     return 2;
   72248   }
   72249   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
   72250   if( pA->op!=pB->op ) return 2;
   72251   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
   72252   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
   72253   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
   72254   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
   72255   if( ExprHasProperty(pA, EP_IntValue) ){
   72256     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
   72257       return 2;
   72258     }
   72259   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
   72260     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
   72261     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
   72262       return 2;
   72263     }
   72264   }
   72265   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
   72266   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
   72267   return 0;
   72268 }
   72269 
   72270 /*
   72271 ** Compare two ExprList objects.  Return 0 if they are identical and
   72272 ** non-zero if they differ in any way.
   72273 **
   72274 ** This routine might return non-zero for equivalent ExprLists.  The
   72275 ** only consequence will be disabled optimizations.  But this routine
   72276 ** must never return 0 if the two ExprList objects are different, or
   72277 ** a malfunction will result.
   72278 **
   72279 ** Two NULL pointers are considered to be the same.  But a NULL pointer
   72280 ** always differs from a non-NULL pointer.
   72281 */
   72282 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
   72283   int i;
   72284   if( pA==0 && pB==0 ) return 0;
   72285   if( pA==0 || pB==0 ) return 1;
   72286   if( pA->nExpr!=pB->nExpr ) return 1;
   72287   for(i=0; i<pA->nExpr; i++){
   72288     Expr *pExprA = pA->a[i].pExpr;
   72289     Expr *pExprB = pB->a[i].pExpr;
   72290     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
   72291     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
   72292   }
   72293   return 0;
   72294 }
   72295 
   72296 /*
   72297 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
   72298 ** the new element.  Return a negative number if malloc fails.
   72299 */
   72300 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
   72301   int i;
   72302   pInfo->aCol = sqlite3ArrayAllocate(
   72303        db,
   72304        pInfo->aCol,
   72305        sizeof(pInfo->aCol[0]),
   72306        3,
   72307        &pInfo->nColumn,
   72308        &pInfo->nColumnAlloc,
   72309        &i
   72310   );
   72311   return i;
   72312 }
   72313 
   72314 /*
   72315 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
   72316 ** the new element.  Return a negative number if malloc fails.
   72317 */
   72318 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   72319   int i;
   72320   pInfo->aFunc = sqlite3ArrayAllocate(
   72321        db,
   72322        pInfo->aFunc,
   72323        sizeof(pInfo->aFunc[0]),
   72324        3,
   72325        &pInfo->nFunc,
   72326        &pInfo->nFuncAlloc,
   72327        &i
   72328   );
   72329   return i;
   72330 }
   72331 
   72332 /*
   72333 ** This is the xExprCallback for a tree walker.  It is used to
   72334 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
   72335 ** for additional information.
   72336 */
   72337 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   72338   int i;
   72339   NameContext *pNC = pWalker->u.pNC;
   72340   Parse *pParse = pNC->pParse;
   72341   SrcList *pSrcList = pNC->pSrcList;
   72342   AggInfo *pAggInfo = pNC->pAggInfo;
   72343 
   72344   switch( pExpr->op ){
   72345     case TK_AGG_COLUMN:
   72346     case TK_COLUMN: {
   72347       testcase( pExpr->op==TK_AGG_COLUMN );
   72348       testcase( pExpr->op==TK_COLUMN );
   72349       /* Check to see if the column is in one of the tables in the FROM
   72350       ** clause of the aggregate query */
   72351       if( ALWAYS(pSrcList!=0) ){
   72352         struct SrcList_item *pItem = pSrcList->a;
   72353         for(i=0; i<pSrcList->nSrc; i++, pItem++){
   72354           struct AggInfo_col *pCol;
   72355           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   72356           if( pExpr->iTable==pItem->iCursor ){
   72357             /* If we reach this point, it means that pExpr refers to a table
   72358             ** that is in the FROM clause of the aggregate query.
   72359             **
   72360             ** Make an entry for the column in pAggInfo->aCol[] if there
   72361             ** is not an entry there already.
   72362             */
   72363             int k;
   72364             pCol = pAggInfo->aCol;
   72365             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
   72366               if( pCol->iTable==pExpr->iTable &&
   72367                   pCol->iColumn==pExpr->iColumn ){
   72368                 break;
   72369               }
   72370             }
   72371             if( (k>=pAggInfo->nColumn)
   72372              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
   72373             ){
   72374               pCol = &pAggInfo->aCol[k];
   72375               pCol->pTab = pExpr->pTab;
   72376               pCol->iTable = pExpr->iTable;
   72377               pCol->iColumn = pExpr->iColumn;
   72378               pCol->iMem = ++pParse->nMem;
   72379               pCol->iSorterColumn = -1;
   72380               pCol->pExpr = pExpr;
   72381               if( pAggInfo->pGroupBy ){
   72382                 int j, n;
   72383                 ExprList *pGB = pAggInfo->pGroupBy;
   72384                 struct ExprList_item *pTerm = pGB->a;
   72385                 n = pGB->nExpr;
   72386                 for(j=0; j<n; j++, pTerm++){
   72387                   Expr *pE = pTerm->pExpr;
   72388                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
   72389                       pE->iColumn==pExpr->iColumn ){
   72390                     pCol->iSorterColumn = j;
   72391                     break;
   72392                   }
   72393                 }
   72394               }
   72395               if( pCol->iSorterColumn<0 ){
   72396                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
   72397               }
   72398             }
   72399             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
   72400             ** because it was there before or because we just created it).
   72401             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
   72402             ** pAggInfo->aCol[] entry.
   72403             */
   72404             ExprSetIrreducible(pExpr);
   72405             pExpr->pAggInfo = pAggInfo;
   72406             pExpr->op = TK_AGG_COLUMN;
   72407             pExpr->iAgg = (i16)k;
   72408             break;
   72409           } /* endif pExpr->iTable==pItem->iCursor */
   72410         } /* end loop over pSrcList */
   72411       }
   72412       return WRC_Prune;
   72413     }
   72414     case TK_AGG_FUNCTION: {
   72415       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
   72416       ** to be ignored */
   72417       if( pNC->nDepth==0 ){
   72418         /* Check to see if pExpr is a duplicate of another aggregate
   72419         ** function that is already in the pAggInfo structure
   72420         */
   72421         struct AggInfo_func *pItem = pAggInfo->aFunc;
   72422         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
   72423           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
   72424             break;
   72425           }
   72426         }
   72427         if( i>=pAggInfo->nFunc ){
   72428           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
   72429           */
   72430           u8 enc = ENC(pParse->db);
   72431           i = addAggInfoFunc(pParse->db, pAggInfo);
   72432           if( i>=0 ){
   72433             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   72434             pItem = &pAggInfo->aFunc[i];
   72435             pItem->pExpr = pExpr;
   72436             pItem->iMem = ++pParse->nMem;
   72437             assert( !ExprHasProperty(pExpr, EP_IntValue) );
   72438             pItem->pFunc = sqlite3FindFunction(pParse->db,
   72439                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
   72440                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
   72441             if( pExpr->flags & EP_Distinct ){
   72442               pItem->iDistinct = pParse->nTab++;
   72443             }else{
   72444               pItem->iDistinct = -1;
   72445             }
   72446           }
   72447         }
   72448         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
   72449         */
   72450         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
   72451         ExprSetIrreducible(pExpr);
   72452         pExpr->iAgg = (i16)i;
   72453         pExpr->pAggInfo = pAggInfo;
   72454         return WRC_Prune;
   72455       }
   72456     }
   72457   }
   72458   return WRC_Continue;
   72459 }
   72460 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
   72461   NameContext *pNC = pWalker->u.pNC;
   72462   if( pNC->nDepth==0 ){
   72463     pNC->nDepth++;
   72464     sqlite3WalkSelect(pWalker, pSelect);
   72465     pNC->nDepth--;
   72466     return WRC_Prune;
   72467   }else{
   72468     return WRC_Continue;
   72469   }
   72470 }
   72471 
   72472 /*
   72473 ** Analyze the given expression looking for aggregate functions and
   72474 ** for variables that need to be added to the pParse->aAgg[] array.
   72475 ** Make additional entries to the pParse->aAgg[] array as necessary.
   72476 **
   72477 ** This routine should only be called after the expression has been
   72478 ** analyzed by sqlite3ResolveExprNames().
   72479 */
   72480 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   72481   Walker w;
   72482   w.xExprCallback = analyzeAggregate;
   72483   w.xSelectCallback = analyzeAggregatesInSelect;
   72484   w.u.pNC = pNC;
   72485   assert( pNC->pSrcList!=0 );
   72486   sqlite3WalkExpr(&w, pExpr);
   72487 }
   72488 
   72489 /*
   72490 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
   72491 ** expression list.  Return the number of errors.
   72492 **
   72493 ** If an error is found, the analysis is cut short.
   72494 */
   72495 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
   72496   struct ExprList_item *pItem;
   72497   int i;
   72498   if( pList ){
   72499     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
   72500       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
   72501     }
   72502   }
   72503 }
   72504 
   72505 /*
   72506 ** Allocate a single new register for use to hold some intermediate result.
   72507 */
   72508 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
   72509   if( pParse->nTempReg==0 ){
   72510     return ++pParse->nMem;
   72511   }
   72512   return pParse->aTempReg[--pParse->nTempReg];
   72513 }
   72514 
   72515 /*
   72516 ** Deallocate a register, making available for reuse for some other
   72517 ** purpose.
   72518 **
   72519 ** If a register is currently being used by the column cache, then
   72520 ** the dallocation is deferred until the column cache line that uses
   72521 ** the register becomes stale.
   72522 */
   72523 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
   72524   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
   72525     int i;
   72526     struct yColCache *p;
   72527     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
   72528       if( p->iReg==iReg ){
   72529         p->tempReg = 1;
   72530         return;
   72531       }
   72532     }
   72533     pParse->aTempReg[pParse->nTempReg++] = iReg;
   72534   }
   72535 }
   72536 
   72537 /*
   72538 ** Allocate or deallocate a block of nReg consecutive registers
   72539 */
   72540 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
   72541   int i, n;
   72542   i = pParse->iRangeReg;
   72543   n = pParse->nRangeReg;
   72544   if( nReg<=n ){
   72545     assert( !usedAsColumnCache(pParse, i, i+n-1) );
   72546     pParse->iRangeReg += nReg;
   72547     pParse->nRangeReg -= nReg;
   72548   }else{
   72549     i = pParse->nMem+1;
   72550     pParse->nMem += nReg;
   72551   }
   72552   return i;
   72553 }
   72554 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
   72555   sqlite3ExprCacheRemove(pParse, iReg, nReg);
   72556   if( nReg>pParse->nRangeReg ){
   72557     pParse->nRangeReg = nReg;
   72558     pParse->iRangeReg = iReg;
   72559   }
   72560 }
   72561 
   72562 /************** End of expr.c ************************************************/
   72563 /************** Begin file alter.c *******************************************/
   72564 /*
   72565 ** 2005 February 15
   72566 **
   72567 ** The author disclaims copyright to this source code.  In place of
   72568 ** a legal notice, here is a blessing:
   72569 **
   72570 **    May you do good and not evil.
   72571 **    May you find forgiveness for yourself and forgive others.
   72572 **    May you share freely, never taking more than you give.
   72573 **
   72574 *************************************************************************
   72575 ** This file contains C code routines that used to generate VDBE code
   72576 ** that implements the ALTER TABLE command.
   72577 */
   72578 
   72579 /*
   72580 ** The code in this file only exists if we are not omitting the
   72581 ** ALTER TABLE logic from the build.
   72582 */
   72583 #ifndef SQLITE_OMIT_ALTERTABLE
   72584 
   72585 
   72586 /*
   72587 ** This function is used by SQL generated to implement the
   72588 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
   72589 ** CREATE INDEX command. The second is a table name. The table name in
   72590 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
   72591 ** argument and the result returned. Examples:
   72592 **
   72593 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
   72594 **     -> 'CREATE TABLE def(a, b, c)'
   72595 **
   72596 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
   72597 **     -> 'CREATE INDEX i ON def(a, b, c)'
   72598 */
   72599 static void renameTableFunc(
   72600   sqlite3_context *context,
   72601   int NotUsed,
   72602   sqlite3_value **argv
   72603 ){
   72604   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   72605   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   72606 
   72607   int token;
   72608   Token tname;
   72609   unsigned char const *zCsr = zSql;
   72610   int len = 0;
   72611   char *zRet;
   72612 
   72613   sqlite3 *db = sqlite3_context_db_handle(context);
   72614 
   72615   UNUSED_PARAMETER(NotUsed);
   72616 
   72617   /* The principle used to locate the table name in the CREATE TABLE
   72618   ** statement is that the table name is the first non-space token that
   72619   ** is immediately followed by a TK_LP or TK_USING token.
   72620   */
   72621   if( zSql ){
   72622     do {
   72623       if( !*zCsr ){
   72624         /* Ran out of input before finding an opening bracket. Return NULL. */
   72625         return;
   72626       }
   72627 
   72628       /* Store the token that zCsr points to in tname. */
   72629       tname.z = (char*)zCsr;
   72630       tname.n = len;
   72631 
   72632       /* Advance zCsr to the next token. Store that token type in 'token',
   72633       ** and its length in 'len' (to be used next iteration of this loop).
   72634       */
   72635       do {
   72636         zCsr += len;
   72637         len = sqlite3GetToken(zCsr, &token);
   72638       } while( token==TK_SPACE );
   72639       assert( len>0 );
   72640     } while( token!=TK_LP && token!=TK_USING );
   72641 
   72642     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   72643        zTableName, tname.z+tname.n);
   72644     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   72645   }
   72646 }
   72647 
   72648 /*
   72649 ** This C function implements an SQL user function that is used by SQL code
   72650 ** generated by the ALTER TABLE ... RENAME command to modify the definition
   72651 ** of any foreign key constraints that use the table being renamed as the
   72652 ** parent table. It is passed three arguments:
   72653 **
   72654 **   1) The complete text of the CREATE TABLE statement being modified,
   72655 **   2) The old name of the table being renamed, and
   72656 **   3) The new name of the table being renamed.
   72657 **
   72658 ** It returns the new CREATE TABLE statement. For example:
   72659 **
   72660 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
   72661 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
   72662 */
   72663 #ifndef SQLITE_OMIT_FOREIGN_KEY
   72664 static void renameParentFunc(
   72665   sqlite3_context *context,
   72666   int NotUsed,
   72667   sqlite3_value **argv
   72668 ){
   72669   sqlite3 *db = sqlite3_context_db_handle(context);
   72670   char *zOutput = 0;
   72671   char *zResult;
   72672   unsigned char const *zInput = sqlite3_value_text(argv[0]);
   72673   unsigned char const *zOld = sqlite3_value_text(argv[1]);
   72674   unsigned char const *zNew = sqlite3_value_text(argv[2]);
   72675 
   72676   unsigned const char *z;         /* Pointer to token */
   72677   int n;                          /* Length of token z */
   72678   int token;                      /* Type of token */
   72679 
   72680   UNUSED_PARAMETER(NotUsed);
   72681   for(z=zInput; *z; z=z+n){
   72682     n = sqlite3GetToken(z, &token);
   72683     if( token==TK_REFERENCES ){
   72684       char *zParent;
   72685       do {
   72686         z += n;
   72687         n = sqlite3GetToken(z, &token);
   72688       }while( token==TK_SPACE );
   72689 
   72690       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   72691       if( zParent==0 ) break;
   72692       sqlite3Dequote(zParent);
   72693       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   72694         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
   72695             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
   72696         );
   72697         sqlite3DbFree(db, zOutput);
   72698         zOutput = zOut;
   72699         zInput = &z[n];
   72700       }
   72701       sqlite3DbFree(db, zParent);
   72702     }
   72703   }
   72704 
   72705   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
   72706   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
   72707   sqlite3DbFree(db, zOutput);
   72708 }
   72709 #endif
   72710 
   72711 #ifndef SQLITE_OMIT_TRIGGER
   72712 /* This function is used by SQL generated to implement the
   72713 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
   72714 ** statement. The second is a table name. The table name in the CREATE
   72715 ** TRIGGER statement is replaced with the third argument and the result
   72716 ** returned. This is analagous to renameTableFunc() above, except for CREATE
   72717 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
   72718 */
   72719 static void renameTriggerFunc(
   72720   sqlite3_context *context,
   72721   int NotUsed,
   72722   sqlite3_value **argv
   72723 ){
   72724   unsigned char const *zSql = sqlite3_value_text(argv[0]);
   72725   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
   72726 
   72727   int token;
   72728   Token tname;
   72729   int dist = 3;
   72730   unsigned char const *zCsr = zSql;
   72731   int len = 0;
   72732   char *zRet;
   72733   sqlite3 *db = sqlite3_context_db_handle(context);
   72734 
   72735   UNUSED_PARAMETER(NotUsed);
   72736 
   72737   /* The principle used to locate the table name in the CREATE TRIGGER
   72738   ** statement is that the table name is the first token that is immediatedly
   72739   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
   72740   ** of TK_WHEN, TK_BEGIN or TK_FOR.
   72741   */
   72742   if( zSql ){
   72743     do {
   72744 
   72745       if( !*zCsr ){
   72746         /* Ran out of input before finding the table name. Return NULL. */
   72747         return;
   72748       }
   72749 
   72750       /* Store the token that zCsr points to in tname. */
   72751       tname.z = (char*)zCsr;
   72752       tname.n = len;
   72753 
   72754       /* Advance zCsr to the next token. Store that token type in 'token',
   72755       ** and its length in 'len' (to be used next iteration of this loop).
   72756       */
   72757       do {
   72758         zCsr += len;
   72759         len = sqlite3GetToken(zCsr, &token);
   72760       }while( token==TK_SPACE );
   72761       assert( len>0 );
   72762 
   72763       /* Variable 'dist' stores the number of tokens read since the most
   72764       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
   72765       ** token is read and 'dist' equals 2, the condition stated above
   72766       ** to be met.
   72767       **
   72768       ** Note that ON cannot be a database, table or column name, so
   72769       ** there is no need to worry about syntax like
   72770       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
   72771       */
   72772       dist++;
   72773       if( token==TK_DOT || token==TK_ON ){
   72774         dist = 0;
   72775       }
   72776     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   72777 
   72778     /* Variable tname now contains the token that is the old table-name
   72779     ** in the CREATE TRIGGER statement.
   72780     */
   72781     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
   72782        zTableName, tname.z+tname.n);
   72783     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   72784   }
   72785 }
   72786 #endif   /* !SQLITE_OMIT_TRIGGER */
   72787 
   72788 /*
   72789 ** Register built-in functions used to help implement ALTER TABLE
   72790 */
   72791 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
   72792   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
   72793     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
   72794 #ifndef SQLITE_OMIT_TRIGGER
   72795     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
   72796 #endif
   72797 #ifndef SQLITE_OMIT_FOREIGN_KEY
   72798     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
   72799 #endif
   72800   };
   72801   int i;
   72802   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   72803   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
   72804 
   72805   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
   72806     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   72807   }
   72808 }
   72809 
   72810 /*
   72811 ** This function is used to create the text of expressions of the form:
   72812 **
   72813 **   name=<constant1> OR name=<constant2> OR ...
   72814 **
   72815 ** If argument zWhere is NULL, then a pointer string containing the text
   72816 ** "name=<constant>" is returned, where <constant> is the quoted version
   72817 ** of the string passed as argument zConstant. The returned buffer is
   72818 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
   72819 ** caller to ensure that it is eventually freed.
   72820 **
   72821 ** If argument zWhere is not NULL, then the string returned is
   72822 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
   72823 ** In this case zWhere is passed to sqlite3DbFree() before returning.
   72824 **
   72825 */
   72826 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
   72827   char *zNew;
   72828   if( !zWhere ){
   72829     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
   72830   }else{
   72831     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
   72832     sqlite3DbFree(db, zWhere);
   72833   }
   72834   return zNew;
   72835 }
   72836 
   72837 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   72838 /*
   72839 ** Generate the text of a WHERE expression which can be used to select all
   72840 ** tables that have foreign key constraints that refer to table pTab (i.e.
   72841 ** constraints for which pTab is the parent table) from the sqlite_master
   72842 ** table.
   72843 */
   72844 static char *whereForeignKeys(Parse *pParse, Table *pTab){
   72845   FKey *p;
   72846   char *zWhere = 0;
   72847   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   72848     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
   72849   }
   72850   return zWhere;
   72851 }
   72852 #endif
   72853 
   72854 /*
   72855 ** Generate the text of a WHERE expression which can be used to select all
   72856 ** temporary triggers on table pTab from the sqlite_temp_master table. If
   72857 ** table pTab has no temporary triggers, or is itself stored in the
   72858 ** temporary database, NULL is returned.
   72859 */
   72860 static char *whereTempTriggers(Parse *pParse, Table *pTab){
   72861   Trigger *pTrig;
   72862   char *zWhere = 0;
   72863   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
   72864 
   72865   /* If the table is not located in the temp-db (in which case NULL is
   72866   ** returned, loop through the tables list of triggers. For each trigger
   72867   ** that is not part of the temp-db schema, add a clause to the WHERE
   72868   ** expression being built up in zWhere.
   72869   */
   72870   if( pTab->pSchema!=pTempSchema ){
   72871     sqlite3 *db = pParse->db;
   72872     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   72873       if( pTrig->pSchema==pTempSchema ){
   72874         zWhere = whereOrName(db, zWhere, pTrig->zName);
   72875       }
   72876     }
   72877   }
   72878   if( zWhere ){
   72879     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
   72880     sqlite3DbFree(pParse->db, zWhere);
   72881     zWhere = zNew;
   72882   }
   72883   return zWhere;
   72884 }
   72885 
   72886 /*
   72887 ** Generate code to drop and reload the internal representation of table
   72888 ** pTab from the database, including triggers and temporary triggers.
   72889 ** Argument zName is the name of the table in the database schema at
   72890 ** the time the generated code is executed. This can be different from
   72891 ** pTab->zName if this function is being called to code part of an
   72892 ** "ALTER TABLE RENAME TO" statement.
   72893 */
   72894 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
   72895   Vdbe *v;
   72896   char *zWhere;
   72897   int iDb;                   /* Index of database containing pTab */
   72898 #ifndef SQLITE_OMIT_TRIGGER
   72899   Trigger *pTrig;
   72900 #endif
   72901 
   72902   v = sqlite3GetVdbe(pParse);
   72903   if( NEVER(v==0) ) return;
   72904   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   72905   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   72906   assert( iDb>=0 );
   72907 
   72908 #ifndef SQLITE_OMIT_TRIGGER
   72909   /* Drop any table triggers from the internal schema. */
   72910   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
   72911     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   72912     assert( iTrigDb==iDb || iTrigDb==1 );
   72913     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
   72914   }
   72915 #endif
   72916 
   72917   /* Drop the table and index from the internal schema.  */
   72918   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   72919 
   72920   /* Reload the table, index and permanent trigger schemas. */
   72921   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
   72922   if( !zWhere ) return;
   72923   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
   72924 
   72925 #ifndef SQLITE_OMIT_TRIGGER
   72926   /* Now, if the table is not stored in the temp database, reload any temp
   72927   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
   72928   */
   72929   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   72930     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
   72931   }
   72932 #endif
   72933 }
   72934 
   72935 /*
   72936 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
   72937 ** command.
   72938 */
   72939 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   72940   Parse *pParse,            /* Parser context. */
   72941   SrcList *pSrc,            /* The table to rename. */
   72942   Token *pName              /* The new table name. */
   72943 ){
   72944   int iDb;                  /* Database that contains the table */
   72945   char *zDb;                /* Name of database iDb */
   72946   Table *pTab;              /* Table being renamed */
   72947   char *zName = 0;          /* NULL-terminated version of pName */
   72948   sqlite3 *db = pParse->db; /* Database connection */
   72949   int nTabName;             /* Number of UTF-8 characters in zTabName */
   72950   const char *zTabName;     /* Original name of the table */
   72951   Vdbe *v;
   72952 #ifndef SQLITE_OMIT_TRIGGER
   72953   char *zWhere = 0;         /* Where clause to locate temp triggers */
   72954 #endif
   72955   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   72956   int savedDbFlags;         /* Saved value of db->flags */
   72957 
   72958   savedDbFlags = db->flags;
   72959   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   72960   assert( pSrc->nSrc==1 );
   72961   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   72962 
   72963   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   72964   if( !pTab ) goto exit_rename_table;
   72965   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   72966   zDb = db->aDb[iDb].zName;
   72967   db->flags |= SQLITE_PreferBuiltin;
   72968 
   72969   /* Get a NULL terminated version of the new table name. */
   72970   zName = sqlite3NameFromToken(db, pName);
   72971   if( !zName ) goto exit_rename_table;
   72972 
   72973   /* Check that a table or index named 'zName' does not already exist
   72974   ** in database iDb. If so, this is an error.
   72975   */
   72976   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
   72977     sqlite3ErrorMsg(pParse,
   72978         "there is already another table or index with this name: %s", zName);
   72979     goto exit_rename_table;
   72980   }
   72981 
   72982   /* Make sure it is not a system table being altered, or a reserved name
   72983   ** that the table is being renamed to.
   72984   */
   72985   if( sqlite3Strlen30(pTab->zName)>6
   72986    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
   72987   ){
   72988     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
   72989     goto exit_rename_table;
   72990   }
   72991   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   72992     goto exit_rename_table;
   72993   }
   72994 
   72995 #ifndef SQLITE_OMIT_VIEW
   72996   if( pTab->pSelect ){
   72997     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
   72998     goto exit_rename_table;
   72999   }
   73000 #endif
   73001 
   73002 #ifndef SQLITE_OMIT_AUTHORIZATION
   73003   /* Invoke the authorization callback. */
   73004   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   73005     goto exit_rename_table;
   73006   }
   73007 #endif
   73008 
   73009 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73010   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   73011     goto exit_rename_table;
   73012   }
   73013   if( IsVirtual(pTab) ){
   73014     pVTab = sqlite3GetVTable(db, pTab);
   73015     if( pVTab->pVtab->pModule->xRename==0 ){
   73016       pVTab = 0;
   73017     }
   73018   }
   73019 #endif
   73020 
   73021   /* Begin a transaction and code the VerifyCookie for database iDb.
   73022   ** Then modify the schema cookie (since the ALTER TABLE modifies the
   73023   ** schema). Open a statement transaction if the table is a virtual
   73024   ** table.
   73025   */
   73026   v = sqlite3GetVdbe(pParse);
   73027   if( v==0 ){
   73028     goto exit_rename_table;
   73029   }
   73030   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
   73031   sqlite3ChangeCookie(pParse, iDb);
   73032 
   73033   /* If this is a virtual table, invoke the xRename() function if
   73034   ** one is defined. The xRename() callback will modify the names
   73035   ** of any resources used by the v-table implementation (including other
   73036   ** SQLite tables) that are identified by the name of the virtual table.
   73037   */
   73038 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73039   if( pVTab ){
   73040     int i = ++pParse->nMem;
   73041     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
   73042     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
   73043     sqlite3MayAbort(pParse);
   73044   }
   73045 #endif
   73046 
   73047   /* figure out how many UTF-8 characters are in zName */
   73048   zTabName = pTab->zName;
   73049   nTabName = sqlite3Utf8CharLen(zTabName, -1);
   73050 
   73051 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   73052   if( db->flags&SQLITE_ForeignKeys ){
   73053     /* If foreign-key support is enabled, rewrite the CREATE TABLE
   73054     ** statements corresponding to all child tables of foreign key constraints
   73055     ** for which the renamed table is the parent table.  */
   73056     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
   73057       sqlite3NestedParse(pParse,
   73058           "UPDATE \"%w\".%s SET "
   73059               "sql = sqlite_rename_parent(sql, %Q, %Q) "
   73060               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
   73061       sqlite3DbFree(db, zWhere);
   73062     }
   73063   }
   73064 #endif
   73065 
   73066   /* Modify the sqlite_master table to use the new table name. */
   73067   sqlite3NestedParse(pParse,
   73068       "UPDATE %Q.%s SET "
   73069 #ifdef SQLITE_OMIT_TRIGGER
   73070           "sql = sqlite_rename_table(sql, %Q), "
   73071 #else
   73072           "sql = CASE "
   73073             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
   73074             "ELSE sqlite_rename_table(sql, %Q) END, "
   73075 #endif
   73076           "tbl_name = %Q, "
   73077           "name = CASE "
   73078             "WHEN type='table' THEN %Q "
   73079             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
   73080              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
   73081             "ELSE name END "
   73082       "WHERE tbl_name=%Q AND "
   73083           "(type='table' OR type='index' OR type='trigger');",
   73084       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
   73085 #ifndef SQLITE_OMIT_TRIGGER
   73086       zName,
   73087 #endif
   73088       zName, nTabName, zTabName
   73089   );
   73090 
   73091 #ifndef SQLITE_OMIT_AUTOINCREMENT
   73092   /* If the sqlite_sequence table exists in this database, then update
   73093   ** it with the new table name.
   73094   */
   73095   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
   73096     sqlite3NestedParse(pParse,
   73097         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
   73098         zDb, zName, pTab->zName);
   73099   }
   73100 #endif
   73101 
   73102 #ifndef SQLITE_OMIT_TRIGGER
   73103   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
   73104   ** table. Don't do this if the table being ALTERed is itself located in
   73105   ** the temp database.
   73106   */
   73107   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
   73108     sqlite3NestedParse(pParse,
   73109         "UPDATE sqlite_temp_master SET "
   73110             "sql = sqlite_rename_trigger(sql, %Q), "
   73111             "tbl_name = %Q "
   73112             "WHERE %s;", zName, zName, zWhere);
   73113     sqlite3DbFree(db, zWhere);
   73114   }
   73115 #endif
   73116 
   73117 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   73118   if( db->flags&SQLITE_ForeignKeys ){
   73119     FKey *p;
   73120     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   73121       Table *pFrom = p->pFrom;
   73122       if( pFrom!=pTab ){
   73123         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
   73124       }
   73125     }
   73126   }
   73127 #endif
   73128 
   73129   /* Drop and reload the internal table schema. */
   73130   reloadTableSchema(pParse, pTab, zName);
   73131 
   73132 exit_rename_table:
   73133   sqlite3SrcListDelete(db, pSrc);
   73134   sqlite3DbFree(db, zName);
   73135   db->flags = savedDbFlags;
   73136 }
   73137 
   73138 
   73139 /*
   73140 ** Generate code to make sure the file format number is at least minFormat.
   73141 ** The generated code will increase the file format number if necessary.
   73142 */
   73143 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
   73144   Vdbe *v;
   73145   v = sqlite3GetVdbe(pParse);
   73146   /* The VDBE should have been allocated before this routine is called.
   73147   ** If that allocation failed, we would have quit before reaching this
   73148   ** point */
   73149   if( ALWAYS(v) ){
   73150     int r1 = sqlite3GetTempReg(pParse);
   73151     int r2 = sqlite3GetTempReg(pParse);
   73152     int j1;
   73153     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   73154     sqlite3VdbeUsesBtree(v, iDb);
   73155     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   73156     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
   73157     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   73158     sqlite3VdbeJumpHere(v, j1);
   73159     sqlite3ReleaseTempReg(pParse, r1);
   73160     sqlite3ReleaseTempReg(pParse, r2);
   73161   }
   73162 }
   73163 
   73164 /*
   73165 ** This function is called after an "ALTER TABLE ... ADD" statement
   73166 ** has been parsed. Argument pColDef contains the text of the new
   73167 ** column definition.
   73168 **
   73169 ** The Table structure pParse->pNewTable was extended to include
   73170 ** the new column during parsing.
   73171 */
   73172 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   73173   Table *pNew;              /* Copy of pParse->pNewTable */
   73174   Table *pTab;              /* Table being altered */
   73175   int iDb;                  /* Database number */
   73176   const char *zDb;          /* Database name */
   73177   const char *zTab;         /* Table name */
   73178   char *zCol;               /* Null-terminated column definition */
   73179   Column *pCol;             /* The new column */
   73180   Expr *pDflt;              /* Default value for the new column */
   73181   sqlite3 *db;              /* The database connection; */
   73182 
   73183   db = pParse->db;
   73184   if( pParse->nErr || db->mallocFailed ) return;
   73185   pNew = pParse->pNewTable;
   73186   assert( pNew );
   73187 
   73188   assert( sqlite3BtreeHoldsAllMutexes(db) );
   73189   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
   73190   zDb = db->aDb[iDb].zName;
   73191   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
   73192   pCol = &pNew->aCol[pNew->nCol-1];
   73193   pDflt = pCol->pDflt;
   73194   pTab = sqlite3FindTable(db, zTab, zDb);
   73195   assert( pTab );
   73196 
   73197 #ifndef SQLITE_OMIT_AUTHORIZATION
   73198   /* Invoke the authorization callback. */
   73199   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
   73200     return;
   73201   }
   73202 #endif
   73203 
   73204   /* If the default value for the new column was specified with a
   73205   ** literal NULL, then set pDflt to 0. This simplifies checking
   73206   ** for an SQL NULL default below.
   73207   */
   73208   if( pDflt && pDflt->op==TK_NULL ){
   73209     pDflt = 0;
   73210   }
   73211 
   73212   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   73213   ** If there is a NOT NULL constraint, then the default value for the
   73214   ** column must not be NULL.
   73215   */
   73216   if( pCol->isPrimKey ){
   73217     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
   73218     return;
   73219   }
   73220   if( pNew->pIndex ){
   73221     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
   73222     return;
   73223   }
   73224   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
   73225     sqlite3ErrorMsg(pParse,
   73226         "Cannot add a REFERENCES column with non-NULL default value");
   73227     return;
   73228   }
   73229   if( pCol->notNull && !pDflt ){
   73230     sqlite3ErrorMsg(pParse,
   73231         "Cannot add a NOT NULL column with default value NULL");
   73232     return;
   73233   }
   73234 
   73235   /* Ensure the default expression is something that sqlite3ValueFromExpr()
   73236   ** can handle (i.e. not CURRENT_TIME etc.)
   73237   */
   73238   if( pDflt ){
   73239     sqlite3_value *pVal;
   73240     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
   73241       db->mallocFailed = 1;
   73242       return;
   73243     }
   73244     if( !pVal ){
   73245       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   73246       return;
   73247     }
   73248     sqlite3ValueFree(pVal);
   73249   }
   73250 
   73251   /* Modify the CREATE TABLE statement. */
   73252   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   73253   if( zCol ){
   73254     char *zEnd = &zCol[pColDef->n-1];
   73255     int savedDbFlags = db->flags;
   73256     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
   73257       *zEnd-- = '\0';
   73258     }
   73259     db->flags |= SQLITE_PreferBuiltin;
   73260     sqlite3NestedParse(pParse,
   73261         "UPDATE \"%w\".%s SET "
   73262           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
   73263         "WHERE type = 'table' AND name = %Q",
   73264       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
   73265       zTab
   73266     );
   73267     sqlite3DbFree(db, zCol);
   73268     db->flags = savedDbFlags;
   73269   }
   73270 
   73271   /* If the default value of the new column is NULL, then set the file
   73272   ** format to 2. If the default value of the new column is not NULL,
   73273   ** the file format becomes 3.
   73274   */
   73275   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
   73276 
   73277   /* Reload the schema of the modified table. */
   73278   reloadTableSchema(pParse, pTab, pTab->zName);
   73279 }
   73280 
   73281 /*
   73282 ** This function is called by the parser after the table-name in
   73283 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
   73284 ** pSrc is the full-name of the table being altered.
   73285 **
   73286 ** This routine makes a (partial) copy of the Table structure
   73287 ** for the table being altered and sets Parse.pNewTable to point
   73288 ** to it. Routines called by the parser as the column definition
   73289 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
   73290 ** the copy. The copy of the Table structure is deleted by tokenize.c
   73291 ** after parsing is finished.
   73292 **
   73293 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
   73294 ** coding the "ALTER TABLE ... ADD" statement.
   73295 */
   73296 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   73297   Table *pNew;
   73298   Table *pTab;
   73299   Vdbe *v;
   73300   int iDb;
   73301   int i;
   73302   int nAlloc;
   73303   sqlite3 *db = pParse->db;
   73304 
   73305   /* Look up the table being altered. */
   73306   assert( pParse->pNewTable==0 );
   73307   assert( sqlite3BtreeHoldsAllMutexes(db) );
   73308   if( db->mallocFailed ) goto exit_begin_add_column;
   73309   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
   73310   if( !pTab ) goto exit_begin_add_column;
   73311 
   73312 #ifndef SQLITE_OMIT_VIRTUALTABLE
   73313   if( IsVirtual(pTab) ){
   73314     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
   73315     goto exit_begin_add_column;
   73316   }
   73317 #endif
   73318 
   73319   /* Make sure this is not an attempt to ALTER a view. */
   73320   if( pTab->pSelect ){
   73321     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
   73322     goto exit_begin_add_column;
   73323   }
   73324 
   73325   assert( pTab->addColOffset>0 );
   73326   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   73327 
   73328   /* Put a copy of the Table struct in Parse.pNewTable for the
   73329   ** sqlite3AddColumn() function and friends to modify.  But modify
   73330   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
   73331   ** prefix, we insure that the name will not collide with an existing
   73332   ** table because user table are not allowed to have the "sqlite_"
   73333   ** prefix on their name.
   73334   */
   73335   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
   73336   if( !pNew ) goto exit_begin_add_column;
   73337   pParse->pNewTable = pNew;
   73338   pNew->nRef = 1;
   73339   pNew->nCol = pTab->nCol;
   73340   assert( pNew->nCol>0 );
   73341   nAlloc = (((pNew->nCol-1)/8)*8)+8;
   73342   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
   73343   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
   73344   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
   73345   if( !pNew->aCol || !pNew->zName ){
   73346     db->mallocFailed = 1;
   73347     goto exit_begin_add_column;
   73348   }
   73349   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
   73350   for(i=0; i<pNew->nCol; i++){
   73351     Column *pCol = &pNew->aCol[i];
   73352     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
   73353     pCol->zColl = 0;
   73354     pCol->zType = 0;
   73355     pCol->pDflt = 0;
   73356     pCol->zDflt = 0;
   73357   }
   73358   pNew->pSchema = db->aDb[iDb].pSchema;
   73359   pNew->addColOffset = pTab->addColOffset;
   73360   pNew->nRef = 1;
   73361 
   73362   /* Begin a transaction and increment the schema cookie.  */
   73363   sqlite3BeginWriteOperation(pParse, 0, iDb);
   73364   v = sqlite3GetVdbe(pParse);
   73365   if( !v ) goto exit_begin_add_column;
   73366   sqlite3ChangeCookie(pParse, iDb);
   73367 
   73368 exit_begin_add_column:
   73369   sqlite3SrcListDelete(db, pSrc);
   73370   return;
   73371 }
   73372 #endif  /* SQLITE_ALTER_TABLE */
   73373 
   73374 /************** End of alter.c ***********************************************/
   73375 /************** Begin file analyze.c *****************************************/
   73376 /*
   73377 ** 2005 July 8
   73378 **
   73379 ** The author disclaims copyright to this source code.  In place of
   73380 ** a legal notice, here is a blessing:
   73381 **
   73382 **    May you do good and not evil.
   73383 **    May you find forgiveness for yourself and forgive others.
   73384 **    May you share freely, never taking more than you give.
   73385 **
   73386 *************************************************************************
   73387 ** This file contains code associated with the ANALYZE command.
   73388 */
   73389 #ifndef SQLITE_OMIT_ANALYZE
   73390 
   73391 /*
   73392 ** This routine generates code that opens the sqlite_stat1 table for
   73393 ** writing with cursor iStatCur. If the library was built with the
   73394 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
   73395 ** opened for writing using cursor (iStatCur+1)
   73396 **
   73397 ** If the sqlite_stat1 tables does not previously exist, it is created.
   73398 ** Similarly, if the sqlite_stat2 table does not exist and the library
   73399 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
   73400 **
   73401 ** Argument zWhere may be a pointer to a buffer containing a table name,
   73402 ** or it may be a NULL pointer. If it is not NULL, then all entries in
   73403 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
   73404 ** with the named table are deleted. If zWhere==0, then code is generated
   73405 ** to delete all stat table entries.
   73406 */
   73407 static void openStatTable(
   73408   Parse *pParse,          /* Parsing context */
   73409   int iDb,                /* The database we are looking in */
   73410   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
   73411   const char *zWhere      /* Delete entries associated with this table */
   73412 ){
   73413   static const struct {
   73414     const char *zName;
   73415     const char *zCols;
   73416   } aTable[] = {
   73417     { "sqlite_stat1", "tbl,idx,stat" },
   73418 #ifdef SQLITE_ENABLE_STAT2
   73419     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
   73420 #endif
   73421   };
   73422 
   73423   int aRoot[] = {0, 0};
   73424   u8 aCreateTbl[] = {0, 0};
   73425 
   73426   int i;
   73427   sqlite3 *db = pParse->db;
   73428   Db *pDb;
   73429   Vdbe *v = sqlite3GetVdbe(pParse);
   73430   if( v==0 ) return;
   73431   assert( sqlite3BtreeHoldsAllMutexes(db) );
   73432   assert( sqlite3VdbeDb(v)==db );
   73433   pDb = &db->aDb[iDb];
   73434 
   73435   for(i=0; i<ArraySize(aTable); i++){
   73436     const char *zTab = aTable[i].zName;
   73437     Table *pStat;
   73438     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
   73439       /* The sqlite_stat[12] table does not exist. Create it. Note that a
   73440       ** side-effect of the CREATE TABLE statement is to leave the rootpage
   73441       ** of the new table in register pParse->regRoot. This is important
   73442       ** because the OpenWrite opcode below will be needing it. */
   73443       sqlite3NestedParse(pParse,
   73444           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
   73445       );
   73446       aRoot[i] = pParse->regRoot;
   73447       aCreateTbl[i] = 1;
   73448     }else{
   73449       /* The table already exists. If zWhere is not NULL, delete all entries
   73450       ** associated with the table zWhere. If zWhere is NULL, delete the
   73451       ** entire contents of the table. */
   73452       aRoot[i] = pStat->tnum;
   73453       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
   73454       if( zWhere ){
   73455         sqlite3NestedParse(pParse,
   73456            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
   73457         );
   73458       }else{
   73459         /* The sqlite_stat[12] table already exists.  Delete all rows. */
   73460         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
   73461       }
   73462     }
   73463   }
   73464 
   73465   /* Open the sqlite_stat[12] tables for writing. */
   73466   for(i=0; i<ArraySize(aTable); i++){
   73467     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
   73468     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
   73469     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
   73470   }
   73471 }
   73472 
   73473 /*
   73474 ** Generate code to do an analysis of all indices associated with
   73475 ** a single table.
   73476 */
   73477 static void analyzeOneTable(
   73478   Parse *pParse,   /* Parser context */
   73479   Table *pTab,     /* Table whose indices are to be analyzed */
   73480   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
   73481   int iMem         /* Available memory locations begin here */
   73482 ){
   73483   sqlite3 *db = pParse->db;    /* Database handle */
   73484   Index *pIdx;                 /* An index to being analyzed */
   73485   int iIdxCur;                 /* Cursor open on index being analyzed */
   73486   Vdbe *v;                     /* The virtual machine being built up */
   73487   int i;                       /* Loop counter */
   73488   int topOfLoop;               /* The top of the loop */
   73489   int endOfLoop;               /* The end of the loop */
   73490   int addr = 0;                /* The address of an instruction */
   73491   int jZeroRows = 0;           /* Jump from here if number of rows is zero */
   73492   int iDb;                     /* Index of database containing pTab */
   73493   int regTabname = iMem++;     /* Register containing table name */
   73494   int regIdxname = iMem++;     /* Register containing index name */
   73495   int regSampleno = iMem++;    /* Register containing next sample number */
   73496   int regCol = iMem++;         /* Content of a column analyzed table */
   73497   int regRec = iMem++;         /* Register holding completed record */
   73498   int regTemp = iMem++;        /* Temporary use register */
   73499   int regRowid = iMem++;       /* Rowid for the inserted record */
   73500 
   73501 #ifdef SQLITE_ENABLE_STAT2
   73502   int regTemp2 = iMem++;       /* Temporary use register */
   73503   int regSamplerecno = iMem++; /* Index of next sample to record */
   73504   int regRecno = iMem++;       /* Current sample index */
   73505   int regLast = iMem++;        /* Index of last sample to record */
   73506   int regFirst = iMem++;       /* Index of first sample to record */
   73507 #endif
   73508 
   73509   v = sqlite3GetVdbe(pParse);
   73510   if( v==0 || NEVER(pTab==0) ){
   73511     return;
   73512   }
   73513   if( pTab->tnum==0 ){
   73514     /* Do not gather statistics on views or virtual tables */
   73515     return;
   73516   }
   73517   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
   73518     /* Do not gather statistics on system tables */
   73519     return;
   73520   }
   73521   assert( sqlite3BtreeHoldsAllMutexes(db) );
   73522   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   73523   assert( iDb>=0 );
   73524 #ifndef SQLITE_OMIT_AUTHORIZATION
   73525   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
   73526       db->aDb[iDb].zName ) ){
   73527     return;
   73528   }
   73529 #endif
   73530 
   73531   /* Establish a read-lock on the table at the shared-cache level. */
   73532   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   73533 
   73534   iIdxCur = pParse->nTab++;
   73535   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
   73536   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   73537     int nCol = pIdx->nColumn;
   73538     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   73539 
   73540     if( iMem+1+(nCol*2)>pParse->nMem ){
   73541       pParse->nMem = iMem+1+(nCol*2);
   73542     }
   73543 
   73544     /* Open a cursor to the index to be analyzed. */
   73545     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
   73546     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
   73547         (char *)pKey, P4_KEYINFO_HANDOFF);
   73548     VdbeComment((v, "%s", pIdx->zName));
   73549 
   73550     /* Populate the register containing the index name. */
   73551     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
   73552 
   73553 #ifdef SQLITE_ENABLE_STAT2
   73554 
   73555     /* If this iteration of the loop is generating code to analyze the
   73556     ** first index in the pTab->pIndex list, then register regLast has
   73557     ** not been populated. In this case populate it now.  */
   73558     if( pTab->pIndex==pIdx ){
   73559       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
   73560       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
   73561       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
   73562 
   73563       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
   73564       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
   73565       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
   73566       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
   73567       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
   73568       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
   73569       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
   73570       sqlite3VdbeJumpHere(v, addr);
   73571     }
   73572 
   73573     /* Zero the regSampleno and regRecno registers. */
   73574     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
   73575     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
   73576     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
   73577 #endif
   73578 
   73579     /* The block of memory cells initialized here is used as follows.
   73580     **
   73581     **    iMem:
   73582     **        The total number of rows in the table.
   73583     **
   73584     **    iMem+1 .. iMem+nCol:
   73585     **        Number of distinct entries in index considering the
   73586     **        left-most N columns only, where N is between 1 and nCol,
   73587     **        inclusive.
   73588     **
   73589     **    iMem+nCol+1 .. Mem+2*nCol:
   73590     **        Previous value of indexed columns, from left to right.
   73591     **
   73592     ** Cells iMem through iMem+nCol are initialized to 0. The others are
   73593     ** initialized to contain an SQL NULL.
   73594     */
   73595     for(i=0; i<=nCol; i++){
   73596       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
   73597     }
   73598     for(i=0; i<nCol; i++){
   73599       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
   73600     }
   73601 
   73602     /* Start the analysis loop. This loop runs through all the entries in
   73603     ** the index b-tree.  */
   73604     endOfLoop = sqlite3VdbeMakeLabel(v);
   73605     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
   73606     topOfLoop = sqlite3VdbeCurrentAddr(v);
   73607     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
   73608 
   73609     for(i=0; i<nCol; i++){
   73610       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
   73611 #ifdef SQLITE_ENABLE_STAT2
   73612       if( i==0 ){
   73613         /* Check if the record that cursor iIdxCur points to contains a
   73614         ** value that should be stored in the sqlite_stat2 table. If so,
   73615         ** store it.  */
   73616         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
   73617         assert( regTabname+1==regIdxname
   73618              && regTabname+2==regSampleno
   73619              && regTabname+3==regCol
   73620         );
   73621         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   73622         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
   73623         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
   73624         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
   73625 
   73626         /* Calculate new values for regSamplerecno and regSampleno.
   73627         **
   73628         **   sampleno = sampleno + 1
   73629         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
   73630         */
   73631         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
   73632         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
   73633         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   73634         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
   73635         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
   73636         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
   73637         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
   73638 
   73639         sqlite3VdbeJumpHere(v, ne);
   73640         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
   73641       }
   73642 #endif
   73643 
   73644       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
   73645       /**** TODO:  add collating sequence *****/
   73646       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   73647     }
   73648     if( db->mallocFailed ){
   73649       /* If a malloc failure has occurred, then the result of the expression
   73650       ** passed as the second argument to the call to sqlite3VdbeJumpHere()
   73651       ** below may be negative. Which causes an assert() to fail (or an
   73652       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
   73653       return;
   73654     }
   73655     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
   73656     for(i=0; i<nCol; i++){
   73657       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
   73658       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
   73659       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
   73660     }
   73661 
   73662     /* End of the analysis loop. */
   73663     sqlite3VdbeResolveLabel(v, endOfLoop);
   73664     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
   73665     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   73666 
   73667     /* Store the results in sqlite_stat1.
   73668     **
   73669     ** The result is a single row of the sqlite_stat1 table.  The first
   73670     ** two columns are the names of the table and index.  The third column
   73671     ** is a string composed of a list of integer statistics about the
   73672     ** index.  The first integer in the list is the total number of entries
   73673     ** in the index.  There is one additional integer in the list for each
   73674     ** column of the table.  This additional integer is a guess of how many
   73675     ** rows of the table the index will select.  If D is the count of distinct
   73676     ** values and K is the total number of rows, then the integer is computed
   73677     ** as:
   73678     **
   73679     **        I = (K+D-1)/D
   73680     **
   73681     ** If K==0 then no entry is made into the sqlite_stat1 table.
   73682     ** If K>0 then it is always the case the D>0 so division by zero
   73683     ** is never possible.
   73684     */
   73685     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
   73686     if( jZeroRows==0 ){
   73687       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   73688     }
   73689     for(i=0; i<nCol; i++){
   73690       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
   73691       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
   73692       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
   73693       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   73694       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
   73695       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
   73696       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
   73697     }
   73698     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   73699     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
   73700     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
   73701     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   73702   }
   73703 
   73704   /* If the table has no indices, create a single sqlite_stat1 entry
   73705   ** containing NULL as the index name and the row count as the content.
   73706   */
   73707   if( pTab->pIndex==0 ){
   73708     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
   73709     VdbeComment((v, "%s", pTab->zName));
   73710     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
   73711     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   73712   }else{
   73713     assert( jZeroRows>0 );
   73714     addr = sqlite3VdbeAddOp0(v, OP_Goto);
   73715     sqlite3VdbeJumpHere(v, jZeroRows);
   73716   }
   73717   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   73718   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   73719   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
   73720   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
   73721   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   73722   if( pParse->nMem<regRec ) pParse->nMem = regRec;
   73723   if( jZeroRows ){
   73724     sqlite3VdbeJumpHere(v, addr);
   73725   }
   73726 }
   73727 
   73728 /*
   73729 ** Generate code that will cause the most recent index analysis to
   73730 ** be loaded into internal hash tables where is can be used.
   73731 */
   73732 static void loadAnalysis(Parse *pParse, int iDb){
   73733   Vdbe *v = sqlite3GetVdbe(pParse);
   73734   if( v ){
   73735     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
   73736   }
   73737 }
   73738 
   73739 /*
   73740 ** Generate code that will do an analysis of an entire database
   73741 */
   73742 static void analyzeDatabase(Parse *pParse, int iDb){
   73743   sqlite3 *db = pParse->db;
   73744   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
   73745   HashElem *k;
   73746   int iStatCur;
   73747   int iMem;
   73748 
   73749   sqlite3BeginWriteOperation(pParse, 0, iDb);
   73750   iStatCur = pParse->nTab;
   73751   pParse->nTab += 2;
   73752   openStatTable(pParse, iDb, iStatCur, 0);
   73753   iMem = pParse->nMem+1;
   73754   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
   73755     Table *pTab = (Table*)sqliteHashData(k);
   73756     analyzeOneTable(pParse, pTab, iStatCur, iMem);
   73757   }
   73758   loadAnalysis(pParse, iDb);
   73759 }
   73760 
   73761 /*
   73762 ** Generate code that will do an analysis of a single table in
   73763 ** a database.
   73764 */
   73765 static void analyzeTable(Parse *pParse, Table *pTab){
   73766   int iDb;
   73767   int iStatCur;
   73768 
   73769   assert( pTab!=0 );
   73770   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   73771   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   73772   sqlite3BeginWriteOperation(pParse, 0, iDb);
   73773   iStatCur = pParse->nTab;
   73774   pParse->nTab += 2;
   73775   openStatTable(pParse, iDb, iStatCur, pTab->zName);
   73776   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
   73777   loadAnalysis(pParse, iDb);
   73778 }
   73779 
   73780 /*
   73781 ** Generate code for the ANALYZE command.  The parser calls this routine
   73782 ** when it recognizes an ANALYZE command.
   73783 **
   73784 **        ANALYZE                            -- 1
   73785 **        ANALYZE  <database>                -- 2
   73786 **        ANALYZE  ?<database>.?<tablename>  -- 3
   73787 **
   73788 ** Form 1 causes all indices in all attached databases to be analyzed.
   73789 ** Form 2 analyzes all indices the single database named.
   73790 ** Form 3 analyzes all indices associated with the named table.
   73791 */
   73792 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
   73793   sqlite3 *db = pParse->db;
   73794   int iDb;
   73795   int i;
   73796   char *z, *zDb;
   73797   Table *pTab;
   73798   Token *pTableName;
   73799 
   73800   /* Read the database schema. If an error occurs, leave an error message
   73801   ** and code in pParse and return NULL. */
   73802   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
   73803   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   73804     return;
   73805   }
   73806 
   73807   assert( pName2!=0 || pName1==0 );
   73808   if( pName1==0 ){
   73809     /* Form 1:  Analyze everything */
   73810     for(i=0; i<db->nDb; i++){
   73811       if( i==1 ) continue;  /* Do not analyze the TEMP database */
   73812       analyzeDatabase(pParse, i);
   73813     }
   73814   }else if( pName2->n==0 ){
   73815     /* Form 2:  Analyze the database or table named */
   73816     iDb = sqlite3FindDb(db, pName1);
   73817     if( iDb>=0 ){
   73818       analyzeDatabase(pParse, iDb);
   73819     }else{
   73820       z = sqlite3NameFromToken(db, pName1);
   73821       if( z ){
   73822         pTab = sqlite3LocateTable(pParse, 0, z, 0);
   73823         sqlite3DbFree(db, z);
   73824         if( pTab ){
   73825           analyzeTable(pParse, pTab);
   73826         }
   73827       }
   73828     }
   73829   }else{
   73830     /* Form 3: Analyze the fully qualified table name */
   73831     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
   73832     if( iDb>=0 ){
   73833       zDb = db->aDb[iDb].zName;
   73834       z = sqlite3NameFromToken(db, pTableName);
   73835       if( z ){
   73836         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
   73837         sqlite3DbFree(db, z);
   73838         if( pTab ){
   73839           analyzeTable(pParse, pTab);
   73840         }
   73841       }
   73842     }
   73843   }
   73844 }
   73845 
   73846 /*
   73847 ** Used to pass information from the analyzer reader through to the
   73848 ** callback routine.
   73849 */
   73850 typedef struct analysisInfo analysisInfo;
   73851 struct analysisInfo {
   73852   sqlite3 *db;
   73853   const char *zDatabase;
   73854 };
   73855 
   73856 /*
   73857 ** This callback is invoked once for each index when reading the
   73858 ** sqlite_stat1 table.
   73859 **
   73860 **     argv[0] = name of the table
   73861 **     argv[1] = name of the index (might be NULL)
   73862 **     argv[2] = results of analysis - on integer for each column
   73863 **
   73864 ** Entries for which argv[1]==NULL simply record the number of rows in
   73865 ** the table.
   73866 */
   73867 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
   73868   analysisInfo *pInfo = (analysisInfo*)pData;
   73869   Index *pIndex;
   73870   Table *pTable;
   73871   int i, c, n;
   73872   unsigned int v;
   73873   const char *z;
   73874 
   73875   assert( argc==3 );
   73876   UNUSED_PARAMETER2(NotUsed, argc);
   73877 
   73878   if( argv==0 || argv[0]==0 || argv[2]==0 ){
   73879     return 0;
   73880   }
   73881   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
   73882   if( pTable==0 ){
   73883     return 0;
   73884   }
   73885   if( argv[1] ){
   73886     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
   73887   }else{
   73888     pIndex = 0;
   73889   }
   73890   n = pIndex ? pIndex->nColumn : 0;
   73891   z = argv[2];
   73892   for(i=0; *z && i<=n; i++){
   73893     v = 0;
   73894     while( (c=z[0])>='0' && c<='9' ){
   73895       v = v*10 + c - '0';
   73896       z++;
   73897     }
   73898     if( i==0 ) pTable->nRowEst = v;
   73899     if( pIndex==0 ) break;
   73900     pIndex->aiRowEst[i] = v;
   73901     if( *z==' ' ) z++;
   73902   }
   73903   return 0;
   73904 }
   73905 
   73906 /*
   73907 ** If the Index.aSample variable is not NULL, delete the aSample[] array
   73908 ** and its contents.
   73909 */
   73910 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
   73911 #ifdef SQLITE_ENABLE_STAT2
   73912   if( pIdx->aSample ){
   73913     int j;
   73914     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
   73915       IndexSample *p = &pIdx->aSample[j];
   73916       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
   73917         sqlite3DbFree(db, p->u.z);
   73918       }
   73919     }
   73920     sqlite3DbFree(db, pIdx->aSample);
   73921   }
   73922 #else
   73923   UNUSED_PARAMETER(db);
   73924   UNUSED_PARAMETER(pIdx);
   73925 #endif
   73926 }
   73927 
   73928 /*
   73929 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
   73930 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
   73931 ** arrays. The contents of sqlite_stat2 are used to populate the
   73932 ** Index.aSample[] arrays.
   73933 **
   73934 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
   73935 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
   73936 ** during compilation and the sqlite_stat2 table is present, no data is
   73937 ** read from it.
   73938 **
   73939 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
   73940 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
   73941 ** returned. However, in this case, data is read from the sqlite_stat1
   73942 ** table (if it is present) before returning.
   73943 **
   73944 ** If an OOM error occurs, this function always sets db->mallocFailed.
   73945 ** This means if the caller does not care about other errors, the return
   73946 ** code may be ignored.
   73947 */
   73948 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   73949   analysisInfo sInfo;
   73950   HashElem *i;
   73951   char *zSql;
   73952   int rc;
   73953 
   73954   assert( iDb>=0 && iDb<db->nDb );
   73955   assert( db->aDb[iDb].pBt!=0 );
   73956   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   73957 
   73958   /* Clear any prior statistics */
   73959   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
   73960     Index *pIdx = sqliteHashData(i);
   73961     sqlite3DefaultRowEst(pIdx);
   73962     sqlite3DeleteIndexSamples(db, pIdx);
   73963     pIdx->aSample = 0;
   73964   }
   73965 
   73966   /* Check to make sure the sqlite_stat1 table exists */
   73967   sInfo.db = db;
   73968   sInfo.zDatabase = db->aDb[iDb].zName;
   73969   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
   73970     return SQLITE_ERROR;
   73971   }
   73972 
   73973   /* Load new statistics out of the sqlite_stat1 table */
   73974   zSql = sqlite3MPrintf(db,
   73975       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
   73976   if( zSql==0 ){
   73977     rc = SQLITE_NOMEM;
   73978   }else{
   73979     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
   73980     sqlite3DbFree(db, zSql);
   73981   }
   73982 
   73983 
   73984   /* Load the statistics from the sqlite_stat2 table. */
   73985 #ifdef SQLITE_ENABLE_STAT2
   73986   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
   73987     rc = SQLITE_ERROR;
   73988   }
   73989   if( rc==SQLITE_OK ){
   73990     sqlite3_stmt *pStmt = 0;
   73991 
   73992     zSql = sqlite3MPrintf(db,
   73993         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
   73994     if( !zSql ){
   73995       rc = SQLITE_NOMEM;
   73996     }else{
   73997       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   73998       sqlite3DbFree(db, zSql);
   73999     }
   74000 
   74001     if( rc==SQLITE_OK ){
   74002       while( sqlite3_step(pStmt)==SQLITE_ROW ){
   74003         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
   74004         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
   74005         if( pIdx ){
   74006           int iSample = sqlite3_column_int(pStmt, 1);
   74007           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
   74008             int eType = sqlite3_column_type(pStmt, 2);
   74009 
   74010             if( pIdx->aSample==0 ){
   74011               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
   74012               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
   74013               if( pIdx->aSample==0 ){
   74014                 db->mallocFailed = 1;
   74015                 break;
   74016               }
   74017 	      memset(pIdx->aSample, 0, sz);
   74018             }
   74019 
   74020             assert( pIdx->aSample );
   74021             {
   74022               IndexSample *pSample = &pIdx->aSample[iSample];
   74023               pSample->eType = (u8)eType;
   74024               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   74025                 pSample->u.r = sqlite3_column_double(pStmt, 2);
   74026               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
   74027                 const char *z = (const char *)(
   74028                     (eType==SQLITE_BLOB) ?
   74029                     sqlite3_column_blob(pStmt, 2):
   74030                     sqlite3_column_text(pStmt, 2)
   74031                 );
   74032                 int n = sqlite3_column_bytes(pStmt, 2);
   74033                 if( n>24 ){
   74034                   n = 24;
   74035                 }
   74036                 pSample->nByte = (u8)n;
   74037                 if( n < 1){
   74038                   pSample->u.z = 0;
   74039                 }else{
   74040                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
   74041                   if( pSample->u.z==0 ){
   74042                     db->mallocFailed = 1;
   74043                     break;
   74044                   }
   74045                 }
   74046               }
   74047             }
   74048           }
   74049         }
   74050       }
   74051       rc = sqlite3_finalize(pStmt);
   74052     }
   74053   }
   74054 #endif
   74055 
   74056   if( rc==SQLITE_NOMEM ){
   74057     db->mallocFailed = 1;
   74058   }
   74059   return rc;
   74060 }
   74061 
   74062 
   74063 #endif /* SQLITE_OMIT_ANALYZE */
   74064 
   74065 /************** End of analyze.c *********************************************/
   74066 /************** Begin file attach.c ******************************************/
   74067 /*
   74068 ** 2003 April 6
   74069 **
   74070 ** The author disclaims copyright to this source code.  In place of
   74071 ** a legal notice, here is a blessing:
   74072 **
   74073 **    May you do good and not evil.
   74074 **    May you find forgiveness for yourself and forgive others.
   74075 **    May you share freely, never taking more than you give.
   74076 **
   74077 *************************************************************************
   74078 ** This file contains code used to implement the ATTACH and DETACH commands.
   74079 */
   74080 
   74081 #ifndef SQLITE_OMIT_ATTACH
   74082 /*
   74083 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
   74084 ** is slightly different from resolving a normal SQL expression, because simple
   74085 ** identifiers are treated as strings, not possible column names or aliases.
   74086 **
   74087 ** i.e. if the parser sees:
   74088 **
   74089 **     ATTACH DATABASE abc AS def
   74090 **
   74091 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
   74092 ** looking for columns of the same name.
   74093 **
   74094 ** This only applies to the root node of pExpr, so the statement:
   74095 **
   74096 **     ATTACH DATABASE abc||def AS 'db2'
   74097 **
   74098 ** will fail because neither abc or def can be resolved.
   74099 */
   74100 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
   74101 {
   74102   int rc = SQLITE_OK;
   74103   if( pExpr ){
   74104     if( pExpr->op!=TK_ID ){
   74105       rc = sqlite3ResolveExprNames(pName, pExpr);
   74106       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
   74107         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
   74108         return SQLITE_ERROR;
   74109       }
   74110     }else{
   74111       pExpr->op = TK_STRING;
   74112     }
   74113   }
   74114   return rc;
   74115 }
   74116 
   74117 /*
   74118 ** An SQL user-function registered to do the work of an ATTACH statement. The
   74119 ** three arguments to the function come directly from an attach statement:
   74120 **
   74121 **     ATTACH DATABASE x AS y KEY z
   74122 **
   74123 **     SELECT sqlite_attach(x, y, z)
   74124 **
   74125 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
   74126 ** third argument.
   74127 */
   74128 static void attachFunc(
   74129   sqlite3_context *context,
   74130   int NotUsed,
   74131   sqlite3_value **argv
   74132 ){
   74133   int i;
   74134   int rc = 0;
   74135   sqlite3 *db = sqlite3_context_db_handle(context);
   74136   const char *zName;
   74137   const char *zFile;
   74138   Db *aNew;
   74139   char *zErrDyn = 0;
   74140 
   74141   UNUSED_PARAMETER(NotUsed);
   74142 
   74143   zFile = (const char *)sqlite3_value_text(argv[0]);
   74144   zName = (const char *)sqlite3_value_text(argv[1]);
   74145   if( zFile==0 ) zFile = "";
   74146   if( zName==0 ) zName = "";
   74147 
   74148   /* Check for the following errors:
   74149   **
   74150   **     * Too many attached databases,
   74151   **     * Transaction currently open
   74152   **     * Specified database name already being used.
   74153   */
   74154   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
   74155     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
   74156       db->aLimit[SQLITE_LIMIT_ATTACHED]
   74157     );
   74158     goto attach_error;
   74159   }
   74160   if( !db->autoCommit ){
   74161     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
   74162     goto attach_error;
   74163   }
   74164   for(i=0; i<db->nDb; i++){
   74165     char *z = db->aDb[i].zName;
   74166     assert( z && zName );
   74167     if( sqlite3StrICmp(z, zName)==0 ){
   74168       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
   74169       goto attach_error;
   74170     }
   74171   }
   74172 
   74173   /* Allocate the new entry in the db->aDb[] array and initialise the schema
   74174   ** hash tables.
   74175   */
   74176   if( db->aDb==db->aDbStatic ){
   74177     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
   74178     if( aNew==0 ) return;
   74179     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   74180   }else{
   74181     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   74182     if( aNew==0 ) return;
   74183   }
   74184   db->aDb = aNew;
   74185   aNew = &db->aDb[db->nDb];
   74186   memset(aNew, 0, sizeof(*aNew));
   74187 
   74188   /* Open the database file. If the btree is successfully opened, use
   74189   ** it to obtain the database schema. At this point the schema may
   74190   ** or may not be initialised.
   74191   */
   74192   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
   74193                         db->openFlags | SQLITE_OPEN_MAIN_DB);
   74194   db->nDb++;
   74195   if( rc==SQLITE_CONSTRAINT ){
   74196     rc = SQLITE_ERROR;
   74197     zErrDyn = sqlite3MPrintf(db, "database is already attached");
   74198   }else if( rc==SQLITE_OK ){
   74199     Pager *pPager;
   74200     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
   74201     if( !aNew->pSchema ){
   74202       rc = SQLITE_NOMEM;
   74203     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
   74204       zErrDyn = sqlite3MPrintf(db,
   74205         "attached databases must use the same text encoding as main database");
   74206       rc = SQLITE_ERROR;
   74207     }
   74208     pPager = sqlite3BtreePager(aNew->pBt);
   74209     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
   74210     sqlite3BtreeSecureDelete(aNew->pBt,
   74211                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
   74212   }
   74213   aNew->safety_level = 3;
   74214   aNew->zName = sqlite3DbStrDup(db, zName);
   74215   if( rc==SQLITE_OK && aNew->zName==0 ){
   74216     rc = SQLITE_NOMEM;
   74217   }
   74218 
   74219 
   74220 #ifdef SQLITE_HAS_CODEC
   74221   if( rc==SQLITE_OK ){
   74222     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
   74223     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   74224     int nKey;
   74225     char *zKey;
   74226     int t = sqlite3_value_type(argv[2]);
   74227     switch( t ){
   74228       case SQLITE_INTEGER:
   74229       case SQLITE_FLOAT:
   74230         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
   74231         rc = SQLITE_ERROR;
   74232         break;
   74233 
   74234       case SQLITE_TEXT:
   74235       case SQLITE_BLOB:
   74236         nKey = sqlite3_value_bytes(argv[2]);
   74237         zKey = (char *)sqlite3_value_blob(argv[2]);
   74238         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   74239         break;
   74240 
   74241       case SQLITE_NULL:
   74242         /* No key specified.  Use the key from the main database */
   74243         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   74244         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
   74245         break;
   74246     }
   74247   }
   74248 #endif
   74249 
   74250   /* If the file was opened successfully, read the schema for the new database.
   74251   ** If this fails, or if opening the file failed, then close the file and
   74252   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
   74253   ** we found it.
   74254   */
   74255   if( rc==SQLITE_OK ){
   74256     sqlite3BtreeEnterAll(db);
   74257     rc = sqlite3Init(db, &zErrDyn);
   74258     sqlite3BtreeLeaveAll(db);
   74259   }
   74260   if( rc ){
   74261     int iDb = db->nDb - 1;
   74262     assert( iDb>=2 );
   74263     if( db->aDb[iDb].pBt ){
   74264       sqlite3BtreeClose(db->aDb[iDb].pBt);
   74265       db->aDb[iDb].pBt = 0;
   74266       db->aDb[iDb].pSchema = 0;
   74267     }
   74268     sqlite3ResetInternalSchema(db, 0);
   74269     db->nDb = iDb;
   74270     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   74271       db->mallocFailed = 1;
   74272       sqlite3DbFree(db, zErrDyn);
   74273       zErrDyn = sqlite3MPrintf(db, "out of memory");
   74274     }else if( zErrDyn==0 ){
   74275       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   74276     }
   74277     goto attach_error;
   74278   }
   74279 
   74280   return;
   74281 
   74282 attach_error:
   74283   /* Return an error if we get here */
   74284   if( zErrDyn ){
   74285     sqlite3_result_error(context, zErrDyn, -1);
   74286     sqlite3DbFree(db, zErrDyn);
   74287   }
   74288   if( rc ) sqlite3_result_error_code(context, rc);
   74289 }
   74290 
   74291 /*
   74292 ** An SQL user-function registered to do the work of an DETACH statement. The
   74293 ** three arguments to the function come directly from a detach statement:
   74294 **
   74295 **     DETACH DATABASE x
   74296 **
   74297 **     SELECT sqlite_detach(x)
   74298 */
   74299 static void detachFunc(
   74300   sqlite3_context *context,
   74301   int NotUsed,
   74302   sqlite3_value **argv
   74303 ){
   74304   const char *zName = (const char *)sqlite3_value_text(argv[0]);
   74305   sqlite3 *db = sqlite3_context_db_handle(context);
   74306   int i;
   74307   Db *pDb = 0;
   74308   char zErr[128];
   74309 
   74310   UNUSED_PARAMETER(NotUsed);
   74311 
   74312   if( zName==0 ) zName = "";
   74313   for(i=0; i<db->nDb; i++){
   74314     pDb = &db->aDb[i];
   74315     if( pDb->pBt==0 ) continue;
   74316     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
   74317   }
   74318 
   74319   if( i>=db->nDb ){
   74320     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
   74321     goto detach_error;
   74322   }
   74323   if( i<2 ){
   74324     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
   74325     goto detach_error;
   74326   }
   74327   if( !db->autoCommit ){
   74328     sqlite3_snprintf(sizeof(zErr), zErr,
   74329                      "cannot DETACH database within transaction");
   74330     goto detach_error;
   74331   }
   74332   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
   74333     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
   74334     goto detach_error;
   74335   }
   74336 
   74337   sqlite3BtreeClose(pDb->pBt);
   74338   pDb->pBt = 0;
   74339   pDb->pSchema = 0;
   74340   sqlite3ResetInternalSchema(db, 0);
   74341   return;
   74342 
   74343 detach_error:
   74344   sqlite3_result_error(context, zErr, -1);
   74345 }
   74346 
   74347 /*
   74348 ** This procedure generates VDBE code for a single invocation of either the
   74349 ** sqlite_detach() or sqlite_attach() SQL user functions.
   74350 */
   74351 static void codeAttach(
   74352   Parse *pParse,       /* The parser context */
   74353   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
   74354   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
   74355   Expr *pAuthArg,      /* Expression to pass to authorization callback */
   74356   Expr *pFilename,     /* Name of database file */
   74357   Expr *pDbname,       /* Name of the database to use internally */
   74358   Expr *pKey           /* Database key for encryption extension */
   74359 ){
   74360   int rc;
   74361   NameContext sName;
   74362   Vdbe *v;
   74363   sqlite3* db = pParse->db;
   74364   int regArgs;
   74365 
   74366   memset(&sName, 0, sizeof(NameContext));
   74367   sName.pParse = pParse;
   74368 
   74369   if(
   74370       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
   74371       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
   74372       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
   74373   ){
   74374     pParse->nErr++;
   74375     goto attach_end;
   74376   }
   74377 
   74378 #ifndef SQLITE_OMIT_AUTHORIZATION
   74379   if( pAuthArg ){
   74380     char *zAuthArg = pAuthArg->u.zToken;
   74381     if( NEVER(zAuthArg==0) ){
   74382       goto attach_end;
   74383     }
   74384     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
   74385     if(rc!=SQLITE_OK ){
   74386       goto attach_end;
   74387     }
   74388   }
   74389 #endif /* SQLITE_OMIT_AUTHORIZATION */
   74390 
   74391 
   74392   v = sqlite3GetVdbe(pParse);
   74393   regArgs = sqlite3GetTempRange(pParse, 4);
   74394   sqlite3ExprCode(pParse, pFilename, regArgs);
   74395   sqlite3ExprCode(pParse, pDbname, regArgs+1);
   74396   sqlite3ExprCode(pParse, pKey, regArgs+2);
   74397 
   74398   assert( v || db->mallocFailed );
   74399   if( v ){
   74400     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
   74401     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
   74402     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
   74403     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
   74404 
   74405     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
   74406     ** statement only). For DETACH, set it to false (expire all existing
   74407     ** statements).
   74408     */
   74409     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   74410   }
   74411 
   74412 attach_end:
   74413   sqlite3ExprDelete(db, pFilename);
   74414   sqlite3ExprDelete(db, pDbname);
   74415   sqlite3ExprDelete(db, pKey);
   74416 }
   74417 
   74418 /*
   74419 ** Called by the parser to compile a DETACH statement.
   74420 **
   74421 **     DETACH pDbname
   74422 */
   74423 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
   74424   static const FuncDef detach_func = {
   74425     1,                /* nArg */
   74426     SQLITE_UTF8,      /* iPrefEnc */
   74427     0,                /* flags */
   74428     0,                /* pUserData */
   74429     0,                /* pNext */
   74430     detachFunc,       /* xFunc */
   74431     0,                /* xStep */
   74432     0,                /* xFinalize */
   74433     "sqlite_detach",  /* zName */
   74434     0,                /* pHash */
   74435     0                 /* pDestructor */
   74436   };
   74437   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
   74438 }
   74439 
   74440 /*
   74441 ** Called by the parser to compile an ATTACH statement.
   74442 **
   74443 **     ATTACH p AS pDbname KEY pKey
   74444 */
   74445 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
   74446   static const FuncDef attach_func = {
   74447     3,                /* nArg */
   74448     SQLITE_UTF8,      /* iPrefEnc */
   74449     0,                /* flags */
   74450     0,                /* pUserData */
   74451     0,                /* pNext */
   74452     attachFunc,       /* xFunc */
   74453     0,                /* xStep */
   74454     0,                /* xFinalize */
   74455     "sqlite_attach",  /* zName */
   74456     0,                /* pHash */
   74457     0                 /* pDestructor */
   74458   };
   74459   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
   74460 }
   74461 #endif /* SQLITE_OMIT_ATTACH */
   74462 
   74463 /*
   74464 ** Initialize a DbFixer structure.  This routine must be called prior
   74465 ** to passing the structure to one of the sqliteFixAAAA() routines below.
   74466 **
   74467 ** The return value indicates whether or not fixation is required.  TRUE
   74468 ** means we do need to fix the database references, FALSE means we do not.
   74469 */
   74470 SQLITE_PRIVATE int sqlite3FixInit(
   74471   DbFixer *pFix,      /* The fixer to be initialized */
   74472   Parse *pParse,      /* Error messages will be written here */
   74473   int iDb,            /* This is the database that must be used */
   74474   const char *zType,  /* "view", "trigger", or "index" */
   74475   const Token *pName  /* Name of the view, trigger, or index */
   74476 ){
   74477   sqlite3 *db;
   74478 
   74479   if( NEVER(iDb<0) || iDb==1 ) return 0;
   74480   db = pParse->db;
   74481   assert( db->nDb>iDb );
   74482   pFix->pParse = pParse;
   74483   pFix->zDb = db->aDb[iDb].zName;
   74484   pFix->zType = zType;
   74485   pFix->pName = pName;
   74486   return 1;
   74487 }
   74488 
   74489 /*
   74490 ** The following set of routines walk through the parse tree and assign
   74491 ** a specific database to all table references where the database name
   74492 ** was left unspecified in the original SQL statement.  The pFix structure
   74493 ** must have been initialized by a prior call to sqlite3FixInit().
   74494 **
   74495 ** These routines are used to make sure that an index, trigger, or
   74496 ** view in one database does not refer to objects in a different database.
   74497 ** (Exception: indices, triggers, and views in the TEMP database are
   74498 ** allowed to refer to anything.)  If a reference is explicitly made
   74499 ** to an object in a different database, an error message is added to
   74500 ** pParse->zErrMsg and these routines return non-zero.  If everything
   74501 ** checks out, these routines return 0.
   74502 */
   74503 SQLITE_PRIVATE int sqlite3FixSrcList(
   74504   DbFixer *pFix,       /* Context of the fixation */
   74505   SrcList *pList       /* The Source list to check and modify */
   74506 ){
   74507   int i;
   74508   const char *zDb;
   74509   struct SrcList_item *pItem;
   74510 
   74511   if( NEVER(pList==0) ) return 0;
   74512   zDb = pFix->zDb;
   74513   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   74514     if( pItem->zDatabase==0 ){
   74515       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
   74516     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
   74517       sqlite3ErrorMsg(pFix->pParse,
   74518          "%s %T cannot reference objects in database %s",
   74519          pFix->zType, pFix->pName, pItem->zDatabase);
   74520       return 1;
   74521     }
   74522 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   74523     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
   74524     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
   74525 #endif
   74526   }
   74527   return 0;
   74528 }
   74529 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
   74530 SQLITE_PRIVATE int sqlite3FixSelect(
   74531   DbFixer *pFix,       /* Context of the fixation */
   74532   Select *pSelect      /* The SELECT statement to be fixed to one database */
   74533 ){
   74534   while( pSelect ){
   74535     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
   74536       return 1;
   74537     }
   74538     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
   74539       return 1;
   74540     }
   74541     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
   74542       return 1;
   74543     }
   74544     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
   74545       return 1;
   74546     }
   74547     pSelect = pSelect->pPrior;
   74548   }
   74549   return 0;
   74550 }
   74551 SQLITE_PRIVATE int sqlite3FixExpr(
   74552   DbFixer *pFix,     /* Context of the fixation */
   74553   Expr *pExpr        /* The expression to be fixed to one database */
   74554 ){
   74555   while( pExpr ){
   74556     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
   74557     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   74558       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
   74559     }else{
   74560       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
   74561     }
   74562     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
   74563       return 1;
   74564     }
   74565     pExpr = pExpr->pLeft;
   74566   }
   74567   return 0;
   74568 }
   74569 SQLITE_PRIVATE int sqlite3FixExprList(
   74570   DbFixer *pFix,     /* Context of the fixation */
   74571   ExprList *pList    /* The expression to be fixed to one database */
   74572 ){
   74573   int i;
   74574   struct ExprList_item *pItem;
   74575   if( pList==0 ) return 0;
   74576   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
   74577     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
   74578       return 1;
   74579     }
   74580   }
   74581   return 0;
   74582 }
   74583 #endif
   74584 
   74585 #ifndef SQLITE_OMIT_TRIGGER
   74586 SQLITE_PRIVATE int sqlite3FixTriggerStep(
   74587   DbFixer *pFix,     /* Context of the fixation */
   74588   TriggerStep *pStep /* The trigger step be fixed to one database */
   74589 ){
   74590   while( pStep ){
   74591     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
   74592       return 1;
   74593     }
   74594     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
   74595       return 1;
   74596     }
   74597     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
   74598       return 1;
   74599     }
   74600     pStep = pStep->pNext;
   74601   }
   74602   return 0;
   74603 }
   74604 #endif
   74605 
   74606 /************** End of attach.c **********************************************/
   74607 /************** Begin file auth.c ********************************************/
   74608 /*
   74609 ** 2003 January 11
   74610 **
   74611 ** The author disclaims copyright to this source code.  In place of
   74612 ** a legal notice, here is a blessing:
   74613 **
   74614 **    May you do good and not evil.
   74615 **    May you find forgiveness for yourself and forgive others.
   74616 **    May you share freely, never taking more than you give.
   74617 **
   74618 *************************************************************************
   74619 ** This file contains code used to implement the sqlite3_set_authorizer()
   74620 ** API.  This facility is an optional feature of the library.  Embedded
   74621 ** systems that do not need this facility may omit it by recompiling
   74622 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
   74623 */
   74624 
   74625 /*
   74626 ** All of the code in this file may be omitted by defining a single
   74627 ** macro.
   74628 */
   74629 #ifndef SQLITE_OMIT_AUTHORIZATION
   74630 
   74631 /*
   74632 ** Set or clear the access authorization function.
   74633 **
   74634 ** The access authorization function is be called during the compilation
   74635 ** phase to verify that the user has read and/or write access permission on
   74636 ** various fields of the database.  The first argument to the auth function
   74637 ** is a copy of the 3rd argument to this routine.  The second argument
   74638 ** to the auth function is one of these constants:
   74639 **
   74640 **       SQLITE_CREATE_INDEX
   74641 **       SQLITE_CREATE_TABLE
   74642 **       SQLITE_CREATE_TEMP_INDEX
   74643 **       SQLITE_CREATE_TEMP_TABLE
   74644 **       SQLITE_CREATE_TEMP_TRIGGER
   74645 **       SQLITE_CREATE_TEMP_VIEW
   74646 **       SQLITE_CREATE_TRIGGER
   74647 **       SQLITE_CREATE_VIEW
   74648 **       SQLITE_DELETE
   74649 **       SQLITE_DROP_INDEX
   74650 **       SQLITE_DROP_TABLE
   74651 **       SQLITE_DROP_TEMP_INDEX
   74652 **       SQLITE_DROP_TEMP_TABLE
   74653 **       SQLITE_DROP_TEMP_TRIGGER
   74654 **       SQLITE_DROP_TEMP_VIEW
   74655 **       SQLITE_DROP_TRIGGER
   74656 **       SQLITE_DROP_VIEW
   74657 **       SQLITE_INSERT
   74658 **       SQLITE_PRAGMA
   74659 **       SQLITE_READ
   74660 **       SQLITE_SELECT
   74661 **       SQLITE_TRANSACTION
   74662 **       SQLITE_UPDATE
   74663 **
   74664 ** The third and fourth arguments to the auth function are the name of
   74665 ** the table and the column that are being accessed.  The auth function
   74666 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
   74667 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
   74668 ** means that the SQL statement will never-run - the sqlite3_exec() call
   74669 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
   74670 ** should run but attempts to read the specified column will return NULL
   74671 ** and attempts to write the column will be ignored.
   74672 **
   74673 ** Setting the auth function to NULL disables this hook.  The default
   74674 ** setting of the auth function is NULL.
   74675 */
   74676 SQLITE_API int sqlite3_set_authorizer(
   74677   sqlite3 *db,
   74678   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
   74679   void *pArg
   74680 ){
   74681   sqlite3_mutex_enter(db->mutex);
   74682   db->xAuth = xAuth;
   74683   db->pAuthArg = pArg;
   74684   sqlite3ExpirePreparedStatements(db);
   74685   sqlite3_mutex_leave(db->mutex);
   74686   return SQLITE_OK;
   74687 }
   74688 
   74689 /*
   74690 ** Write an error message into pParse->zErrMsg that explains that the
   74691 ** user-supplied authorization function returned an illegal value.
   74692 */
   74693 static void sqliteAuthBadReturnCode(Parse *pParse){
   74694   sqlite3ErrorMsg(pParse, "authorizer malfunction");
   74695   pParse->rc = SQLITE_ERROR;
   74696 }
   74697 
   74698 /*
   74699 ** Invoke the authorization callback for permission to read column zCol from
   74700 ** table zTab in database zDb. This function assumes that an authorization
   74701 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
   74702 **
   74703 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
   74704 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
   74705 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
   74706 */
   74707 SQLITE_PRIVATE int sqlite3AuthReadCol(
   74708   Parse *pParse,                  /* The parser context */
   74709   const char *zTab,               /* Table name */
   74710   const char *zCol,               /* Column name */
   74711   int iDb                         /* Index of containing database. */
   74712 ){
   74713   sqlite3 *db = pParse->db;       /* Database handle */
   74714   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
   74715   int rc;                         /* Auth callback return code */
   74716 
   74717   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
   74718   if( rc==SQLITE_DENY ){
   74719     if( db->nDb>2 || iDb!=0 ){
   74720       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
   74721     }else{
   74722       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
   74723     }
   74724     pParse->rc = SQLITE_AUTH;
   74725   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
   74726     sqliteAuthBadReturnCode(pParse);
   74727   }
   74728   return rc;
   74729 }
   74730 
   74731 /*
   74732 ** The pExpr should be a TK_COLUMN expression.  The table referred to
   74733 ** is in pTabList or else it is the NEW or OLD table of a trigger.
   74734 ** Check to see if it is OK to read this particular column.
   74735 **
   74736 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
   74737 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
   74738 ** then generate an error.
   74739 */
   74740 SQLITE_PRIVATE void sqlite3AuthRead(
   74741   Parse *pParse,        /* The parser context */
   74742   Expr *pExpr,          /* The expression to check authorization on */
   74743   Schema *pSchema,      /* The schema of the expression */
   74744   SrcList *pTabList     /* All table that pExpr might refer to */
   74745 ){
   74746   sqlite3 *db = pParse->db;
   74747   Table *pTab = 0;      /* The table being read */
   74748   const char *zCol;     /* Name of the column of the table */
   74749   int iSrc;             /* Index in pTabList->a[] of table being read */
   74750   int iDb;              /* The index of the database the expression refers to */
   74751   int iCol;             /* Index of column in table */
   74752 
   74753   if( db->xAuth==0 ) return;
   74754   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
   74755   if( iDb<0 ){
   74756     /* An attempt to read a column out of a subquery or other
   74757     ** temporary table. */
   74758     return;
   74759   }
   74760 
   74761   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
   74762   if( pExpr->op==TK_TRIGGER ){
   74763     pTab = pParse->pTriggerTab;
   74764   }else{
   74765     assert( pTabList );
   74766     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
   74767       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
   74768         pTab = pTabList->a[iSrc].pTab;
   74769         break;
   74770       }
   74771     }
   74772   }
   74773   iCol = pExpr->iColumn;
   74774   if( NEVER(pTab==0) ) return;
   74775 
   74776   if( iCol>=0 ){
   74777     assert( iCol<pTab->nCol );
   74778     zCol = pTab->aCol[iCol].zName;
   74779   }else if( pTab->iPKey>=0 ){
   74780     assert( pTab->iPKey<pTab->nCol );
   74781     zCol = pTab->aCol[pTab->iPKey].zName;
   74782   }else{
   74783     zCol = "ROWID";
   74784   }
   74785   assert( iDb>=0 && iDb<db->nDb );
   74786   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
   74787     pExpr->op = TK_NULL;
   74788   }
   74789 }
   74790 
   74791 /*
   74792 ** Do an authorization check using the code and arguments given.  Return
   74793 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
   74794 ** is returned, then the error count and error message in pParse are
   74795 ** modified appropriately.
   74796 */
   74797 SQLITE_PRIVATE int sqlite3AuthCheck(
   74798   Parse *pParse,
   74799   int code,
   74800   const char *zArg1,
   74801   const char *zArg2,
   74802   const char *zArg3
   74803 ){
   74804   sqlite3 *db = pParse->db;
   74805   int rc;
   74806 
   74807   /* Don't do any authorization checks if the database is initialising
   74808   ** or if the parser is being invoked from within sqlite3_declare_vtab.
   74809   */
   74810   if( db->init.busy || IN_DECLARE_VTAB ){
   74811     return SQLITE_OK;
   74812   }
   74813 
   74814   if( db->xAuth==0 ){
   74815     return SQLITE_OK;
   74816   }
   74817   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
   74818   if( rc==SQLITE_DENY ){
   74819     sqlite3ErrorMsg(pParse, "not authorized");
   74820     pParse->rc = SQLITE_AUTH;
   74821   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
   74822     rc = SQLITE_DENY;
   74823     sqliteAuthBadReturnCode(pParse);
   74824   }
   74825   return rc;
   74826 }
   74827 
   74828 /*
   74829 ** Push an authorization context.  After this routine is called, the
   74830 ** zArg3 argument to authorization callbacks will be zContext until
   74831 ** popped.  Or if pParse==0, this routine is a no-op.
   74832 */
   74833 SQLITE_PRIVATE void sqlite3AuthContextPush(
   74834   Parse *pParse,
   74835   AuthContext *pContext,
   74836   const char *zContext
   74837 ){
   74838   assert( pParse );
   74839   pContext->pParse = pParse;
   74840   pContext->zAuthContext = pParse->zAuthContext;
   74841   pParse->zAuthContext = zContext;
   74842 }
   74843 
   74844 /*
   74845 ** Pop an authorization context that was previously pushed
   74846 ** by sqlite3AuthContextPush
   74847 */
   74848 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
   74849   if( pContext->pParse ){
   74850     pContext->pParse->zAuthContext = pContext->zAuthContext;
   74851     pContext->pParse = 0;
   74852   }
   74853 }
   74854 
   74855 #endif /* SQLITE_OMIT_AUTHORIZATION */
   74856 
   74857 /************** End of auth.c ************************************************/
   74858 /************** Begin file build.c *******************************************/
   74859 /*
   74860 ** 2001 September 15
   74861 **
   74862 ** The author disclaims copyright to this source code.  In place of
   74863 ** a legal notice, here is a blessing:
   74864 **
   74865 **    May you do good and not evil.
   74866 **    May you find forgiveness for yourself and forgive others.
   74867 **    May you share freely, never taking more than you give.
   74868 **
   74869 *************************************************************************
   74870 ** This file contains C code routines that are called by the SQLite parser
   74871 ** when syntax rules are reduced.  The routines in this file handle the
   74872 ** following kinds of SQL syntax:
   74873 **
   74874 **     CREATE TABLE
   74875 **     DROP TABLE
   74876 **     CREATE INDEX
   74877 **     DROP INDEX
   74878 **     creating ID lists
   74879 **     BEGIN TRANSACTION
   74880 **     COMMIT
   74881 **     ROLLBACK
   74882 */
   74883 
   74884 /*
   74885 ** This routine is called when a new SQL statement is beginning to
   74886 ** be parsed.  Initialize the pParse structure as needed.
   74887 */
   74888 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
   74889   pParse->explain = (u8)explainFlag;
   74890   pParse->nVar = 0;
   74891 }
   74892 
   74893 #ifndef SQLITE_OMIT_SHARED_CACHE
   74894 /*
   74895 ** The TableLock structure is only used by the sqlite3TableLock() and
   74896 ** codeTableLocks() functions.
   74897 */
   74898 struct TableLock {
   74899   int iDb;             /* The database containing the table to be locked */
   74900   int iTab;            /* The root page of the table to be locked */
   74901   u8 isWriteLock;      /* True for write lock.  False for a read lock */
   74902   const char *zName;   /* Name of the table */
   74903 };
   74904 
   74905 /*
   74906 ** Record the fact that we want to lock a table at run-time.
   74907 **
   74908 ** The table to be locked has root page iTab and is found in database iDb.
   74909 ** A read or a write lock can be taken depending on isWritelock.
   74910 **
   74911 ** This routine just records the fact that the lock is desired.  The
   74912 ** code to make the lock occur is generated by a later call to
   74913 ** codeTableLocks() which occurs during sqlite3FinishCoding().
   74914 */
   74915 SQLITE_PRIVATE void sqlite3TableLock(
   74916   Parse *pParse,     /* Parsing context */
   74917   int iDb,           /* Index of the database containing the table to lock */
   74918   int iTab,          /* Root page number of the table to be locked */
   74919   u8 isWriteLock,    /* True for a write lock */
   74920   const char *zName  /* Name of the table to be locked */
   74921 ){
   74922   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   74923   int i;
   74924   int nBytes;
   74925   TableLock *p;
   74926   assert( iDb>=0 );
   74927 
   74928   for(i=0; i<pToplevel->nTableLock; i++){
   74929     p = &pToplevel->aTableLock[i];
   74930     if( p->iDb==iDb && p->iTab==iTab ){
   74931       p->isWriteLock = (p->isWriteLock || isWriteLock);
   74932       return;
   74933     }
   74934   }
   74935 
   74936   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
   74937   pToplevel->aTableLock =
   74938       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
   74939   if( pToplevel->aTableLock ){
   74940     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
   74941     p->iDb = iDb;
   74942     p->iTab = iTab;
   74943     p->isWriteLock = isWriteLock;
   74944     p->zName = zName;
   74945   }else{
   74946     pToplevel->nTableLock = 0;
   74947     pToplevel->db->mallocFailed = 1;
   74948   }
   74949 }
   74950 
   74951 /*
   74952 ** Code an OP_TableLock instruction for each table locked by the
   74953 ** statement (configured by calls to sqlite3TableLock()).
   74954 */
   74955 static void codeTableLocks(Parse *pParse){
   74956   int i;
   74957   Vdbe *pVdbe;
   74958 
   74959   pVdbe = sqlite3GetVdbe(pParse);
   74960   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
   74961 
   74962   for(i=0; i<pParse->nTableLock; i++){
   74963     TableLock *p = &pParse->aTableLock[i];
   74964     int p1 = p->iDb;
   74965     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
   74966                       p->zName, P4_STATIC);
   74967   }
   74968 }
   74969 #else
   74970   #define codeTableLocks(x)
   74971 #endif
   74972 
   74973 /*
   74974 ** This routine is called after a single SQL statement has been
   74975 ** parsed and a VDBE program to execute that statement has been
   74976 ** prepared.  This routine puts the finishing touches on the
   74977 ** VDBE program and resets the pParse structure for the next
   74978 ** parse.
   74979 **
   74980 ** Note that if an error occurred, it might be the case that
   74981 ** no VDBE code was generated.
   74982 */
   74983 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   74984   sqlite3 *db;
   74985   Vdbe *v;
   74986 
   74987   db = pParse->db;
   74988   if( db->mallocFailed ) return;
   74989   if( pParse->nested ) return;
   74990   if( pParse->nErr ) return;
   74991 
   74992   /* Begin by generating some termination code at the end of the
   74993   ** vdbe program
   74994   */
   74995   v = sqlite3GetVdbe(pParse);
   74996   assert( !pParse->isMultiWrite
   74997        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   74998   if( v ){
   74999     sqlite3VdbeAddOp0(v, OP_Halt);
   75000 
   75001     /* The cookie mask contains one bit for each database file open.
   75002     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   75003     ** set for each database that is used.  Generate code to start a
   75004     ** transaction on each used database and to verify the schema cookie
   75005     ** on each used database.
   75006     */
   75007     if( pParse->cookieGoto>0 ){
   75008       u32 mask;
   75009       int iDb;
   75010       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   75011       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   75012         if( (mask & pParse->cookieMask)==0 ) continue;
   75013         sqlite3VdbeUsesBtree(v, iDb);
   75014         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   75015         if( db->init.busy==0 ){
   75016           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
   75017         }
   75018       }
   75019 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75020       {
   75021         int i;
   75022         for(i=0; i<pParse->nVtabLock; i++){
   75023           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   75024           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   75025         }
   75026         pParse->nVtabLock = 0;
   75027       }
   75028 #endif
   75029 
   75030       /* Once all the cookies have been verified and transactions opened,
   75031       ** obtain the required table-locks. This is a no-op unless the
   75032       ** shared-cache feature is enabled.
   75033       */
   75034       codeTableLocks(pParse);
   75035 
   75036       /* Initialize any AUTOINCREMENT data structures required.
   75037       */
   75038       sqlite3AutoincrementBegin(pParse);
   75039 
   75040       /* Finally, jump back to the beginning of the executable code. */
   75041       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
   75042     }
   75043   }
   75044 
   75045 
   75046   /* Get the VDBE program ready for execution
   75047   */
   75048   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
   75049 #ifdef SQLITE_DEBUG
   75050     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
   75051     sqlite3VdbeTrace(v, trace);
   75052 #endif
   75053     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
   75054     /* A minimum of one cursor is required if autoincrement is used
   75055     *  See ticket [a696379c1f08866] */
   75056     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
   75057     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
   75058                          pParse->nTab, pParse->nMaxArg, pParse->explain,
   75059                          pParse->isMultiWrite && pParse->mayAbort);
   75060     pParse->rc = SQLITE_DONE;
   75061     pParse->colNamesSet = 0;
   75062   }else{
   75063     pParse->rc = SQLITE_ERROR;
   75064   }
   75065   pParse->nTab = 0;
   75066   pParse->nMem = 0;
   75067   pParse->nSet = 0;
   75068   pParse->nVar = 0;
   75069   pParse->cookieMask = 0;
   75070   pParse->cookieGoto = 0;
   75071 }
   75072 
   75073 /*
   75074 ** Run the parser and code generator recursively in order to generate
   75075 ** code for the SQL statement given onto the end of the pParse context
   75076 ** currently under construction.  When the parser is run recursively
   75077 ** this way, the final OP_Halt is not appended and other initialization
   75078 ** and finalization steps are omitted because those are handling by the
   75079 ** outermost parser.
   75080 **
   75081 ** Not everything is nestable.  This facility is designed to permit
   75082 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
   75083 ** care if you decide to try to use this routine for some other purposes.
   75084 */
   75085 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
   75086   va_list ap;
   75087   char *zSql;
   75088   char *zErrMsg = 0;
   75089   sqlite3 *db = pParse->db;
   75090 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
   75091   char saveBuf[SAVE_SZ];
   75092 
   75093   if( pParse->nErr ) return;
   75094   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
   75095   va_start(ap, zFormat);
   75096   zSql = sqlite3VMPrintf(db, zFormat, ap);
   75097   va_end(ap);
   75098   if( zSql==0 ){
   75099     return;   /* A malloc must have failed */
   75100   }
   75101   pParse->nested++;
   75102   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
   75103   memset(&pParse->nVar, 0, SAVE_SZ);
   75104   sqlite3RunParser(pParse, zSql, &zErrMsg);
   75105   sqlite3DbFree(db, zErrMsg);
   75106   sqlite3DbFree(db, zSql);
   75107   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
   75108   pParse->nested--;
   75109 }
   75110 
   75111 /*
   75112 ** Locate the in-memory structure that describes a particular database
   75113 ** table given the name of that table and (optionally) the name of the
   75114 ** database containing the table.  Return NULL if not found.
   75115 **
   75116 ** If zDatabase is 0, all databases are searched for the table and the
   75117 ** first matching table is returned.  (No checking for duplicate table
   75118 ** names is done.)  The search order is TEMP first, then MAIN, then any
   75119 ** auxiliary databases added using the ATTACH command.
   75120 **
   75121 ** See also sqlite3LocateTable().
   75122 */
   75123 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
   75124   Table *p = 0;
   75125   int i;
   75126   int nName;
   75127   assert( zName!=0 );
   75128   nName = sqlite3Strlen30(zName);
   75129   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   75130     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
   75131     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
   75132     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
   75133     if( p ) break;
   75134   }
   75135   return p;
   75136 }
   75137 
   75138 /*
   75139 ** Locate the in-memory structure that describes a particular database
   75140 ** table given the name of that table and (optionally) the name of the
   75141 ** database containing the table.  Return NULL if not found.  Also leave an
   75142 ** error message in pParse->zErrMsg.
   75143 **
   75144 ** The difference between this routine and sqlite3FindTable() is that this
   75145 ** routine leaves an error message in pParse->zErrMsg where
   75146 ** sqlite3FindTable() does not.
   75147 */
   75148 SQLITE_PRIVATE Table *sqlite3LocateTable(
   75149   Parse *pParse,         /* context in which to report errors */
   75150   int isView,            /* True if looking for a VIEW rather than a TABLE */
   75151   const char *zName,     /* Name of the table we are looking for */
   75152   const char *zDbase     /* Name of the database.  Might be NULL */
   75153 ){
   75154   Table *p;
   75155 
   75156   /* Read the database schema. If an error occurs, leave an error message
   75157   ** and code in pParse and return NULL. */
   75158   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   75159     return 0;
   75160   }
   75161 
   75162   p = sqlite3FindTable(pParse->db, zName, zDbase);
   75163   if( p==0 ){
   75164     const char *zMsg = isView ? "no such view" : "no such table";
   75165     if( zDbase ){
   75166       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
   75167     }else{
   75168       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
   75169     }
   75170     pParse->checkSchema = 1;
   75171   }
   75172   return p;
   75173 }
   75174 
   75175 /*
   75176 ** Locate the in-memory structure that describes
   75177 ** a particular index given the name of that index
   75178 ** and the name of the database that contains the index.
   75179 ** Return NULL if not found.
   75180 **
   75181 ** If zDatabase is 0, all databases are searched for the
   75182 ** table and the first matching index is returned.  (No checking
   75183 ** for duplicate index names is done.)  The search order is
   75184 ** TEMP first, then MAIN, then any auxiliary databases added
   75185 ** using the ATTACH command.
   75186 */
   75187 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
   75188   Index *p = 0;
   75189   int i;
   75190   int nName = sqlite3Strlen30(zName);
   75191   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   75192     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   75193     Schema *pSchema = db->aDb[j].pSchema;
   75194     assert( pSchema );
   75195     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
   75196     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
   75197     if( p ) break;
   75198   }
   75199   return p;
   75200 }
   75201 
   75202 /*
   75203 ** Reclaim the memory used by an index
   75204 */
   75205 static void freeIndex(sqlite3 *db, Index *p){
   75206 #ifndef SQLITE_OMIT_ANALYZE
   75207   sqlite3DeleteIndexSamples(db, p);
   75208 #endif
   75209   sqlite3DbFree(db, p->zColAff);
   75210   sqlite3DbFree(db, p);
   75211 }
   75212 
   75213 /*
   75214 ** For the index called zIdxName which is found in the database iDb,
   75215 ** unlike that index from its Table then remove the index from
   75216 ** the index hash table and free all memory structures associated
   75217 ** with the index.
   75218 */
   75219 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
   75220   Index *pIndex;
   75221   int len;
   75222   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
   75223 
   75224   len = sqlite3Strlen30(zIdxName);
   75225   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
   75226   if( pIndex ){
   75227     if( pIndex->pTable->pIndex==pIndex ){
   75228       pIndex->pTable->pIndex = pIndex->pNext;
   75229     }else{
   75230       Index *p;
   75231       /* Justification of ALWAYS();  The index must be on the list of
   75232       ** indices. */
   75233       p = pIndex->pTable->pIndex;
   75234       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
   75235       if( ALWAYS(p && p->pNext==pIndex) ){
   75236         p->pNext = pIndex->pNext;
   75237       }
   75238     }
   75239     freeIndex(db, pIndex);
   75240   }
   75241   db->flags |= SQLITE_InternChanges;
   75242 }
   75243 
   75244 /*
   75245 ** Erase all schema information from the in-memory hash tables of
   75246 ** a single database.  This routine is called to reclaim memory
   75247 ** before the database closes.  It is also called during a rollback
   75248 ** if there were schema changes during the transaction or if a
   75249 ** schema-cookie mismatch occurs.
   75250 **
   75251 ** If iDb==0 then reset the internal schema tables for all database
   75252 ** files.  If iDb>=1 then reset the internal schema for only the
   75253 ** single file indicated.
   75254 */
   75255 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
   75256   int i, j;
   75257   assert( iDb>=0 && iDb<db->nDb );
   75258 
   75259   if( iDb==0 ){
   75260     sqlite3BtreeEnterAll(db);
   75261   }
   75262   for(i=iDb; i<db->nDb; i++){
   75263     Db *pDb = &db->aDb[i];
   75264     if( pDb->pSchema ){
   75265       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
   75266       sqlite3SchemaFree(pDb->pSchema);
   75267     }
   75268     if( iDb>0 ) return;
   75269   }
   75270   assert( iDb==0 );
   75271   db->flags &= ~SQLITE_InternChanges;
   75272   sqlite3VtabUnlockList(db);
   75273   sqlite3BtreeLeaveAll(db);
   75274 
   75275   /* If one or more of the auxiliary database files has been closed,
   75276   ** then remove them from the auxiliary database list.  We take the
   75277   ** opportunity to do this here since we have just deleted all of the
   75278   ** schema hash tables and therefore do not have to make any changes
   75279   ** to any of those tables.
   75280   */
   75281   for(i=j=2; i<db->nDb; i++){
   75282     struct Db *pDb = &db->aDb[i];
   75283     if( pDb->pBt==0 ){
   75284       sqlite3DbFree(db, pDb->zName);
   75285       pDb->zName = 0;
   75286       continue;
   75287     }
   75288     if( j<i ){
   75289       db->aDb[j] = db->aDb[i];
   75290     }
   75291     j++;
   75292   }
   75293   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
   75294   db->nDb = j;
   75295   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
   75296     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
   75297     sqlite3DbFree(db, db->aDb);
   75298     db->aDb = db->aDbStatic;
   75299   }
   75300 }
   75301 
   75302 /*
   75303 ** This routine is called when a commit occurs.
   75304 */
   75305 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
   75306   db->flags &= ~SQLITE_InternChanges;
   75307 }
   75308 
   75309 /*
   75310 ** Delete memory allocated for the column names of a table or view (the
   75311 ** Table.aCol[] array).
   75312 */
   75313 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
   75314   int i;
   75315   Column *pCol;
   75316   assert( pTable!=0 );
   75317   if( (pCol = pTable->aCol)!=0 ){
   75318     for(i=0; i<pTable->nCol; i++, pCol++){
   75319       sqlite3DbFree(db, pCol->zName);
   75320       sqlite3ExprDelete(db, pCol->pDflt);
   75321       sqlite3DbFree(db, pCol->zDflt);
   75322       sqlite3DbFree(db, pCol->zType);
   75323       sqlite3DbFree(db, pCol->zColl);
   75324     }
   75325     sqlite3DbFree(db, pTable->aCol);
   75326   }
   75327 }
   75328 
   75329 /*
   75330 ** Remove the memory data structures associated with the given
   75331 ** Table.  No changes are made to disk by this routine.
   75332 **
   75333 ** This routine just deletes the data structure.  It does not unlink
   75334 ** the table data structure from the hash table.  But it does destroy
   75335 ** memory structures of the indices and foreign keys associated with
   75336 ** the table.
   75337 */
   75338 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
   75339   Index *pIndex, *pNext;
   75340 
   75341   assert( !pTable || pTable->nRef>0 );
   75342 
   75343   /* Do not delete the table until the reference count reaches zero. */
   75344   if( !pTable ) return;
   75345   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
   75346 
   75347   /* Delete all indices associated with this table. */
   75348   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
   75349     pNext = pIndex->pNext;
   75350     assert( pIndex->pSchema==pTable->pSchema );
   75351     if( !db || db->pnBytesFreed==0 ){
   75352       char *zName = pIndex->zName;
   75353       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
   75354 	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
   75355       );
   75356       assert( pOld==pIndex || pOld==0 );
   75357     }
   75358     freeIndex(db, pIndex);
   75359   }
   75360 
   75361   /* Delete any foreign keys attached to this table. */
   75362   sqlite3FkDelete(db, pTable);
   75363 
   75364   /* Delete the Table structure itself.
   75365   */
   75366   sqliteDeleteColumnNames(db, pTable);
   75367   sqlite3DbFree(db, pTable->zName);
   75368   sqlite3DbFree(db, pTable->zColAff);
   75369   sqlite3SelectDelete(db, pTable->pSelect);
   75370 #ifndef SQLITE_OMIT_CHECK
   75371   sqlite3ExprDelete(db, pTable->pCheck);
   75372 #endif
   75373 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75374   sqlite3VtabClear(db, pTable);
   75375 #endif
   75376   sqlite3DbFree(db, pTable);
   75377 }
   75378 
   75379 /*
   75380 ** Unlink the given table from the hash tables and the delete the
   75381 ** table structure with all its indices and foreign keys.
   75382 */
   75383 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
   75384   Table *p;
   75385   Db *pDb;
   75386 
   75387   assert( db!=0 );
   75388   assert( iDb>=0 && iDb<db->nDb );
   75389   assert( zTabName );
   75390   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
   75391   pDb = &db->aDb[iDb];
   75392   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
   75393                         sqlite3Strlen30(zTabName),0);
   75394   sqlite3DeleteTable(db, p);
   75395   db->flags |= SQLITE_InternChanges;
   75396 }
   75397 
   75398 /*
   75399 ** Given a token, return a string that consists of the text of that
   75400 ** token.  Space to hold the returned string
   75401 ** is obtained from sqliteMalloc() and must be freed by the calling
   75402 ** function.
   75403 **
   75404 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
   75405 ** surround the body of the token are removed.
   75406 **
   75407 ** Tokens are often just pointers into the original SQL text and so
   75408 ** are not \000 terminated and are not persistent.  The returned string
   75409 ** is \000 terminated and is persistent.
   75410 */
   75411 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
   75412   char *zName;
   75413   if( pName ){
   75414     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
   75415     sqlite3Dequote(zName);
   75416   }else{
   75417     zName = 0;
   75418   }
   75419   return zName;
   75420 }
   75421 
   75422 /*
   75423 ** Open the sqlite_master table stored in database number iDb for
   75424 ** writing. The table is opened using cursor 0.
   75425 */
   75426 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
   75427   Vdbe *v = sqlite3GetVdbe(p);
   75428   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
   75429   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
   75430   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
   75431   if( p->nTab==0 ){
   75432     p->nTab = 1;
   75433   }
   75434 }
   75435 
   75436 /*
   75437 ** Parameter zName points to a nul-terminated buffer containing the name
   75438 ** of a database ("main", "temp" or the name of an attached db). This
   75439 ** function returns the index of the named database in db->aDb[], or
   75440 ** -1 if the named db cannot be found.
   75441 */
   75442 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
   75443   int i = -1;         /* Database number */
   75444   if( zName ){
   75445     Db *pDb;
   75446     int n = sqlite3Strlen30(zName);
   75447     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
   75448       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
   75449           0==sqlite3StrICmp(pDb->zName, zName) ){
   75450         break;
   75451       }
   75452     }
   75453   }
   75454   return i;
   75455 }
   75456 
   75457 /*
   75458 ** The token *pName contains the name of a database (either "main" or
   75459 ** "temp" or the name of an attached db). This routine returns the
   75460 ** index of the named database in db->aDb[], or -1 if the named db
   75461 ** does not exist.
   75462 */
   75463 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
   75464   int i;                               /* Database number */
   75465   char *zName;                         /* Name we are searching for */
   75466   zName = sqlite3NameFromToken(db, pName);
   75467   i = sqlite3FindDbName(db, zName);
   75468   sqlite3DbFree(db, zName);
   75469   return i;
   75470 }
   75471 
   75472 /* The table or view or trigger name is passed to this routine via tokens
   75473 ** pName1 and pName2. If the table name was fully qualified, for example:
   75474 **
   75475 ** CREATE TABLE xxx.yyy (...);
   75476 **
   75477 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   75478 ** the table name is not fully qualified, i.e.:
   75479 **
   75480 ** CREATE TABLE yyy(...);
   75481 **
   75482 ** Then pName1 is set to "yyy" and pName2 is "".
   75483 **
   75484 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
   75485 ** pName2) that stores the unqualified table name.  The index of the
   75486 ** database "xxx" is returned.
   75487 */
   75488 SQLITE_PRIVATE int sqlite3TwoPartName(
   75489   Parse *pParse,      /* Parsing and code generating context */
   75490   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
   75491   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
   75492   Token **pUnqual     /* Write the unqualified object name here */
   75493 ){
   75494   int iDb;                    /* Database holding the object */
   75495   sqlite3 *db = pParse->db;
   75496 
   75497   if( ALWAYS(pName2!=0) && pName2->n>0 ){
   75498     if( db->init.busy ) {
   75499       sqlite3ErrorMsg(pParse, "corrupt database");
   75500       pParse->nErr++;
   75501       return -1;
   75502     }
   75503     *pUnqual = pName2;
   75504     iDb = sqlite3FindDb(db, pName1);
   75505     if( iDb<0 ){
   75506       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
   75507       pParse->nErr++;
   75508       return -1;
   75509     }
   75510   }else{
   75511     assert( db->init.iDb==0 || db->init.busy );
   75512     iDb = db->init.iDb;
   75513     *pUnqual = pName1;
   75514   }
   75515   return iDb;
   75516 }
   75517 
   75518 /*
   75519 ** This routine is used to check if the UTF-8 string zName is a legal
   75520 ** unqualified name for a new schema object (table, index, view or
   75521 ** trigger). All names are legal except those that begin with the string
   75522 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
   75523 ** is reserved for internal use.
   75524 */
   75525 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
   75526   if( !pParse->db->init.busy && pParse->nested==0
   75527           && (pParse->db->flags & SQLITE_WriteSchema)==0
   75528           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
   75529     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
   75530     return SQLITE_ERROR;
   75531   }
   75532   return SQLITE_OK;
   75533 }
   75534 
   75535 /*
   75536 ** Begin constructing a new table representation in memory.  This is
   75537 ** the first of several action routines that get called in response
   75538 ** to a CREATE TABLE statement.  In particular, this routine is called
   75539 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
   75540 ** flag is true if the table should be stored in the auxiliary database
   75541 ** file instead of in the main database file.  This is normally the case
   75542 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
   75543 ** CREATE and TABLE.
   75544 **
   75545 ** The new table record is initialized and put in pParse->pNewTable.
   75546 ** As more of the CREATE TABLE statement is parsed, additional action
   75547 ** routines will be called to add more information to this record.
   75548 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
   75549 ** is called to complete the construction of the new table record.
   75550 */
   75551 SQLITE_PRIVATE void sqlite3StartTable(
   75552   Parse *pParse,   /* Parser context */
   75553   Token *pName1,   /* First part of the name of the table or view */
   75554   Token *pName2,   /* Second part of the name of the table or view */
   75555   int isTemp,      /* True if this is a TEMP table */
   75556   int isView,      /* True if this is a VIEW */
   75557   int isVirtual,   /* True if this is a VIRTUAL table */
   75558   int noErr        /* Do nothing if table already exists */
   75559 ){
   75560   Table *pTable;
   75561   char *zName = 0; /* The name of the new table */
   75562   sqlite3 *db = pParse->db;
   75563   Vdbe *v;
   75564   int iDb;         /* Database number to create the table in */
   75565   Token *pName;    /* Unqualified name of the table to create */
   75566 
   75567   /* The table or view name to create is passed to this routine via tokens
   75568   ** pName1 and pName2. If the table name was fully qualified, for example:
   75569   **
   75570   ** CREATE TABLE xxx.yyy (...);
   75571   **
   75572   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
   75573   ** the table name is not fully qualified, i.e.:
   75574   **
   75575   ** CREATE TABLE yyy(...);
   75576   **
   75577   ** Then pName1 is set to "yyy" and pName2 is "".
   75578   **
   75579   ** The call below sets the pName pointer to point at the token (pName1 or
   75580   ** pName2) that stores the unqualified table name. The variable iDb is
   75581   ** set to the index of the database that the table or view is to be
   75582   ** created in.
   75583   */
   75584   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   75585   if( iDb<0 ) return;
   75586   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
   75587     /* If creating a temp table, the name may not be qualified. Unless
   75588     ** the database name is "temp" anyway.  */
   75589     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
   75590     return;
   75591   }
   75592   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
   75593 
   75594   pParse->sNameToken = *pName;
   75595   zName = sqlite3NameFromToken(db, pName);
   75596   if( zName==0 ) return;
   75597   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   75598     goto begin_table_error;
   75599   }
   75600   if( db->init.iDb==1 ) isTemp = 1;
   75601 #ifndef SQLITE_OMIT_AUTHORIZATION
   75602   assert( (isTemp & 1)==isTemp );
   75603   {
   75604     int code;
   75605     char *zDb = db->aDb[iDb].zName;
   75606     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
   75607       goto begin_table_error;
   75608     }
   75609     if( isView ){
   75610       if( !OMIT_TEMPDB && isTemp ){
   75611         code = SQLITE_CREATE_TEMP_VIEW;
   75612       }else{
   75613         code = SQLITE_CREATE_VIEW;
   75614       }
   75615     }else{
   75616       if( !OMIT_TEMPDB && isTemp ){
   75617         code = SQLITE_CREATE_TEMP_TABLE;
   75618       }else{
   75619         code = SQLITE_CREATE_TABLE;
   75620       }
   75621     }
   75622     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
   75623       goto begin_table_error;
   75624     }
   75625   }
   75626 #endif
   75627 
   75628   /* Make sure the new table name does not collide with an existing
   75629   ** index or table name in the same database.  Issue an error message if
   75630   ** it does. The exception is if the statement being parsed was passed
   75631   ** to an sqlite3_declare_vtab() call. In that case only the column names
   75632   ** and types will be used, so there is no need to test for namespace
   75633   ** collisions.
   75634   */
   75635   if( !IN_DECLARE_VTAB ){
   75636     char *zDb = db->aDb[iDb].zName;
   75637     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   75638       goto begin_table_error;
   75639     }
   75640     pTable = sqlite3FindTable(db, zName, zDb);
   75641     if( pTable ){
   75642       if( !noErr ){
   75643         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
   75644       }
   75645       goto begin_table_error;
   75646     }
   75647     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
   75648       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
   75649       goto begin_table_error;
   75650     }
   75651   }
   75652 
   75653   pTable = sqlite3DbMallocZero(db, sizeof(Table));
   75654   if( pTable==0 ){
   75655     db->mallocFailed = 1;
   75656     pParse->rc = SQLITE_NOMEM;
   75657     pParse->nErr++;
   75658     goto begin_table_error;
   75659   }
   75660   pTable->zName = zName;
   75661   pTable->iPKey = -1;
   75662   pTable->pSchema = db->aDb[iDb].pSchema;
   75663   pTable->nRef = 1;
   75664   pTable->nRowEst = 1000000;
   75665   assert( pParse->pNewTable==0 );
   75666   pParse->pNewTable = pTable;
   75667 
   75668   /* If this is the magic sqlite_sequence table used by autoincrement,
   75669   ** then record a pointer to this table in the main database structure
   75670   ** so that INSERT can find the table easily.
   75671   */
   75672 #ifndef SQLITE_OMIT_AUTOINCREMENT
   75673   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
   75674     pTable->pSchema->pSeqTab = pTable;
   75675   }
   75676 #endif
   75677 
   75678   /* Begin generating the code that will insert the table record into
   75679   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
   75680   ** and allocate the record number for the table entry now.  Before any
   75681   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
   75682   ** indices to be created and the table record must come before the
   75683   ** indices.  Hence, the record number for the table must be allocated
   75684   ** now.
   75685   */
   75686   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
   75687     int j1;
   75688     int fileFormat;
   75689     int reg1, reg2, reg3;
   75690     sqlite3BeginWriteOperation(pParse, 0, iDb);
   75691 
   75692 #ifndef SQLITE_OMIT_VIRTUALTABLE
   75693     if( isVirtual ){
   75694       sqlite3VdbeAddOp0(v, OP_VBegin);
   75695     }
   75696 #endif
   75697 
   75698     /* If the file format and encoding in the database have not been set,
   75699     ** set them now.
   75700     */
   75701     reg1 = pParse->regRowid = ++pParse->nMem;
   75702     reg2 = pParse->regRoot = ++pParse->nMem;
   75703     reg3 = ++pParse->nMem;
   75704     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   75705     sqlite3VdbeUsesBtree(v, iDb);
   75706     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
   75707     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   75708                   1 : SQLITE_MAX_FILE_FORMAT;
   75709     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   75710     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   75711     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   75712     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   75713     sqlite3VdbeJumpHere(v, j1);
   75714 
   75715     /* This just creates a place-holder record in the sqlite_master table.
   75716     ** The record created does not contain anything yet.  It will be replaced
   75717     ** by the real entry in code generated at sqlite3EndTable().
   75718     **
   75719     ** The rowid for the new entry is left in register pParse->regRowid.
   75720     ** The root page number of the new table is left in reg pParse->regRoot.
   75721     ** The rowid and root page number values are needed by the code that
   75722     ** sqlite3EndTable will generate.
   75723     */
   75724 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   75725     if( isView || isVirtual ){
   75726       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
   75727     }else
   75728 #endif
   75729     {
   75730       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
   75731     }
   75732     sqlite3OpenMasterTable(pParse, iDb);
   75733     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
   75734     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
   75735     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
   75736     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   75737     sqlite3VdbeAddOp0(v, OP_Close);
   75738   }
   75739 
   75740   /* Normal (non-error) return. */
   75741   return;
   75742 
   75743   /* If an error occurs, we jump here */
   75744 begin_table_error:
   75745   sqlite3DbFree(db, zName);
   75746   return;
   75747 }
   75748 
   75749 /*
   75750 ** This macro is used to compare two strings in a case-insensitive manner.
   75751 ** It is slightly faster than calling sqlite3StrICmp() directly, but
   75752 ** produces larger code.
   75753 **
   75754 ** WARNING: This macro is not compatible with the strcmp() family. It
   75755 ** returns true if the two strings are equal, otherwise false.
   75756 */
   75757 #define STRICMP(x, y) (\
   75758 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
   75759 sqlite3UpperToLower[*(unsigned char *)(y)]     \
   75760 && sqlite3StrICmp((x)+1,(y)+1)==0 )
   75761 
   75762 /*
   75763 ** Add a new column to the table currently being constructed.
   75764 **
   75765 ** The parser calls this routine once for each column declaration
   75766 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
   75767 ** first to get things going.  Then this routine is called for each
   75768 ** column.
   75769 */
   75770 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
   75771   Table *p;
   75772   int i;
   75773   char *z;
   75774   Column *pCol;
   75775   sqlite3 *db = pParse->db;
   75776   if( (p = pParse->pNewTable)==0 ) return;
   75777 #if SQLITE_MAX_COLUMN
   75778   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   75779     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
   75780     return;
   75781   }
   75782 #endif
   75783   z = sqlite3NameFromToken(db, pName);
   75784   if( z==0 ) return;
   75785   for(i=0; i<p->nCol; i++){
   75786     if( STRICMP(z, p->aCol[i].zName) ){
   75787       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
   75788       sqlite3DbFree(db, z);
   75789       return;
   75790     }
   75791   }
   75792   if( (p->nCol & 0x7)==0 ){
   75793     Column *aNew;
   75794     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
   75795     if( aNew==0 ){
   75796       sqlite3DbFree(db, z);
   75797       return;
   75798     }
   75799     p->aCol = aNew;
   75800   }
   75801   pCol = &p->aCol[p->nCol];
   75802   memset(pCol, 0, sizeof(p->aCol[0]));
   75803   pCol->zName = z;
   75804 
   75805   /* If there is no type specified, columns have the default affinity
   75806   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
   75807   ** be called next to set pCol->affinity correctly.
   75808   */
   75809   pCol->affinity = SQLITE_AFF_NONE;
   75810   p->nCol++;
   75811 }
   75812 
   75813 /*
   75814 ** This routine is called by the parser while in the middle of
   75815 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
   75816 ** been seen on a column.  This routine sets the notNull flag on
   75817 ** the column currently under construction.
   75818 */
   75819 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
   75820   Table *p;
   75821   p = pParse->pNewTable;
   75822   if( p==0 || NEVER(p->nCol<1) ) return;
   75823   p->aCol[p->nCol-1].notNull = (u8)onError;
   75824 }
   75825 
   75826 /*
   75827 ** Scan the column type name zType (length nType) and return the
   75828 ** associated affinity type.
   75829 **
   75830 ** This routine does a case-independent search of zType for the
   75831 ** substrings in the following table. If one of the substrings is
   75832 ** found, the corresponding affinity is returned. If zType contains
   75833 ** more than one of the substrings, entries toward the top of
   75834 ** the table take priority. For example, if zType is 'BLOBINT',
   75835 ** SQLITE_AFF_INTEGER is returned.
   75836 **
   75837 ** Substring     | Affinity
   75838 ** --------------------------------
   75839 ** 'INT'         | SQLITE_AFF_INTEGER
   75840 ** 'CHAR'        | SQLITE_AFF_TEXT
   75841 ** 'CLOB'        | SQLITE_AFF_TEXT
   75842 ** 'TEXT'        | SQLITE_AFF_TEXT
   75843 ** 'BLOB'        | SQLITE_AFF_NONE
   75844 ** 'REAL'        | SQLITE_AFF_REAL
   75845 ** 'FLOA'        | SQLITE_AFF_REAL
   75846 ** 'DOUB'        | SQLITE_AFF_REAL
   75847 **
   75848 ** If none of the substrings in the above table are found,
   75849 ** SQLITE_AFF_NUMERIC is returned.
   75850 */
   75851 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
   75852   u32 h = 0;
   75853   char aff = SQLITE_AFF_NUMERIC;
   75854 
   75855   if( zIn ) while( zIn[0] ){
   75856     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
   75857     zIn++;
   75858     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
   75859       aff = SQLITE_AFF_TEXT;
   75860     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
   75861       aff = SQLITE_AFF_TEXT;
   75862     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
   75863       aff = SQLITE_AFF_TEXT;
   75864     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
   75865         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
   75866       aff = SQLITE_AFF_NONE;
   75867 #ifndef SQLITE_OMIT_FLOATING_POINT
   75868     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
   75869         && aff==SQLITE_AFF_NUMERIC ){
   75870       aff = SQLITE_AFF_REAL;
   75871     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
   75872         && aff==SQLITE_AFF_NUMERIC ){
   75873       aff = SQLITE_AFF_REAL;
   75874     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
   75875         && aff==SQLITE_AFF_NUMERIC ){
   75876       aff = SQLITE_AFF_REAL;
   75877 #endif
   75878     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
   75879       aff = SQLITE_AFF_INTEGER;
   75880       break;
   75881     }
   75882   }
   75883 
   75884   return aff;
   75885 }
   75886 
   75887 /*
   75888 ** This routine is called by the parser while in the middle of
   75889 ** parsing a CREATE TABLE statement.  The pFirst token is the first
   75890 ** token in the sequence of tokens that describe the type of the
   75891 ** column currently under construction.   pLast is the last token
   75892 ** in the sequence.  Use this information to construct a string
   75893 ** that contains the typename of the column and store that string
   75894 ** in zType.
   75895 */
   75896 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
   75897   Table *p;
   75898   Column *pCol;
   75899 
   75900   p = pParse->pNewTable;
   75901   if( p==0 || NEVER(p->nCol<1) ) return;
   75902   pCol = &p->aCol[p->nCol-1];
   75903   assert( pCol->zType==0 );
   75904   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
   75905   pCol->affinity = sqlite3AffinityType(pCol->zType);
   75906 }
   75907 
   75908 /*
   75909 ** The expression is the default value for the most recently added column
   75910 ** of the table currently under construction.
   75911 **
   75912 ** Default value expressions must be constant.  Raise an exception if this
   75913 ** is not the case.
   75914 **
   75915 ** This routine is called by the parser while in the middle of
   75916 ** parsing a CREATE TABLE statement.
   75917 */
   75918 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
   75919   Table *p;
   75920   Column *pCol;
   75921   sqlite3 *db = pParse->db;
   75922   p = pParse->pNewTable;
   75923   if( p!=0 ){
   75924     pCol = &(p->aCol[p->nCol-1]);
   75925     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
   75926       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   75927           pCol->zName);
   75928     }else{
   75929       /* A copy of pExpr is used instead of the original, as pExpr contains
   75930       ** tokens that point to volatile memory. The 'span' of the expression
   75931       ** is required by pragma table_info.
   75932       */
   75933       sqlite3ExprDelete(db, pCol->pDflt);
   75934       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
   75935       sqlite3DbFree(db, pCol->zDflt);
   75936       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
   75937                                      (int)(pSpan->zEnd - pSpan->zStart));
   75938     }
   75939   }
   75940   sqlite3ExprDelete(db, pSpan->pExpr);
   75941 }
   75942 
   75943 /*
   75944 ** Designate the PRIMARY KEY for the table.  pList is a list of names
   75945 ** of columns that form the primary key.  If pList is NULL, then the
   75946 ** most recently added column of the table is the primary key.
   75947 **
   75948 ** A table can have at most one primary key.  If the table already has
   75949 ** a primary key (and this is the second primary key) then create an
   75950 ** error.
   75951 **
   75952 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
   75953 ** then we will try to use that column as the rowid.  Set the Table.iPKey
   75954 ** field of the table under construction to be the index of the
   75955 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
   75956 ** no INTEGER PRIMARY KEY.
   75957 **
   75958 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
   75959 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
   75960 */
   75961 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   75962   Parse *pParse,    /* Parsing context */
   75963   ExprList *pList,  /* List of field names to be indexed */
   75964   int onError,      /* What to do with a uniqueness conflict */
   75965   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
   75966   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
   75967 ){
   75968   Table *pTab = pParse->pNewTable;
   75969   char *zType = 0;
   75970   int iCol = -1, i;
   75971   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
   75972   if( pTab->tabFlags & TF_HasPrimaryKey ){
   75973     sqlite3ErrorMsg(pParse,
   75974       "table \"%s\" has more than one primary key", pTab->zName);
   75975     goto primary_key_exit;
   75976   }
   75977   pTab->tabFlags |= TF_HasPrimaryKey;
   75978   if( pList==0 ){
   75979     iCol = pTab->nCol - 1;
   75980     pTab->aCol[iCol].isPrimKey = 1;
   75981   }else{
   75982     for(i=0; i<pList->nExpr; i++){
   75983       for(iCol=0; iCol<pTab->nCol; iCol++){
   75984         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
   75985           break;
   75986         }
   75987       }
   75988       if( iCol<pTab->nCol ){
   75989         pTab->aCol[iCol].isPrimKey = 1;
   75990       }
   75991     }
   75992     if( pList->nExpr>1 ) iCol = -1;
   75993   }
   75994   if( iCol>=0 && iCol<pTab->nCol ){
   75995     zType = pTab->aCol[iCol].zType;
   75996   }
   75997   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
   75998         && sortOrder==SQLITE_SO_ASC ){
   75999     pTab->iPKey = iCol;
   76000     pTab->keyConf = (u8)onError;
   76001     assert( autoInc==0 || autoInc==1 );
   76002     pTab->tabFlags |= autoInc*TF_Autoincrement;
   76003   }else if( autoInc ){
   76004 #ifndef SQLITE_OMIT_AUTOINCREMENT
   76005     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
   76006        "INTEGER PRIMARY KEY");
   76007 #endif
   76008   }else{
   76009     Index *p;
   76010     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
   76011     if( p ){
   76012       p->autoIndex = 2;
   76013     }
   76014     pList = 0;
   76015   }
   76016 
   76017 primary_key_exit:
   76018   sqlite3ExprListDelete(pParse->db, pList);
   76019   return;
   76020 }
   76021 
   76022 /*
   76023 ** Add a new CHECK constraint to the table currently under construction.
   76024 */
   76025 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
   76026   Parse *pParse,    /* Parsing context */
   76027   Expr *pCheckExpr  /* The check expression */
   76028 ){
   76029   sqlite3 *db = pParse->db;
   76030 #ifndef SQLITE_OMIT_CHECK
   76031   Table *pTab = pParse->pNewTable;
   76032   if( pTab && !IN_DECLARE_VTAB ){
   76033     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
   76034   }else
   76035 #endif
   76036   {
   76037     sqlite3ExprDelete(db, pCheckExpr);
   76038   }
   76039 }
   76040 
   76041 /*
   76042 ** Set the collation function of the most recently parsed table column
   76043 ** to the CollSeq given.
   76044 */
   76045 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   76046   Table *p;
   76047   int i;
   76048   char *zColl;              /* Dequoted name of collation sequence */
   76049   sqlite3 *db;
   76050 
   76051   if( (p = pParse->pNewTable)==0 ) return;
   76052   i = p->nCol-1;
   76053   db = pParse->db;
   76054   zColl = sqlite3NameFromToken(db, pToken);
   76055   if( !zColl ) return;
   76056 
   76057   if( sqlite3LocateCollSeq(pParse, zColl) ){
   76058     Index *pIdx;
   76059     p->aCol[i].zColl = zColl;
   76060 
   76061     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
   76062     ** then an index may have been created on this column before the
   76063     ** collation type was added. Correct this if it is the case.
   76064     */
   76065     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
   76066       assert( pIdx->nColumn==1 );
   76067       if( pIdx->aiColumn[0]==i ){
   76068         pIdx->azColl[0] = p->aCol[i].zColl;
   76069       }
   76070     }
   76071   }else{
   76072     sqlite3DbFree(db, zColl);
   76073   }
   76074 }
   76075 
   76076 /*
   76077 ** This function returns the collation sequence for database native text
   76078 ** encoding identified by the string zName, length nName.
   76079 **
   76080 ** If the requested collation sequence is not available, or not available
   76081 ** in the database native encoding, the collation factory is invoked to
   76082 ** request it. If the collation factory does not supply such a sequence,
   76083 ** and the sequence is available in another text encoding, then that is
   76084 ** returned instead.
   76085 **
   76086 ** If no versions of the requested collations sequence are available, or
   76087 ** another error occurs, NULL is returned and an error message written into
   76088 ** pParse.
   76089 **
   76090 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
   76091 ** invokes the collation factory if the named collation cannot be found
   76092 ** and generates an error message.
   76093 **
   76094 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
   76095 */
   76096 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
   76097   sqlite3 *db = pParse->db;
   76098   u8 enc = ENC(db);
   76099   u8 initbusy = db->init.busy;
   76100   CollSeq *pColl;
   76101 
   76102   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
   76103   if( !initbusy && (!pColl || !pColl->xCmp) ){
   76104     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
   76105     if( !pColl ){
   76106       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   76107     }
   76108   }
   76109 
   76110   return pColl;
   76111 }
   76112 
   76113 
   76114 /*
   76115 ** Generate code that will increment the schema cookie.
   76116 **
   76117 ** The schema cookie is used to determine when the schema for the
   76118 ** database changes.  After each schema change, the cookie value
   76119 ** changes.  When a process first reads the schema it records the
   76120 ** cookie.  Thereafter, whenever it goes to access the database,
   76121 ** it checks the cookie to make sure the schema has not changed
   76122 ** since it was last read.
   76123 **
   76124 ** This plan is not completely bullet-proof.  It is possible for
   76125 ** the schema to change multiple times and for the cookie to be
   76126 ** set back to prior value.  But schema changes are infrequent
   76127 ** and the probability of hitting the same cookie value is only
   76128 ** 1 chance in 2^32.  So we're safe enough.
   76129 */
   76130 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   76131   int r1 = sqlite3GetTempReg(pParse);
   76132   sqlite3 *db = pParse->db;
   76133   Vdbe *v = pParse->pVdbe;
   76134   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
   76135   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
   76136   sqlite3ReleaseTempReg(pParse, r1);
   76137 }
   76138 
   76139 /*
   76140 ** Measure the number of characters needed to output the given
   76141 ** identifier.  The number returned includes any quotes used
   76142 ** but does not include the null terminator.
   76143 **
   76144 ** The estimate is conservative.  It might be larger that what is
   76145 ** really needed.
   76146 */
   76147 static int identLength(const char *z){
   76148   int n;
   76149   for(n=0; *z; n++, z++){
   76150     if( *z=='"' ){ n++; }
   76151   }
   76152   return n + 2;
   76153 }
   76154 
   76155 /*
   76156 ** The first parameter is a pointer to an output buffer. The second
   76157 ** parameter is a pointer to an integer that contains the offset at
   76158 ** which to write into the output buffer. This function copies the
   76159 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
   76160 ** to the specified offset in the buffer and updates *pIdx to refer
   76161 ** to the first byte after the last byte written before returning.
   76162 **
   76163 ** If the string zSignedIdent consists entirely of alpha-numeric
   76164 ** characters, does not begin with a digit and is not an SQL keyword,
   76165 ** then it is copied to the output buffer exactly as it is. Otherwise,
   76166 ** it is quoted using double-quotes.
   76167 */
   76168 static void identPut(char *z, int *pIdx, char *zSignedIdent){
   76169   unsigned char *zIdent = (unsigned char*)zSignedIdent;
   76170   int i, j, needQuote;
   76171   i = *pIdx;
   76172 
   76173   for(j=0; zIdent[j]; j++){
   76174     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
   76175   }
   76176   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
   76177   if( !needQuote ){
   76178     needQuote = zIdent[j];
   76179   }
   76180 
   76181   if( needQuote ) z[i++] = '"';
   76182   for(j=0; zIdent[j]; j++){
   76183     z[i++] = zIdent[j];
   76184     if( zIdent[j]=='"' ) z[i++] = '"';
   76185   }
   76186   if( needQuote ) z[i++] = '"';
   76187   z[i] = 0;
   76188   *pIdx = i;
   76189 }
   76190 
   76191 /*
   76192 ** Generate a CREATE TABLE statement appropriate for the given
   76193 ** table.  Memory to hold the text of the statement is obtained
   76194 ** from sqliteMalloc() and must be freed by the calling function.
   76195 */
   76196 static char *createTableStmt(sqlite3 *db, Table *p){
   76197   int i, k, n;
   76198   char *zStmt;
   76199   char *zSep, *zSep2, *zEnd;
   76200   Column *pCol;
   76201   n = 0;
   76202   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
   76203     n += identLength(pCol->zName) + 5;
   76204   }
   76205   n += identLength(p->zName);
   76206   if( n<50 ){
   76207     zSep = "";
   76208     zSep2 = ",";
   76209     zEnd = ")";
   76210   }else{
   76211     zSep = "\n  ";
   76212     zSep2 = ",\n  ";
   76213     zEnd = "\n)";
   76214   }
   76215   n += 35 + 6*p->nCol;
   76216   zStmt = sqlite3DbMallocRaw(0, n);
   76217   if( zStmt==0 ){
   76218     db->mallocFailed = 1;
   76219     return 0;
   76220   }
   76221   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
   76222   k = sqlite3Strlen30(zStmt);
   76223   identPut(zStmt, &k, p->zName);
   76224   zStmt[k++] = '(';
   76225   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
   76226     static const char * const azType[] = {
   76227         /* SQLITE_AFF_TEXT    */ " TEXT",
   76228         /* SQLITE_AFF_NONE    */ "",
   76229         /* SQLITE_AFF_NUMERIC */ " NUM",
   76230         /* SQLITE_AFF_INTEGER */ " INT",
   76231         /* SQLITE_AFF_REAL    */ " REAL"
   76232     };
   76233     int len;
   76234     const char *zType;
   76235 
   76236     sqlite3_snprintf(n-k, &zStmt[k], zSep);
   76237     k += sqlite3Strlen30(&zStmt[k]);
   76238     zSep = zSep2;
   76239     identPut(zStmt, &k, pCol->zName);
   76240     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
   76241     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
   76242     testcase( pCol->affinity==SQLITE_AFF_TEXT );
   76243     testcase( pCol->affinity==SQLITE_AFF_NONE );
   76244     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
   76245     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
   76246     testcase( pCol->affinity==SQLITE_AFF_REAL );
   76247 
   76248     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
   76249     len = sqlite3Strlen30(zType);
   76250     assert( pCol->affinity==SQLITE_AFF_NONE
   76251             || pCol->affinity==sqlite3AffinityType(zType) );
   76252     memcpy(&zStmt[k], zType, len);
   76253     k += len;
   76254     assert( k<=n );
   76255   }
   76256   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
   76257   return zStmt;
   76258 }
   76259 
   76260 /*
   76261 ** This routine is called to report the final ")" that terminates
   76262 ** a CREATE TABLE statement.
   76263 **
   76264 ** The table structure that other action routines have been building
   76265 ** is added to the internal hash tables, assuming no errors have
   76266 ** occurred.
   76267 **
   76268 ** An entry for the table is made in the master table on disk, unless
   76269 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
   76270 ** it means we are reading the sqlite_master table because we just
   76271 ** connected to the database or because the sqlite_master table has
   76272 ** recently changed, so the entry for this table already exists in
   76273 ** the sqlite_master table.  We do not want to create it again.
   76274 **
   76275 ** If the pSelect argument is not NULL, it means that this routine
   76276 ** was called to create a table generated from a
   76277 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
   76278 ** the new table will match the result set of the SELECT.
   76279 */
   76280 SQLITE_PRIVATE void sqlite3EndTable(
   76281   Parse *pParse,          /* Parse context */
   76282   Token *pCons,           /* The ',' token after the last column defn. */
   76283   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
   76284   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
   76285 ){
   76286   Table *p;
   76287   sqlite3 *db = pParse->db;
   76288   int iDb;
   76289 
   76290   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
   76291     return;
   76292   }
   76293   p = pParse->pNewTable;
   76294   if( p==0 ) return;
   76295 
   76296   assert( !db->init.busy || !pSelect );
   76297 
   76298   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   76299 
   76300 #ifndef SQLITE_OMIT_CHECK
   76301   /* Resolve names in all CHECK constraint expressions.
   76302   */
   76303   if( p->pCheck ){
   76304     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   76305     NameContext sNC;                /* Name context for pParse->pNewTable */
   76306 
   76307     memset(&sNC, 0, sizeof(sNC));
   76308     memset(&sSrc, 0, sizeof(sSrc));
   76309     sSrc.nSrc = 1;
   76310     sSrc.a[0].zName = p->zName;
   76311     sSrc.a[0].pTab = p;
   76312     sSrc.a[0].iCursor = -1;
   76313     sNC.pParse = pParse;
   76314     sNC.pSrcList = &sSrc;
   76315     sNC.isCheck = 1;
   76316     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
   76317       return;
   76318     }
   76319   }
   76320 #endif /* !defined(SQLITE_OMIT_CHECK) */
   76321 
   76322   /* If the db->init.busy is 1 it means we are reading the SQL off the
   76323   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
   76324   ** So do not write to the disk again.  Extract the root page number
   76325   ** for the table from the db->init.newTnum field.  (The page number
   76326   ** should have been put there by the sqliteOpenCb routine.)
   76327   */
   76328   if( db->init.busy ){
   76329     p->tnum = db->init.newTnum;
   76330   }
   76331 
   76332   /* If not initializing, then create a record for the new table
   76333   ** in the SQLITE_MASTER table of the database.
   76334   **
   76335   ** If this is a TEMPORARY table, write the entry into the auxiliary
   76336   ** file instead of into the main database file.
   76337   */
   76338   if( !db->init.busy ){
   76339     int n;
   76340     Vdbe *v;
   76341     char *zType;    /* "view" or "table" */
   76342     char *zType2;   /* "VIEW" or "TABLE" */
   76343     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
   76344 
   76345     v = sqlite3GetVdbe(pParse);
   76346     if( NEVER(v==0) ) return;
   76347 
   76348     sqlite3VdbeAddOp1(v, OP_Close, 0);
   76349 
   76350     /*
   76351     ** Initialize zType for the new view or table.
   76352     */
   76353     if( p->pSelect==0 ){
   76354       /* A regular table */
   76355       zType = "table";
   76356       zType2 = "TABLE";
   76357 #ifndef SQLITE_OMIT_VIEW
   76358     }else{
   76359       /* A view */
   76360       zType = "view";
   76361       zType2 = "VIEW";
   76362 #endif
   76363     }
   76364 
   76365     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
   76366     ** statement to populate the new table. The root-page number for the
   76367     ** new table is in register pParse->regRoot.
   76368     **
   76369     ** Once the SELECT has been coded by sqlite3Select(), it is in a
   76370     ** suitable state to query for the column names and types to be used
   76371     ** by the new table.
   76372     **
   76373     ** A shared-cache write-lock is not required to write to the new table,
   76374     ** as a schema-lock must have already been obtained to create it. Since
   76375     ** a schema-lock excludes all other database users, the write-lock would
   76376     ** be redundant.
   76377     */
   76378     if( pSelect ){
   76379       SelectDest dest;
   76380       Table *pSelTab;
   76381 
   76382       assert(pParse->nTab==1);
   76383       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
   76384       sqlite3VdbeChangeP5(v, 1);
   76385       pParse->nTab = 2;
   76386       sqlite3SelectDestInit(&dest, SRT_Table, 1);
   76387       sqlite3Select(pParse, pSelect, &dest);
   76388       sqlite3VdbeAddOp1(v, OP_Close, 1);
   76389       if( pParse->nErr==0 ){
   76390         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
   76391         if( pSelTab==0 ) return;
   76392         assert( p->aCol==0 );
   76393         p->nCol = pSelTab->nCol;
   76394         p->aCol = pSelTab->aCol;
   76395         pSelTab->nCol = 0;
   76396         pSelTab->aCol = 0;
   76397         sqlite3DeleteTable(db, pSelTab);
   76398       }
   76399     }
   76400 
   76401     /* Compute the complete text of the CREATE statement */
   76402     if( pSelect ){
   76403       zStmt = createTableStmt(db, p);
   76404     }else{
   76405       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
   76406       zStmt = sqlite3MPrintf(db,
   76407           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
   76408       );
   76409     }
   76410 
   76411     /* A slot for the record has already been allocated in the
   76412     ** SQLITE_MASTER table.  We just need to update that slot with all
   76413     ** the information we've collected.
   76414     */
   76415     sqlite3NestedParse(pParse,
   76416       "UPDATE %Q.%s "
   76417          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
   76418        "WHERE rowid=#%d",
   76419       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   76420       zType,
   76421       p->zName,
   76422       p->zName,
   76423       pParse->regRoot,
   76424       zStmt,
   76425       pParse->regRowid
   76426     );
   76427     sqlite3DbFree(db, zStmt);
   76428     sqlite3ChangeCookie(pParse, iDb);
   76429 
   76430 #ifndef SQLITE_OMIT_AUTOINCREMENT
   76431     /* Check to see if we need to create an sqlite_sequence table for
   76432     ** keeping track of autoincrement keys.
   76433     */
   76434     if( p->tabFlags & TF_Autoincrement ){
   76435       Db *pDb = &db->aDb[iDb];
   76436       if( pDb->pSchema->pSeqTab==0 ){
   76437         sqlite3NestedParse(pParse,
   76438           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
   76439           pDb->zName
   76440         );
   76441       }
   76442     }
   76443 #endif
   76444 
   76445     /* Reparse everything to update our internal data structures */
   76446     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
   76447         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
   76448   }
   76449 
   76450 
   76451   /* Add the table to the in-memory representation of the database.
   76452   */
   76453   if( db->init.busy ){
   76454     Table *pOld;
   76455     Schema *pSchema = p->pSchema;
   76456     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
   76457                              sqlite3Strlen30(p->zName),p);
   76458     if( pOld ){
   76459       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
   76460       db->mallocFailed = 1;
   76461       return;
   76462     }
   76463     pParse->pNewTable = 0;
   76464     db->nTable++;
   76465     db->flags |= SQLITE_InternChanges;
   76466 
   76467 #ifndef SQLITE_OMIT_ALTERTABLE
   76468     if( !p->pSelect ){
   76469       const char *zName = (const char *)pParse->sNameToken.z;
   76470       int nName;
   76471       assert( !pSelect && pCons && pEnd );
   76472       if( pCons->z==0 ){
   76473         pCons = pEnd;
   76474       }
   76475       nName = (int)((const char *)pCons->z - zName);
   76476       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
   76477     }
   76478 #endif
   76479   }
   76480 }
   76481 
   76482 #ifndef SQLITE_OMIT_VIEW
   76483 /*
   76484 ** The parser calls this routine in order to create a new VIEW
   76485 */
   76486 SQLITE_PRIVATE void sqlite3CreateView(
   76487   Parse *pParse,     /* The parsing context */
   76488   Token *pBegin,     /* The CREATE token that begins the statement */
   76489   Token *pName1,     /* The token that holds the name of the view */
   76490   Token *pName2,     /* The token that holds the name of the view */
   76491   Select *pSelect,   /* A SELECT statement that will become the new view */
   76492   int isTemp,        /* TRUE for a TEMPORARY view */
   76493   int noErr          /* Suppress error messages if VIEW already exists */
   76494 ){
   76495   Table *p;
   76496   int n;
   76497   const char *z;
   76498   Token sEnd;
   76499   DbFixer sFix;
   76500   Token *pName;
   76501   int iDb;
   76502   sqlite3 *db = pParse->db;
   76503 
   76504   if( pParse->nVar>0 ){
   76505     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
   76506     sqlite3SelectDelete(db, pSelect);
   76507     return;
   76508   }
   76509   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
   76510   p = pParse->pNewTable;
   76511   if( p==0 || pParse->nErr ){
   76512     sqlite3SelectDelete(db, pSelect);
   76513     return;
   76514   }
   76515   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   76516   iDb = sqlite3SchemaToIndex(db, p->pSchema);
   76517   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
   76518     && sqlite3FixSelect(&sFix, pSelect)
   76519   ){
   76520     sqlite3SelectDelete(db, pSelect);
   76521     return;
   76522   }
   76523 
   76524   /* Make a copy of the entire SELECT statement that defines the view.
   76525   ** This will force all the Expr.token.z values to be dynamically
   76526   ** allocated rather than point to the input string - which means that
   76527   ** they will persist after the current sqlite3_exec() call returns.
   76528   */
   76529   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   76530   sqlite3SelectDelete(db, pSelect);
   76531   if( db->mallocFailed ){
   76532     return;
   76533   }
   76534   if( !db->init.busy ){
   76535     sqlite3ViewGetColumnNames(pParse, p);
   76536   }
   76537 
   76538   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
   76539   ** the end.
   76540   */
   76541   sEnd = pParse->sLastToken;
   76542   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
   76543     sEnd.z += sEnd.n;
   76544   }
   76545   sEnd.n = 0;
   76546   n = (int)(sEnd.z - pBegin->z);
   76547   z = pBegin->z;
   76548   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
   76549   sEnd.z = &z[n-1];
   76550   sEnd.n = 1;
   76551 
   76552   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
   76553   sqlite3EndTable(pParse, 0, &sEnd, 0);
   76554   return;
   76555 }
   76556 #endif /* SQLITE_OMIT_VIEW */
   76557 
   76558 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
   76559 /*
   76560 ** The Table structure pTable is really a VIEW.  Fill in the names of
   76561 ** the columns of the view in the pTable structure.  Return the number
   76562 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
   76563 */
   76564 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   76565   Table *pSelTab;   /* A fake table from which we get the result set */
   76566   Select *pSel;     /* Copy of the SELECT that implements the view */
   76567   int nErr = 0;     /* Number of errors encountered */
   76568   int n;            /* Temporarily holds the number of cursors assigned */
   76569   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
   76570   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   76571 
   76572   assert( pTable );
   76573 
   76574 #ifndef SQLITE_OMIT_VIRTUALTABLE
   76575   if( sqlite3VtabCallConnect(pParse, pTable) ){
   76576     return SQLITE_ERROR;
   76577   }
   76578   if( IsVirtual(pTable) ) return 0;
   76579 #endif
   76580 
   76581 #ifndef SQLITE_OMIT_VIEW
   76582   /* A positive nCol means the columns names for this view are
   76583   ** already known.
   76584   */
   76585   if( pTable->nCol>0 ) return 0;
   76586 
   76587   /* A negative nCol is a special marker meaning that we are currently
   76588   ** trying to compute the column names.  If we enter this routine with
   76589   ** a negative nCol, it means two or more views form a loop, like this:
   76590   **
   76591   **     CREATE VIEW one AS SELECT * FROM two;
   76592   **     CREATE VIEW two AS SELECT * FROM one;
   76593   **
   76594   ** Actually, the error above is now caught prior to reaching this point.
   76595   ** But the following test is still important as it does come up
   76596   ** in the following:
   76597   **
   76598   **     CREATE TABLE main.ex1(a);
   76599   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   76600   **     SELECT * FROM temp.ex1;
   76601   */
   76602   if( pTable->nCol<0 ){
   76603     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
   76604     return 1;
   76605   }
   76606   assert( pTable->nCol>=0 );
   76607 
   76608   /* If we get this far, it means we need to compute the table names.
   76609   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
   76610   ** "*" elements in the results set of the view and will assign cursors
   76611   ** to the elements of the FROM clause.  But we do not want these changes
   76612   ** to be permanent.  So the computation is done on a copy of the SELECT
   76613   ** statement that defines the view.
   76614   */
   76615   assert( pTable->pSelect );
   76616   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   76617   if( pSel ){
   76618     u8 enableLookaside = db->lookaside.bEnabled;
   76619     n = pParse->nTab;
   76620     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
   76621     pTable->nCol = -1;
   76622     db->lookaside.bEnabled = 0;
   76623 #ifndef SQLITE_OMIT_AUTHORIZATION
   76624     xAuth = db->xAuth;
   76625     db->xAuth = 0;
   76626     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   76627     db->xAuth = xAuth;
   76628 #else
   76629     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
   76630 #endif
   76631     db->lookaside.bEnabled = enableLookaside;
   76632     pParse->nTab = n;
   76633     if( pSelTab ){
   76634       assert( pTable->aCol==0 );
   76635       pTable->nCol = pSelTab->nCol;
   76636       pTable->aCol = pSelTab->aCol;
   76637       pSelTab->nCol = 0;
   76638       pSelTab->aCol = 0;
   76639       sqlite3DeleteTable(db, pSelTab);
   76640       pTable->pSchema->flags |= DB_UnresetViews;
   76641     }else{
   76642       pTable->nCol = 0;
   76643       nErr++;
   76644     }
   76645     sqlite3SelectDelete(db, pSel);
   76646   } else {
   76647     nErr++;
   76648   }
   76649 #endif /* SQLITE_OMIT_VIEW */
   76650   return nErr;
   76651 }
   76652 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
   76653 
   76654 #ifndef SQLITE_OMIT_VIEW
   76655 /*
   76656 ** Clear the column names from every VIEW in database idx.
   76657 */
   76658 static void sqliteViewResetAll(sqlite3 *db, int idx){
   76659   HashElem *i;
   76660   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
   76661   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
   76662     Table *pTab = sqliteHashData(i);
   76663     if( pTab->pSelect ){
   76664       sqliteDeleteColumnNames(db, pTab);
   76665       pTab->aCol = 0;
   76666       pTab->nCol = 0;
   76667     }
   76668   }
   76669   DbClearProperty(db, idx, DB_UnresetViews);
   76670 }
   76671 #else
   76672 # define sqliteViewResetAll(A,B)
   76673 #endif /* SQLITE_OMIT_VIEW */
   76674 
   76675 /*
   76676 ** This function is called by the VDBE to adjust the internal schema
   76677 ** used by SQLite when the btree layer moves a table root page. The
   76678 ** root-page of a table or index in database iDb has changed from iFrom
   76679 ** to iTo.
   76680 **
   76681 ** Ticket #1728:  The symbol table might still contain information
   76682 ** on tables and/or indices that are the process of being deleted.
   76683 ** If you are unlucky, one of those deleted indices or tables might
   76684 ** have the same rootpage number as the real table or index that is
   76685 ** being moved.  So we cannot stop searching after the first match
   76686 ** because the first match might be for one of the deleted indices
   76687 ** or tables and not the table/index that is actually being moved.
   76688 ** We must continue looping until all tables and indices with
   76689 ** rootpage==iFrom have been converted to have a rootpage of iTo
   76690 ** in order to be certain that we got the right one.
   76691 */
   76692 #ifndef SQLITE_OMIT_AUTOVACUUM
   76693 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
   76694   HashElem *pElem;
   76695   Hash *pHash;
   76696 
   76697   pHash = &pDb->pSchema->tblHash;
   76698   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   76699     Table *pTab = sqliteHashData(pElem);
   76700     if( pTab->tnum==iFrom ){
   76701       pTab->tnum = iTo;
   76702     }
   76703   }
   76704   pHash = &pDb->pSchema->idxHash;
   76705   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
   76706     Index *pIdx = sqliteHashData(pElem);
   76707     if( pIdx->tnum==iFrom ){
   76708       pIdx->tnum = iTo;
   76709     }
   76710   }
   76711 }
   76712 #endif
   76713 
   76714 /*
   76715 ** Write code to erase the table with root-page iTable from database iDb.
   76716 ** Also write code to modify the sqlite_master table and internal schema
   76717 ** if a root-page of another table is moved by the btree-layer whilst
   76718 ** erasing iTable (this can happen with an auto-vacuum database).
   76719 */
   76720 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   76721   Vdbe *v = sqlite3GetVdbe(pParse);
   76722   int r1 = sqlite3GetTempReg(pParse);
   76723   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
   76724   sqlite3MayAbort(pParse);
   76725 #ifndef SQLITE_OMIT_AUTOVACUUM
   76726   /* OP_Destroy stores an in integer r1. If this integer
   76727   ** is non-zero, then it is the root page number of a table moved to
   76728   ** location iTable. The following code modifies the sqlite_master table to
   76729   ** reflect this.
   76730   **
   76731   ** The "#NNN" in the SQL is a special constant that means whatever value
   76732   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   76733   ** token for additional information.
   76734   */
   76735   sqlite3NestedParse(pParse,
   76736      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
   76737      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
   76738 #endif
   76739   sqlite3ReleaseTempReg(pParse, r1);
   76740 }
   76741 
   76742 /*
   76743 ** Write VDBE code to erase table pTab and all associated indices on disk.
   76744 ** Code to update the sqlite_master tables and internal schema definitions
   76745 ** in case a root-page belonging to another table is moved by the btree layer
   76746 ** is also added (this can happen with an auto-vacuum database).
   76747 */
   76748 static void destroyTable(Parse *pParse, Table *pTab){
   76749 #ifdef SQLITE_OMIT_AUTOVACUUM
   76750   Index *pIdx;
   76751   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   76752   destroyRootPage(pParse, pTab->tnum, iDb);
   76753   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   76754     destroyRootPage(pParse, pIdx->tnum, iDb);
   76755   }
   76756 #else
   76757   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   76758   ** is not defined), then it is important to call OP_Destroy on the
   76759   ** table and index root-pages in order, starting with the numerically
   76760   ** largest root-page number. This guarantees that none of the root-pages
   76761   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   76762   ** following were coded:
   76763   **
   76764   ** OP_Destroy 4 0
   76765   ** ...
   76766   ** OP_Destroy 5 0
   76767   **
   76768   ** and root page 5 happened to be the largest root-page number in the
   76769   ** database, then root page 5 would be moved to page 4 by the
   76770   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   76771   ** a free-list page.
   76772   */
   76773   int iTab = pTab->tnum;
   76774   int iDestroyed = 0;
   76775 
   76776   while( 1 ){
   76777     Index *pIdx;
   76778     int iLargest = 0;
   76779 
   76780     if( iDestroyed==0 || iTab<iDestroyed ){
   76781       iLargest = iTab;
   76782     }
   76783     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   76784       int iIdx = pIdx->tnum;
   76785       assert( pIdx->pSchema==pTab->pSchema );
   76786       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
   76787         iLargest = iIdx;
   76788       }
   76789     }
   76790     if( iLargest==0 ){
   76791       return;
   76792     }else{
   76793       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   76794       destroyRootPage(pParse, iLargest, iDb);
   76795       iDestroyed = iLargest;
   76796     }
   76797   }
   76798 #endif
   76799 }
   76800 
   76801 /*
   76802 ** This routine is called to do the work of a DROP TABLE statement.
   76803 ** pName is the name of the table to be dropped.
   76804 */
   76805 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
   76806   Table *pTab;
   76807   Vdbe *v;
   76808   sqlite3 *db = pParse->db;
   76809   int iDb;
   76810 
   76811   if( db->mallocFailed ){
   76812     goto exit_drop_table;
   76813   }
   76814   assert( pParse->nErr==0 );
   76815   assert( pName->nSrc==1 );
   76816   if( noErr ) db->suppressErr++;
   76817   pTab = sqlite3LocateTable(pParse, isView,
   76818                             pName->a[0].zName, pName->a[0].zDatabase);
   76819   if( noErr ) db->suppressErr--;
   76820 
   76821   if( pTab==0 ){
   76822     goto exit_drop_table;
   76823   }
   76824   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   76825   assert( iDb>=0 && iDb<db->nDb );
   76826 
   76827   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
   76828   ** it is initialized.
   76829   */
   76830   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
   76831     goto exit_drop_table;
   76832   }
   76833 #ifndef SQLITE_OMIT_AUTHORIZATION
   76834   {
   76835     int code;
   76836     const char *zTab = SCHEMA_TABLE(iDb);
   76837     const char *zDb = db->aDb[iDb].zName;
   76838     const char *zArg2 = 0;
   76839     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
   76840       goto exit_drop_table;
   76841     }
   76842     if( isView ){
   76843       if( !OMIT_TEMPDB && iDb==1 ){
   76844         code = SQLITE_DROP_TEMP_VIEW;
   76845       }else{
   76846         code = SQLITE_DROP_VIEW;
   76847       }
   76848 #ifndef SQLITE_OMIT_VIRTUALTABLE
   76849     }else if( IsVirtual(pTab) ){
   76850       code = SQLITE_DROP_VTABLE;
   76851       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
   76852 #endif
   76853     }else{
   76854       if( !OMIT_TEMPDB && iDb==1 ){
   76855         code = SQLITE_DROP_TEMP_TABLE;
   76856       }else{
   76857         code = SQLITE_DROP_TABLE;
   76858       }
   76859     }
   76860     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
   76861       goto exit_drop_table;
   76862     }
   76863     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
   76864       goto exit_drop_table;
   76865     }
   76866   }
   76867 #endif
   76868   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   76869     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
   76870     goto exit_drop_table;
   76871   }
   76872 
   76873 #ifndef SQLITE_OMIT_VIEW
   76874   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
   76875   ** on a table.
   76876   */
   76877   if( isView && pTab->pSelect==0 ){
   76878     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
   76879     goto exit_drop_table;
   76880   }
   76881   if( !isView && pTab->pSelect ){
   76882     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
   76883     goto exit_drop_table;
   76884   }
   76885 #endif
   76886 
   76887   /* Generate code to remove the table from the master table
   76888   ** on disk.
   76889   */
   76890   v = sqlite3GetVdbe(pParse);
   76891   if( v ){
   76892     Trigger *pTrigger;
   76893     Db *pDb = &db->aDb[iDb];
   76894     sqlite3BeginWriteOperation(pParse, 1, iDb);
   76895 
   76896 #ifndef SQLITE_OMIT_VIRTUALTABLE
   76897     if( IsVirtual(pTab) ){
   76898       sqlite3VdbeAddOp0(v, OP_VBegin);
   76899     }
   76900 #endif
   76901     sqlite3FkDropTable(pParse, pName, pTab);
   76902 
   76903     /* Drop all triggers associated with the table being dropped. Code
   76904     ** is generated to remove entries from sqlite_master and/or
   76905     ** sqlite_temp_master if required.
   76906     */
   76907     pTrigger = sqlite3TriggerList(pParse, pTab);
   76908     while( pTrigger ){
   76909       assert( pTrigger->pSchema==pTab->pSchema ||
   76910           pTrigger->pSchema==db->aDb[1].pSchema );
   76911       sqlite3DropTriggerPtr(pParse, pTrigger);
   76912       pTrigger = pTrigger->pNext;
   76913     }
   76914 
   76915 #ifndef SQLITE_OMIT_AUTOINCREMENT
   76916     /* Remove any entries of the sqlite_sequence table associated with
   76917     ** the table being dropped. This is done before the table is dropped
   76918     ** at the btree level, in case the sqlite_sequence table needs to
   76919     ** move as a result of the drop (can happen in auto-vacuum mode).
   76920     */
   76921     if( pTab->tabFlags & TF_Autoincrement ){
   76922       sqlite3NestedParse(pParse,
   76923         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
   76924         pDb->zName, pTab->zName
   76925       );
   76926     }
   76927 #endif
   76928 
   76929     /* Drop all SQLITE_MASTER table and index entries that refer to the
   76930     ** table. The program name loops through the master table and deletes
   76931     ** every row that refers to a table of the same name as the one being
   76932     ** dropped. Triggers are handled seperately because a trigger can be
   76933     ** created in the temp database that refers to a table in another
   76934     ** database.
   76935     */
   76936     sqlite3NestedParse(pParse,
   76937         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
   76938         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
   76939 
   76940     /* Drop any statistics from the sqlite_stat1 table, if it exists */
   76941     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
   76942       sqlite3NestedParse(pParse,
   76943         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
   76944       );
   76945     }
   76946 
   76947     if( !isView && !IsVirtual(pTab) ){
   76948       destroyTable(pParse, pTab);
   76949     }
   76950 
   76951     /* Remove the table entry from SQLite's internal schema and modify
   76952     ** the schema cookie.
   76953     */
   76954     if( IsVirtual(pTab) ){
   76955       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
   76956     }
   76957     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
   76958     sqlite3ChangeCookie(pParse, iDb);
   76959   }
   76960   sqliteViewResetAll(db, iDb);
   76961 
   76962 exit_drop_table:
   76963   sqlite3SrcListDelete(db, pName);
   76964 }
   76965 
   76966 /*
   76967 ** This routine is called to create a new foreign key on the table
   76968 ** currently under construction.  pFromCol determines which columns
   76969 ** in the current table point to the foreign key.  If pFromCol==0 then
   76970 ** connect the key to the last column inserted.  pTo is the name of
   76971 ** the table referred to.  pToCol is a list of tables in the other
   76972 ** pTo table that the foreign key points to.  flags contains all
   76973 ** information about the conflict resolution algorithms specified
   76974 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
   76975 **
   76976 ** An FKey structure is created and added to the table currently
   76977 ** under construction in the pParse->pNewTable field.
   76978 **
   76979 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
   76980 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
   76981 */
   76982 SQLITE_PRIVATE void sqlite3CreateForeignKey(
   76983   Parse *pParse,       /* Parsing context */
   76984   ExprList *pFromCol,  /* Columns in this table that point to other table */
   76985   Token *pTo,          /* Name of the other table */
   76986   ExprList *pToCol,    /* Columns in the other table */
   76987   int flags            /* Conflict resolution algorithms. */
   76988 ){
   76989   sqlite3 *db = pParse->db;
   76990 #ifndef SQLITE_OMIT_FOREIGN_KEY
   76991   FKey *pFKey = 0;
   76992   FKey *pNextTo;
   76993   Table *p = pParse->pNewTable;
   76994   int nByte;
   76995   int i;
   76996   int nCol;
   76997   char *z;
   76998 
   76999   assert( pTo!=0 );
   77000   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
   77001   if( pFromCol==0 ){
   77002     int iCol = p->nCol-1;
   77003     if( NEVER(iCol<0) ) goto fk_end;
   77004     if( pToCol && pToCol->nExpr!=1 ){
   77005       sqlite3ErrorMsg(pParse, "foreign key on %s"
   77006          " should reference only one column of table %T",
   77007          p->aCol[iCol].zName, pTo);
   77008       goto fk_end;
   77009     }
   77010     nCol = 1;
   77011   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
   77012     sqlite3ErrorMsg(pParse,
   77013         "number of columns in foreign key does not match the number of "
   77014         "columns in the referenced table");
   77015     goto fk_end;
   77016   }else{
   77017     nCol = pFromCol->nExpr;
   77018   }
   77019   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   77020   if( pToCol ){
   77021     for(i=0; i<pToCol->nExpr; i++){
   77022       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
   77023     }
   77024   }
   77025   pFKey = sqlite3DbMallocZero(db, nByte );
   77026   if( pFKey==0 ){
   77027     goto fk_end;
   77028   }
   77029   pFKey->pFrom = p;
   77030   pFKey->pNextFrom = p->pFKey;
   77031   z = (char*)&pFKey->aCol[nCol];
   77032   pFKey->zTo = z;
   77033   memcpy(z, pTo->z, pTo->n);
   77034   z[pTo->n] = 0;
   77035   sqlite3Dequote(z);
   77036   z += pTo->n+1;
   77037   pFKey->nCol = nCol;
   77038   if( pFromCol==0 ){
   77039     pFKey->aCol[0].iFrom = p->nCol-1;
   77040   }else{
   77041     for(i=0; i<nCol; i++){
   77042       int j;
   77043       for(j=0; j<p->nCol; j++){
   77044         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
   77045           pFKey->aCol[i].iFrom = j;
   77046           break;
   77047         }
   77048       }
   77049       if( j>=p->nCol ){
   77050         sqlite3ErrorMsg(pParse,
   77051           "unknown column \"%s\" in foreign key definition",
   77052           pFromCol->a[i].zName);
   77053         goto fk_end;
   77054       }
   77055     }
   77056   }
   77057   if( pToCol ){
   77058     for(i=0; i<nCol; i++){
   77059       int n = sqlite3Strlen30(pToCol->a[i].zName);
   77060       pFKey->aCol[i].zCol = z;
   77061       memcpy(z, pToCol->a[i].zName, n);
   77062       z[n] = 0;
   77063       z += n+1;
   77064     }
   77065   }
   77066   pFKey->isDeferred = 0;
   77067   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
   77068   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
   77069 
   77070   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
   77071       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
   77072   );
   77073   if( pNextTo==pFKey ){
   77074     db->mallocFailed = 1;
   77075     goto fk_end;
   77076   }
   77077   if( pNextTo ){
   77078     assert( pNextTo->pPrevTo==0 );
   77079     pFKey->pNextTo = pNextTo;
   77080     pNextTo->pPrevTo = pFKey;
   77081   }
   77082 
   77083   /* Link the foreign key to the table as the last step.
   77084   */
   77085   p->pFKey = pFKey;
   77086   pFKey = 0;
   77087 
   77088 fk_end:
   77089   sqlite3DbFree(db, pFKey);
   77090 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   77091   sqlite3ExprListDelete(db, pFromCol);
   77092   sqlite3ExprListDelete(db, pToCol);
   77093 }
   77094 
   77095 /*
   77096 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
   77097 ** clause is seen as part of a foreign key definition.  The isDeferred
   77098 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
   77099 ** The behavior of the most recently created foreign key is adjusted
   77100 ** accordingly.
   77101 */
   77102 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
   77103 #ifndef SQLITE_OMIT_FOREIGN_KEY
   77104   Table *pTab;
   77105   FKey *pFKey;
   77106   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
   77107   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
   77108   pFKey->isDeferred = (u8)isDeferred;
   77109 #endif
   77110 }
   77111 
   77112 /*
   77113 ** Generate code that will erase and refill index *pIdx.  This is
   77114 ** used to initialize a newly created index or to recompute the
   77115 ** content of an index in response to a REINDEX command.
   77116 **
   77117 ** if memRootPage is not negative, it means that the index is newly
   77118 ** created.  The register specified by memRootPage contains the
   77119 ** root page number of the index.  If memRootPage is negative, then
   77120 ** the index already exists and must be cleared before being refilled and
   77121 ** the root page number of the index is taken from pIndex->tnum.
   77122 */
   77123 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   77124   Table *pTab = pIndex->pTable;  /* The table that is indexed */
   77125   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
   77126   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
   77127   int addr1;                     /* Address of top of loop */
   77128   int tnum;                      /* Root page of index */
   77129   Vdbe *v;                       /* Generate code into this virtual machine */
   77130   KeyInfo *pKey;                 /* KeyInfo for index */
   77131   int regIdxKey;                 /* Registers containing the index key */
   77132   int regRecord;                 /* Register holding assemblied index record */
   77133   sqlite3 *db = pParse->db;      /* The database connection */
   77134   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   77135 
   77136 #ifndef SQLITE_OMIT_AUTHORIZATION
   77137   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
   77138       db->aDb[iDb].zName ) ){
   77139     return;
   77140   }
   77141 #endif
   77142 
   77143   /* Require a write-lock on the table to perform this operation */
   77144   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
   77145 
   77146   v = sqlite3GetVdbe(pParse);
   77147   if( v==0 ) return;
   77148   if( memRootPage>=0 ){
   77149     tnum = memRootPage;
   77150   }else{
   77151     tnum = pIndex->tnum;
   77152     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
   77153   }
   77154   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
   77155   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
   77156                     (char *)pKey, P4_KEYINFO_HANDOFF);
   77157   if( memRootPage>=0 ){
   77158     sqlite3VdbeChangeP5(v, 1);
   77159   }
   77160   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
   77161   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   77162   regRecord = sqlite3GetTempReg(pParse);
   77163   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
   77164   if( pIndex->onError!=OE_None ){
   77165     const int regRowid = regIdxKey + pIndex->nColumn;
   77166     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
   77167     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
   77168 
   77169     /* The registers accessed by the OP_IsUnique opcode were allocated
   77170     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
   77171     ** call above. Just before that function was freed they were released
   77172     ** (made available to the compiler for reuse) using
   77173     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
   77174     ** opcode use the values stored within seems dangerous. However, since
   77175     ** we can be sure that no other temp registers have been allocated
   77176     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
   77177     */
   77178     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
   77179     sqlite3HaltConstraint(
   77180         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
   77181   }
   77182   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
   77183   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   77184   sqlite3ReleaseTempReg(pParse, regRecord);
   77185   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
   77186   sqlite3VdbeJumpHere(v, addr1);
   77187   sqlite3VdbeAddOp1(v, OP_Close, iTab);
   77188   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
   77189 }
   77190 
   77191 /*
   77192 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
   77193 ** and pTblList is the name of the table that is to be indexed.  Both will
   77194 ** be NULL for a primary key or an index that is created to satisfy a
   77195 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
   77196 ** as the table to be indexed.  pParse->pNewTable is a table that is
   77197 ** currently being constructed by a CREATE TABLE statement.
   77198 **
   77199 ** pList is a list of columns to be indexed.  pList will be NULL if this
   77200 ** is a primary key or unique-constraint on the most recent column added
   77201 ** to the table currently under construction.
   77202 **
   77203 ** If the index is created successfully, return a pointer to the new Index
   77204 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
   77205 ** as the tables primary key (Index.autoIndex==2).
   77206 */
   77207 SQLITE_PRIVATE Index *sqlite3CreateIndex(
   77208   Parse *pParse,     /* All information about this parse */
   77209   Token *pName1,     /* First part of index name. May be NULL */
   77210   Token *pName2,     /* Second part of index name. May be NULL */
   77211   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
   77212   ExprList *pList,   /* A list of columns to be indexed */
   77213   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
   77214   Token *pStart,     /* The CREATE token that begins this statement */
   77215   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
   77216   int sortOrder,     /* Sort order of primary key when pList==NULL */
   77217   int ifNotExist     /* Omit error if index already exists */
   77218 ){
   77219   Index *pRet = 0;     /* Pointer to return */
   77220   Table *pTab = 0;     /* Table to be indexed */
   77221   Index *pIndex = 0;   /* The index to be created */
   77222   char *zName = 0;     /* Name of the index */
   77223   int nName;           /* Number of characters in zName */
   77224   int i, j;
   77225   Token nullId;        /* Fake token for an empty ID list */
   77226   DbFixer sFix;        /* For assigning database names to pTable */
   77227   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
   77228   sqlite3 *db = pParse->db;
   77229   Db *pDb;             /* The specific table containing the indexed database */
   77230   int iDb;             /* Index of the database that is being written */
   77231   Token *pName = 0;    /* Unqualified name of the index to create */
   77232   struct ExprList_item *pListItem; /* For looping over pList */
   77233   int nCol;
   77234   int nExtra = 0;
   77235   char *zExtra;
   77236 
   77237   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
   77238   assert( pParse->nErr==0 );      /* Never called with prior errors */
   77239   if( db->mallocFailed || IN_DECLARE_VTAB ){
   77240     goto exit_create_index;
   77241   }
   77242   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   77243     goto exit_create_index;
   77244   }
   77245 
   77246   /*
   77247   ** Find the table that is to be indexed.  Return early if not found.
   77248   */
   77249   if( pTblName!=0 ){
   77250 
   77251     /* Use the two-part index name to determine the database
   77252     ** to search for the table. 'Fix' the table name to this db
   77253     ** before looking up the table.
   77254     */
   77255     assert( pName1 && pName2 );
   77256     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   77257     if( iDb<0 ) goto exit_create_index;
   77258 
   77259 #ifndef SQLITE_OMIT_TEMPDB
   77260     /* If the index name was unqualified, check if the the table
   77261     ** is a temp table. If so, set the database to 1. Do not do this
   77262     ** if initialising a database schema.
   77263     */
   77264     if( !db->init.busy ){
   77265       pTab = sqlite3SrcListLookup(pParse, pTblName);
   77266       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
   77267         iDb = 1;
   77268       }
   77269     }
   77270 #endif
   77271 
   77272     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
   77273         sqlite3FixSrcList(&sFix, pTblName)
   77274     ){
   77275       /* Because the parser constructs pTblName from a single identifier,
   77276       ** sqlite3FixSrcList can never fail. */
   77277       assert(0);
   77278     }
   77279     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
   77280         pTblName->a[0].zDatabase);
   77281     if( !pTab || db->mallocFailed ) goto exit_create_index;
   77282     assert( db->aDb[iDb].pSchema==pTab->pSchema );
   77283   }else{
   77284     assert( pName==0 );
   77285     pTab = pParse->pNewTable;
   77286     if( !pTab ) goto exit_create_index;
   77287     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   77288   }
   77289   pDb = &db->aDb[iDb];
   77290 
   77291   assert( pTab!=0 );
   77292   assert( pParse->nErr==0 );
   77293   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
   77294        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
   77295     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
   77296     goto exit_create_index;
   77297   }
   77298 #ifndef SQLITE_OMIT_VIEW
   77299   if( pTab->pSelect ){
   77300     sqlite3ErrorMsg(pParse, "views may not be indexed");
   77301     goto exit_create_index;
   77302   }
   77303 #endif
   77304 #ifndef SQLITE_OMIT_VIRTUALTABLE
   77305   if( IsVirtual(pTab) ){
   77306     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
   77307     goto exit_create_index;
   77308   }
   77309 #endif
   77310 
   77311   /*
   77312   ** Find the name of the index.  Make sure there is not already another
   77313   ** index or table with the same name.
   77314   **
   77315   ** Exception:  If we are reading the names of permanent indices from the
   77316   ** sqlite_master table (because some other process changed the schema) and
   77317   ** one of the index names collides with the name of a temporary table or
   77318   ** index, then we will continue to process this index.
   77319   **
   77320   ** If pName==0 it means that we are
   77321   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
   77322   ** own name.
   77323   */
   77324   if( pName ){
   77325     zName = sqlite3NameFromToken(db, pName);
   77326     if( zName==0 ) goto exit_create_index;
   77327     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   77328       goto exit_create_index;
   77329     }
   77330     if( !db->init.busy ){
   77331       if( sqlite3FindTable(db, zName, 0)!=0 ){
   77332         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
   77333         goto exit_create_index;
   77334       }
   77335     }
   77336     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
   77337       if( !ifNotExist ){
   77338         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
   77339       }
   77340       goto exit_create_index;
   77341     }
   77342   }else{
   77343     int n;
   77344     Index *pLoop;
   77345     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
   77346     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
   77347     if( zName==0 ){
   77348       goto exit_create_index;
   77349     }
   77350   }
   77351 
   77352   /* Check for authorization to create an index.
   77353   */
   77354 #ifndef SQLITE_OMIT_AUTHORIZATION
   77355   {
   77356     const char *zDb = pDb->zName;
   77357     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
   77358       goto exit_create_index;
   77359     }
   77360     i = SQLITE_CREATE_INDEX;
   77361     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
   77362     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
   77363       goto exit_create_index;
   77364     }
   77365   }
   77366 #endif
   77367 
   77368   /* If pList==0, it means this routine was called to make a primary
   77369   ** key out of the last column added to the table under construction.
   77370   ** So create a fake list to simulate this.
   77371   */
   77372   if( pList==0 ){
   77373     nullId.z = pTab->aCol[pTab->nCol-1].zName;
   77374     nullId.n = sqlite3Strlen30((char*)nullId.z);
   77375     pList = sqlite3ExprListAppend(pParse, 0, 0);
   77376     if( pList==0 ) goto exit_create_index;
   77377     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
   77378     pList->a[0].sortOrder = (u8)sortOrder;
   77379   }
   77380 
   77381   /* Figure out how many bytes of space are required to store explicitly
   77382   ** specified collation sequence names.
   77383   */
   77384   for(i=0; i<pList->nExpr; i++){
   77385     Expr *pExpr = pList->a[i].pExpr;
   77386     if( pExpr ){
   77387       CollSeq *pColl = pExpr->pColl;
   77388       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
   77389       ** failure we have quit before reaching this point. */
   77390       if( ALWAYS(pColl) ){
   77391         nExtra += (1 + sqlite3Strlen30(pColl->zName));
   77392       }
   77393     }
   77394   }
   77395 
   77396   /*
   77397   ** Allocate the index structure.
   77398   */
   77399   nName = sqlite3Strlen30(zName);
   77400   nCol = pList->nExpr;
   77401   pIndex = sqlite3DbMallocZero(db,
   77402       sizeof(Index) +              /* Index structure  */
   77403       sizeof(int)*nCol +           /* Index.aiColumn   */
   77404       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
   77405       sizeof(char *)*nCol +        /* Index.azColl     */
   77406       sizeof(u8)*nCol +            /* Index.aSortOrder */
   77407       nName + 1 +                  /* Index.zName      */
   77408       nExtra                       /* Collation sequence names */
   77409   );
   77410   if( db->mallocFailed ){
   77411     goto exit_create_index;
   77412   }
   77413   pIndex->azColl = (char**)(&pIndex[1]);
   77414   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
   77415   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
   77416   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
   77417   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
   77418   zExtra = (char *)(&pIndex->zName[nName+1]);
   77419   memcpy(pIndex->zName, zName, nName+1);
   77420   pIndex->pTable = pTab;
   77421   pIndex->nColumn = pList->nExpr;
   77422   pIndex->onError = (u8)onError;
   77423   pIndex->autoIndex = (u8)(pName==0);
   77424   pIndex->pSchema = db->aDb[iDb].pSchema;
   77425 
   77426   /* Check to see if we should honor DESC requests on index columns
   77427   */
   77428   if( pDb->pSchema->file_format>=4 ){
   77429     sortOrderMask = -1;   /* Honor DESC */
   77430   }else{
   77431     sortOrderMask = 0;    /* Ignore DESC */
   77432   }
   77433 
   77434   /* Scan the names of the columns of the table to be indexed and
   77435   ** load the column indices into the Index structure.  Report an error
   77436   ** if any column is not found.
   77437   **
   77438   ** TODO:  Add a test to make sure that the same column is not named
   77439   ** more than once within the same index.  Only the first instance of
   77440   ** the column will ever be used by the optimizer.  Note that using the
   77441   ** same column more than once cannot be an error because that would
   77442   ** break backwards compatibility - it needs to be a warning.
   77443   */
   77444   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
   77445     const char *zColName = pListItem->zName;
   77446     Column *pTabCol;
   77447     int requestedSortOrder;
   77448     char *zColl;                   /* Collation sequence name */
   77449 
   77450     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
   77451       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
   77452     }
   77453     if( j>=pTab->nCol ){
   77454       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
   77455         pTab->zName, zColName);
   77456       pParse->checkSchema = 1;
   77457       goto exit_create_index;
   77458     }
   77459     pIndex->aiColumn[i] = j;
   77460     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
   77461     ** the way the "idxlist" non-terminal is constructed by the parser,
   77462     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
   77463     ** must exist or else there must have been an OOM error.  But if there
   77464     ** was an OOM error, we would never reach this point. */
   77465     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
   77466       int nColl;
   77467       zColl = pListItem->pExpr->pColl->zName;
   77468       nColl = sqlite3Strlen30(zColl) + 1;
   77469       assert( nExtra>=nColl );
   77470       memcpy(zExtra, zColl, nColl);
   77471       zColl = zExtra;
   77472       zExtra += nColl;
   77473       nExtra -= nColl;
   77474     }else{
   77475       zColl = pTab->aCol[j].zColl;
   77476       if( !zColl ){
   77477         zColl = db->pDfltColl->zName;
   77478       }
   77479     }
   77480     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
   77481       goto exit_create_index;
   77482     }
   77483     pIndex->azColl[i] = zColl;
   77484     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
   77485     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
   77486   }
   77487   sqlite3DefaultRowEst(pIndex);
   77488 
   77489   if( pTab==pParse->pNewTable ){
   77490     /* This routine has been called to create an automatic index as a
   77491     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
   77492     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
   77493     ** i.e. one of:
   77494     **
   77495     ** CREATE TABLE t(x PRIMARY KEY, y);
   77496     ** CREATE TABLE t(x, y, UNIQUE(x, y));
   77497     **
   77498     ** Either way, check to see if the table already has such an index. If
   77499     ** so, don't bother creating this one. This only applies to
   77500     ** automatically created indices. Users can do as they wish with
   77501     ** explicit indices.
   77502     **
   77503     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
   77504     ** (and thus suppressing the second one) even if they have different
   77505     ** sort orders.
   77506     **
   77507     ** If there are different collating sequences or if the columns of
   77508     ** the constraint occur in different orders, then the constraints are
   77509     ** considered distinct and both result in separate indices.
   77510     */
   77511     Index *pIdx;
   77512     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   77513       int k;
   77514       assert( pIdx->onError!=OE_None );
   77515       assert( pIdx->autoIndex );
   77516       assert( pIndex->onError!=OE_None );
   77517 
   77518       if( pIdx->nColumn!=pIndex->nColumn ) continue;
   77519       for(k=0; k<pIdx->nColumn; k++){
   77520         const char *z1;
   77521         const char *z2;
   77522         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
   77523         z1 = pIdx->azColl[k];
   77524         z2 = pIndex->azColl[k];
   77525         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
   77526       }
   77527       if( k==pIdx->nColumn ){
   77528         if( pIdx->onError!=pIndex->onError ){
   77529           /* This constraint creates the same index as a previous
   77530           ** constraint specified somewhere in the CREATE TABLE statement.
   77531           ** However the ON CONFLICT clauses are different. If both this
   77532           ** constraint and the previous equivalent constraint have explicit
   77533           ** ON CONFLICT clauses this is an error. Otherwise, use the
   77534           ** explicitly specified behaviour for the index.
   77535           */
   77536           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
   77537             sqlite3ErrorMsg(pParse,
   77538                 "conflicting ON CONFLICT clauses specified", 0);
   77539           }
   77540           if( pIdx->onError==OE_Default ){
   77541             pIdx->onError = pIndex->onError;
   77542           }
   77543         }
   77544         goto exit_create_index;
   77545       }
   77546     }
   77547   }
   77548 
   77549   /* Link the new Index structure to its table and to the other
   77550   ** in-memory database structures.
   77551   */
   77552   if( db->init.busy ){
   77553     Index *p;
   77554     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
   77555                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
   77556                           pIndex);
   77557     if( p ){
   77558       assert( p==pIndex );  /* Malloc must have failed */
   77559       db->mallocFailed = 1;
   77560       goto exit_create_index;
   77561     }
   77562     db->flags |= SQLITE_InternChanges;
   77563     if( pTblName!=0 ){
   77564       pIndex->tnum = db->init.newTnum;
   77565     }
   77566   }
   77567 
   77568   /* If the db->init.busy is 0 then create the index on disk.  This
   77569   ** involves writing the index into the master table and filling in the
   77570   ** index with the current table contents.
   77571   **
   77572   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
   77573   ** command.  db->init.busy is 1 when a database is opened and
   77574   ** CREATE INDEX statements are read out of the master table.  In
   77575   ** the latter case the index already exists on disk, which is why
   77576   ** we don't want to recreate it.
   77577   **
   77578   ** If pTblName==0 it means this index is generated as a primary key
   77579   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
   77580   ** has just been created, it contains no data and the index initialization
   77581   ** step can be skipped.
   77582   */
   77583   else{ /* if( db->init.busy==0 ) */
   77584     Vdbe *v;
   77585     char *zStmt;
   77586     int iMem = ++pParse->nMem;
   77587 
   77588     v = sqlite3GetVdbe(pParse);
   77589     if( v==0 ) goto exit_create_index;
   77590 
   77591 
   77592     /* Create the rootpage for the index
   77593     */
   77594     sqlite3BeginWriteOperation(pParse, 1, iDb);
   77595     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
   77596 
   77597     /* Gather the complete text of the CREATE INDEX statement into
   77598     ** the zStmt variable
   77599     */
   77600     if( pStart ){
   77601       assert( pEnd!=0 );
   77602       /* A named index with an explicit CREATE INDEX statement */
   77603       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
   77604         onError==OE_None ? "" : " UNIQUE",
   77605         pEnd->z - pName->z + 1,
   77606         pName->z);
   77607     }else{
   77608       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
   77609       /* zStmt = sqlite3MPrintf(""); */
   77610       zStmt = 0;
   77611     }
   77612 
   77613     /* Add an entry in sqlite_master for this index
   77614     */
   77615     sqlite3NestedParse(pParse,
   77616         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
   77617         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   77618         pIndex->zName,
   77619         pTab->zName,
   77620         iMem,
   77621         zStmt
   77622     );
   77623     sqlite3DbFree(db, zStmt);
   77624 
   77625     /* Fill the index with data and reparse the schema. Code an OP_Expire
   77626     ** to invalidate all pre-compiled statements.
   77627     */
   77628     if( pTblName ){
   77629       sqlite3RefillIndex(pParse, pIndex, iMem);
   77630       sqlite3ChangeCookie(pParse, iDb);
   77631       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
   77632          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
   77633          P4_DYNAMIC);
   77634       sqlite3VdbeAddOp1(v, OP_Expire, 0);
   77635     }
   77636   }
   77637 
   77638   /* When adding an index to the list of indices for a table, make
   77639   ** sure all indices labeled OE_Replace come after all those labeled
   77640   ** OE_Ignore.  This is necessary for the correct constraint check
   77641   ** processing (in sqlite3GenerateConstraintChecks()) as part of
   77642   ** UPDATE and INSERT statements.
   77643   */
   77644   if( db->init.busy || pTblName==0 ){
   77645     if( onError!=OE_Replace || pTab->pIndex==0
   77646          || pTab->pIndex->onError==OE_Replace){
   77647       pIndex->pNext = pTab->pIndex;
   77648       pTab->pIndex = pIndex;
   77649     }else{
   77650       Index *pOther = pTab->pIndex;
   77651       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
   77652         pOther = pOther->pNext;
   77653       }
   77654       pIndex->pNext = pOther->pNext;
   77655       pOther->pNext = pIndex;
   77656     }
   77657     pRet = pIndex;
   77658     pIndex = 0;
   77659   }
   77660 
   77661   /* Clean up before exiting */
   77662 exit_create_index:
   77663   if( pIndex ){
   77664     sqlite3DbFree(db, pIndex->zColAff);
   77665     sqlite3DbFree(db, pIndex);
   77666   }
   77667   sqlite3ExprListDelete(db, pList);
   77668   sqlite3SrcListDelete(db, pTblName);
   77669   sqlite3DbFree(db, zName);
   77670   return pRet;
   77671 }
   77672 
   77673 /*
   77674 ** Fill the Index.aiRowEst[] array with default information - information
   77675 ** to be used when we have not run the ANALYZE command.
   77676 **
   77677 ** aiRowEst[0] is suppose to contain the number of elements in the index.
   77678 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
   77679 ** number of rows in the table that match any particular value of the
   77680 ** first column of the index.  aiRowEst[2] is an estimate of the number
   77681 ** of rows that match any particular combiniation of the first 2 columns
   77682 ** of the index.  And so forth.  It must always be the case that
   77683 *
   77684 **           aiRowEst[N]<=aiRowEst[N-1]
   77685 **           aiRowEst[N]>=1
   77686 **
   77687 ** Apart from that, we have little to go on besides intuition as to
   77688 ** how aiRowEst[] should be initialized.  The numbers generated here
   77689 ** are based on typical values found in actual indices.
   77690 */
   77691 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
   77692   unsigned *a = pIdx->aiRowEst;
   77693   int i;
   77694   unsigned n;
   77695   assert( a!=0 );
   77696   a[0] = pIdx->pTable->nRowEst;
   77697   if( a[0]<10 ) a[0] = 10;
   77698   n = 10;
   77699   for(i=1; i<=pIdx->nColumn; i++){
   77700     a[i] = n;
   77701     if( n>5 ) n--;
   77702   }
   77703   if( pIdx->onError!=OE_None ){
   77704     a[pIdx->nColumn] = 1;
   77705   }
   77706 }
   77707 
   77708 /*
   77709 ** This routine will drop an existing named index.  This routine
   77710 ** implements the DROP INDEX statement.
   77711 */
   77712 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
   77713   Index *pIndex;
   77714   Vdbe *v;
   77715   sqlite3 *db = pParse->db;
   77716   int iDb;
   77717 
   77718   assert( pParse->nErr==0 );   /* Never called with prior errors */
   77719   if( db->mallocFailed ){
   77720     goto exit_drop_index;
   77721   }
   77722   assert( pName->nSrc==1 );
   77723   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   77724     goto exit_drop_index;
   77725   }
   77726   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
   77727   if( pIndex==0 ){
   77728     if( !ifExists ){
   77729       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
   77730     }
   77731     pParse->checkSchema = 1;
   77732     goto exit_drop_index;
   77733   }
   77734   if( pIndex->autoIndex ){
   77735     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
   77736       "or PRIMARY KEY constraint cannot be dropped", 0);
   77737     goto exit_drop_index;
   77738   }
   77739   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
   77740 #ifndef SQLITE_OMIT_AUTHORIZATION
   77741   {
   77742     int code = SQLITE_DROP_INDEX;
   77743     Table *pTab = pIndex->pTable;
   77744     const char *zDb = db->aDb[iDb].zName;
   77745     const char *zTab = SCHEMA_TABLE(iDb);
   77746     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   77747       goto exit_drop_index;
   77748     }
   77749     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
   77750     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
   77751       goto exit_drop_index;
   77752     }
   77753   }
   77754 #endif
   77755 
   77756   /* Generate code to remove the index and from the master table */
   77757   v = sqlite3GetVdbe(pParse);
   77758   if( v ){
   77759     sqlite3BeginWriteOperation(pParse, 1, iDb);
   77760     sqlite3NestedParse(pParse,
   77761        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
   77762        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   77763        pIndex->zName
   77764     );
   77765     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
   77766       sqlite3NestedParse(pParse,
   77767         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
   77768         db->aDb[iDb].zName, pIndex->zName
   77769       );
   77770     }
   77771     sqlite3ChangeCookie(pParse, iDb);
   77772     destroyRootPage(pParse, pIndex->tnum, iDb);
   77773     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
   77774   }
   77775 
   77776 exit_drop_index:
   77777   sqlite3SrcListDelete(db, pName);
   77778 }
   77779 
   77780 /*
   77781 ** pArray is a pointer to an array of objects.  Each object in the
   77782 ** array is szEntry bytes in size.  This routine allocates a new
   77783 ** object on the end of the array.
   77784 **
   77785 ** *pnEntry is the number of entries already in use.  *pnAlloc is
   77786 ** the previously allocated size of the array.  initSize is the
   77787 ** suggested initial array size allocation.
   77788 **
   77789 ** The index of the new entry is returned in *pIdx.
   77790 **
   77791 ** This routine returns a pointer to the array of objects.  This
   77792 ** might be the same as the pArray parameter or it might be a different
   77793 ** pointer if the array was resized.
   77794 */
   77795 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
   77796   sqlite3 *db,      /* Connection to notify of malloc failures */
   77797   void *pArray,     /* Array of objects.  Might be reallocated */
   77798   int szEntry,      /* Size of each object in the array */
   77799   int initSize,     /* Suggested initial allocation, in elements */
   77800   int *pnEntry,     /* Number of objects currently in use */
   77801   int *pnAlloc,     /* Current size of the allocation, in elements */
   77802   int *pIdx         /* Write the index of a new slot here */
   77803 ){
   77804   char *z;
   77805   if( *pnEntry >= *pnAlloc ){
   77806     void *pNew;
   77807     int newSize;
   77808     newSize = (*pnAlloc)*2 + initSize;
   77809     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
   77810     if( pNew==0 ){
   77811       *pIdx = -1;
   77812       return pArray;
   77813     }
   77814     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
   77815     pArray = pNew;
   77816   }
   77817   z = (char*)pArray;
   77818   memset(&z[*pnEntry * szEntry], 0, szEntry);
   77819   *pIdx = *pnEntry;
   77820   ++*pnEntry;
   77821   return pArray;
   77822 }
   77823 
   77824 /*
   77825 ** Append a new element to the given IdList.  Create a new IdList if
   77826 ** need be.
   77827 **
   77828 ** A new IdList is returned, or NULL if malloc() fails.
   77829 */
   77830 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
   77831   int i;
   77832   if( pList==0 ){
   77833     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
   77834     if( pList==0 ) return 0;
   77835     pList->nAlloc = 0;
   77836   }
   77837   pList->a = sqlite3ArrayAllocate(
   77838       db,
   77839       pList->a,
   77840       sizeof(pList->a[0]),
   77841       5,
   77842       &pList->nId,
   77843       &pList->nAlloc,
   77844       &i
   77845   );
   77846   if( i<0 ){
   77847     sqlite3IdListDelete(db, pList);
   77848     return 0;
   77849   }
   77850   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
   77851   return pList;
   77852 }
   77853 
   77854 /*
   77855 ** Delete an IdList.
   77856 */
   77857 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
   77858   int i;
   77859   if( pList==0 ) return;
   77860   for(i=0; i<pList->nId; i++){
   77861     sqlite3DbFree(db, pList->a[i].zName);
   77862   }
   77863   sqlite3DbFree(db, pList->a);
   77864   sqlite3DbFree(db, pList);
   77865 }
   77866 
   77867 /*
   77868 ** Return the index in pList of the identifier named zId.  Return -1
   77869 ** if not found.
   77870 */
   77871 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
   77872   int i;
   77873   if( pList==0 ) return -1;
   77874   for(i=0; i<pList->nId; i++){
   77875     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
   77876   }
   77877   return -1;
   77878 }
   77879 
   77880 /*
   77881 ** Expand the space allocated for the given SrcList object by
   77882 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
   77883 ** New slots are zeroed.
   77884 **
   77885 ** For example, suppose a SrcList initially contains two entries: A,B.
   77886 ** To append 3 new entries onto the end, do this:
   77887 **
   77888 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
   77889 **
   77890 ** After the call above it would contain:  A, B, nil, nil, nil.
   77891 ** If the iStart argument had been 1 instead of 2, then the result
   77892 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
   77893 ** the iStart value would be 0.  The result then would
   77894 ** be: nil, nil, nil, A, B.
   77895 **
   77896 ** If a memory allocation fails the SrcList is unchanged.  The
   77897 ** db->mallocFailed flag will be set to true.
   77898 */
   77899 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
   77900   sqlite3 *db,       /* Database connection to notify of OOM errors */
   77901   SrcList *pSrc,     /* The SrcList to be enlarged */
   77902   int nExtra,        /* Number of new slots to add to pSrc->a[] */
   77903   int iStart         /* Index in pSrc->a[] of first new slot */
   77904 ){
   77905   int i;
   77906 
   77907   /* Sanity checking on calling parameters */
   77908   assert( iStart>=0 );
   77909   assert( nExtra>=1 );
   77910   assert( pSrc!=0 );
   77911   assert( iStart<=pSrc->nSrc );
   77912 
   77913   /* Allocate additional space if needed */
   77914   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
   77915     SrcList *pNew;
   77916     int nAlloc = pSrc->nSrc+nExtra;
   77917     int nGot;
   77918     pNew = sqlite3DbRealloc(db, pSrc,
   77919                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
   77920     if( pNew==0 ){
   77921       assert( db->mallocFailed );
   77922       return pSrc;
   77923     }
   77924     pSrc = pNew;
   77925     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
   77926     pSrc->nAlloc = (u16)nGot;
   77927   }
   77928 
   77929   /* Move existing slots that come after the newly inserted slots
   77930   ** out of the way */
   77931   for(i=pSrc->nSrc-1; i>=iStart; i--){
   77932     pSrc->a[i+nExtra] = pSrc->a[i];
   77933   }
   77934   pSrc->nSrc += (i16)nExtra;
   77935 
   77936   /* Zero the newly allocated slots */
   77937   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
   77938   for(i=iStart; i<iStart+nExtra; i++){
   77939     pSrc->a[i].iCursor = -1;
   77940   }
   77941 
   77942   /* Return a pointer to the enlarged SrcList */
   77943   return pSrc;
   77944 }
   77945 
   77946 
   77947 /*
   77948 ** Append a new table name to the given SrcList.  Create a new SrcList if
   77949 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
   77950 **
   77951 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
   77952 ** SrcList might be the same as the SrcList that was input or it might be
   77953 ** a new one.  If an OOM error does occurs, then the prior value of pList
   77954 ** that is input to this routine is automatically freed.
   77955 **
   77956 ** If pDatabase is not null, it means that the table has an optional
   77957 ** database name prefix.  Like this:  "database.table".  The pDatabase
   77958 ** points to the table name and the pTable points to the database name.
   77959 ** The SrcList.a[].zName field is filled with the table name which might
   77960 ** come from pTable (if pDatabase is NULL) or from pDatabase.
   77961 ** SrcList.a[].zDatabase is filled with the database name from pTable,
   77962 ** or with NULL if no database is specified.
   77963 **
   77964 ** In other words, if call like this:
   77965 **
   77966 **         sqlite3SrcListAppend(D,A,B,0);
   77967 **
   77968 ** Then B is a table name and the database name is unspecified.  If called
   77969 ** like this:
   77970 **
   77971 **         sqlite3SrcListAppend(D,A,B,C);
   77972 **
   77973 ** Then C is the table name and B is the database name.  If C is defined
   77974 ** then so is B.  In other words, we never have a case where:
   77975 **
   77976 **         sqlite3SrcListAppend(D,A,0,C);
   77977 **
   77978 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
   77979 ** before being added to the SrcList.
   77980 */
   77981 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
   77982   sqlite3 *db,        /* Connection to notify of malloc failures */
   77983   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
   77984   Token *pTable,      /* Table to append */
   77985   Token *pDatabase    /* Database of the table */
   77986 ){
   77987   struct SrcList_item *pItem;
   77988   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
   77989   if( pList==0 ){
   77990     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
   77991     if( pList==0 ) return 0;
   77992     pList->nAlloc = 1;
   77993   }
   77994   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
   77995   if( db->mallocFailed ){
   77996     sqlite3SrcListDelete(db, pList);
   77997     return 0;
   77998   }
   77999   pItem = &pList->a[pList->nSrc-1];
   78000   if( pDatabase && pDatabase->z==0 ){
   78001     pDatabase = 0;
   78002   }
   78003   if( pDatabase ){
   78004     Token *pTemp = pDatabase;
   78005     pDatabase = pTable;
   78006     pTable = pTemp;
   78007   }
   78008   pItem->zName = sqlite3NameFromToken(db, pTable);
   78009   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
   78010   return pList;
   78011 }
   78012 
   78013 /*
   78014 ** Assign VdbeCursor index numbers to all tables in a SrcList
   78015 */
   78016 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   78017   int i;
   78018   struct SrcList_item *pItem;
   78019   assert(pList || pParse->db->mallocFailed );
   78020   if( pList ){
   78021     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
   78022       if( pItem->iCursor>=0 ) break;
   78023       pItem->iCursor = pParse->nTab++;
   78024       if( pItem->pSelect ){
   78025         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
   78026       }
   78027     }
   78028   }
   78029 }
   78030 
   78031 /*
   78032 ** Delete an entire SrcList including all its substructure.
   78033 */
   78034 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   78035   int i;
   78036   struct SrcList_item *pItem;
   78037   if( pList==0 ) return;
   78038   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
   78039     sqlite3DbFree(db, pItem->zDatabase);
   78040     sqlite3DbFree(db, pItem->zName);
   78041     sqlite3DbFree(db, pItem->zAlias);
   78042     sqlite3DbFree(db, pItem->zIndex);
   78043     sqlite3DeleteTable(db, pItem->pTab);
   78044     sqlite3SelectDelete(db, pItem->pSelect);
   78045     sqlite3ExprDelete(db, pItem->pOn);
   78046     sqlite3IdListDelete(db, pItem->pUsing);
   78047   }
   78048   sqlite3DbFree(db, pList);
   78049 }
   78050 
   78051 /*
   78052 ** This routine is called by the parser to add a new term to the
   78053 ** end of a growing FROM clause.  The "p" parameter is the part of
   78054 ** the FROM clause that has already been constructed.  "p" is NULL
   78055 ** if this is the first term of the FROM clause.  pTable and pDatabase
   78056 ** are the name of the table and database named in the FROM clause term.
   78057 ** pDatabase is NULL if the database name qualifier is missing - the
   78058 ** usual case.  If the term has a alias, then pAlias points to the
   78059 ** alias token.  If the term is a subquery, then pSubquery is the
   78060 ** SELECT statement that the subquery encodes.  The pTable and
   78061 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
   78062 ** parameters are the content of the ON and USING clauses.
   78063 **
   78064 ** Return a new SrcList which encodes is the FROM with the new
   78065 ** term added.
   78066 */
   78067 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   78068   Parse *pParse,          /* Parsing context */
   78069   SrcList *p,             /* The left part of the FROM clause already seen */
   78070   Token *pTable,          /* Name of the table to add to the FROM clause */
   78071   Token *pDatabase,       /* Name of the database containing pTable */
   78072   Token *pAlias,          /* The right-hand side of the AS subexpression */
   78073   Select *pSubquery,      /* A subquery used in place of a table name */
   78074   Expr *pOn,              /* The ON clause of a join */
   78075   IdList *pUsing          /* The USING clause of a join */
   78076 ){
   78077   struct SrcList_item *pItem;
   78078   sqlite3 *db = pParse->db;
   78079   if( !p && (pOn || pUsing) ){
   78080     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
   78081       (pOn ? "ON" : "USING")
   78082     );
   78083     goto append_from_error;
   78084   }
   78085   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
   78086   if( p==0 || NEVER(p->nSrc==0) ){
   78087     goto append_from_error;
   78088   }
   78089   pItem = &p->a[p->nSrc-1];
   78090   assert( pAlias!=0 );
   78091   if( pAlias->n ){
   78092     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
   78093   }
   78094   pItem->pSelect = pSubquery;
   78095   pItem->pOn = pOn;
   78096   pItem->pUsing = pUsing;
   78097   return p;
   78098 
   78099  append_from_error:
   78100   assert( p==0 );
   78101   sqlite3ExprDelete(db, pOn);
   78102   sqlite3IdListDelete(db, pUsing);
   78103   sqlite3SelectDelete(db, pSubquery);
   78104   return 0;
   78105 }
   78106 
   78107 /*
   78108 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
   78109 ** element of the source-list passed as the second argument.
   78110 */
   78111 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
   78112   assert( pIndexedBy!=0 );
   78113   if( p && ALWAYS(p->nSrc>0) ){
   78114     struct SrcList_item *pItem = &p->a[p->nSrc-1];
   78115     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
   78116     if( pIndexedBy->n==1 && !pIndexedBy->z ){
   78117       /* A "NOT INDEXED" clause was supplied. See parse.y
   78118       ** construct "indexed_opt" for details. */
   78119       pItem->notIndexed = 1;
   78120     }else{
   78121       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
   78122     }
   78123   }
   78124 }
   78125 
   78126 /*
   78127 ** When building up a FROM clause in the parser, the join operator
   78128 ** is initially attached to the left operand.  But the code generator
   78129 ** expects the join operator to be on the right operand.  This routine
   78130 ** Shifts all join operators from left to right for an entire FROM
   78131 ** clause.
   78132 **
   78133 ** Example: Suppose the join is like this:
   78134 **
   78135 **           A natural cross join B
   78136 **
   78137 ** The operator is "natural cross join".  The A and B operands are stored
   78138 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
   78139 ** operator with A.  This routine shifts that operator over to B.
   78140 */
   78141 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
   78142   if( p && p->a ){
   78143     int i;
   78144     for(i=p->nSrc-1; i>0; i--){
   78145       p->a[i].jointype = p->a[i-1].jointype;
   78146     }
   78147     p->a[0].jointype = 0;
   78148   }
   78149 }
   78150 
   78151 /*
   78152 ** Begin a transaction
   78153 */
   78154 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   78155   sqlite3 *db;
   78156   Vdbe *v;
   78157   int i;
   78158 
   78159   assert( pParse!=0 );
   78160   db = pParse->db;
   78161   assert( db!=0 );
   78162 /*  if( db->aDb[0].pBt==0 ) return; */
   78163   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
   78164     return;
   78165   }
   78166   v = sqlite3GetVdbe(pParse);
   78167   if( !v ) return;
   78168   if( type!=TK_DEFERRED ){
   78169     for(i=0; i<db->nDb; i++){
   78170       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
   78171       sqlite3VdbeUsesBtree(v, i);
   78172     }
   78173   }
   78174   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
   78175 }
   78176 
   78177 /*
   78178 ** Commit a transaction
   78179 */
   78180 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
   78181   sqlite3 *db;
   78182   Vdbe *v;
   78183 
   78184   assert( pParse!=0 );
   78185   db = pParse->db;
   78186   assert( db!=0 );
   78187 /*  if( db->aDb[0].pBt==0 ) return; */
   78188   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
   78189     return;
   78190   }
   78191   v = sqlite3GetVdbe(pParse);
   78192   if( v ){
   78193     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
   78194   }
   78195 }
   78196 
   78197 /*
   78198 ** Rollback a transaction
   78199 */
   78200 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
   78201   sqlite3 *db;
   78202   Vdbe *v;
   78203 
   78204   assert( pParse!=0 );
   78205   db = pParse->db;
   78206   assert( db!=0 );
   78207 /*  if( db->aDb[0].pBt==0 ) return; */
   78208   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
   78209     return;
   78210   }
   78211   v = sqlite3GetVdbe(pParse);
   78212   if( v ){
   78213     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
   78214   }
   78215 }
   78216 
   78217 /*
   78218 ** This function is called by the parser when it parses a command to create,
   78219 ** release or rollback an SQL savepoint.
   78220 */
   78221 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   78222   char *zName = sqlite3NameFromToken(pParse->db, pName);
   78223   if( zName ){
   78224     Vdbe *v = sqlite3GetVdbe(pParse);
   78225 #ifndef SQLITE_OMIT_AUTHORIZATION
   78226     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
   78227     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
   78228 #endif
   78229     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
   78230       sqlite3DbFree(pParse->db, zName);
   78231       return;
   78232     }
   78233     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
   78234   }
   78235 }
   78236 
   78237 /*
   78238 ** Make sure the TEMP database is open and available for use.  Return
   78239 ** the number of errors.  Leave any error messages in the pParse structure.
   78240 */
   78241 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   78242   sqlite3 *db = pParse->db;
   78243   if( db->aDb[1].pBt==0 && !pParse->explain ){
   78244     int rc;
   78245     Btree *pBt;
   78246     static const int flags =
   78247           SQLITE_OPEN_READWRITE |
   78248           SQLITE_OPEN_CREATE |
   78249           SQLITE_OPEN_EXCLUSIVE |
   78250           SQLITE_OPEN_DELETEONCLOSE |
   78251           SQLITE_OPEN_TEMP_DB;
   78252 
   78253     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
   78254     if( rc!=SQLITE_OK ){
   78255       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
   78256         "file for storing temporary tables");
   78257       pParse->rc = rc;
   78258       return 1;
   78259     }
   78260     db->aDb[1].pBt = pBt;
   78261     assert( db->aDb[1].pSchema );
   78262     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   78263       db->mallocFailed = 1;
   78264       return 1;
   78265     }
   78266   }
   78267   return 0;
   78268 }
   78269 
   78270 /*
   78271 ** Generate VDBE code that will verify the schema cookie and start
   78272 ** a read-transaction for all named database files.
   78273 **
   78274 ** It is important that all schema cookies be verified and all
   78275 ** read transactions be started before anything else happens in
   78276 ** the VDBE program.  But this routine can be called after much other
   78277 ** code has been generated.  So here is what we do:
   78278 **
   78279 ** The first time this routine is called, we code an OP_Goto that
   78280 ** will jump to a subroutine at the end of the program.  Then we
   78281 ** record every database that needs its schema verified in the
   78282 ** pParse->cookieMask field.  Later, after all other code has been
   78283 ** generated, the subroutine that does the cookie verifications and
   78284 ** starts the transactions will be coded and the OP_Goto P2 value
   78285 ** will be made to point to that subroutine.  The generation of the
   78286 ** cookie verification subroutine code happens in sqlite3FinishCoding().
   78287 **
   78288 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
   78289 ** schema on any databases.  This can be used to position the OP_Goto
   78290 ** early in the code, before we know if any database tables will be used.
   78291 */
   78292 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
   78293   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   78294 
   78295   if( pToplevel->cookieGoto==0 ){
   78296     Vdbe *v = sqlite3GetVdbe(pToplevel);
   78297     if( v==0 ) return;  /* This only happens if there was a prior error */
   78298     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
   78299   }
   78300   if( iDb>=0 ){
   78301     sqlite3 *db = pToplevel->db;
   78302     int mask;
   78303 
   78304     assert( iDb<db->nDb );
   78305     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
   78306     assert( iDb<SQLITE_MAX_ATTACHED+2 );
   78307     mask = 1<<iDb;
   78308     if( (pToplevel->cookieMask & mask)==0 ){
   78309       pToplevel->cookieMask |= mask;
   78310       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
   78311       if( !OMIT_TEMPDB && iDb==1 ){
   78312         sqlite3OpenTempDatabase(pToplevel);
   78313       }
   78314     }
   78315   }
   78316 }
   78317 
   78318 /*
   78319 ** Generate VDBE code that prepares for doing an operation that
   78320 ** might change the database.
   78321 **
   78322 ** This routine starts a new transaction if we are not already within
   78323 ** a transaction.  If we are already within a transaction, then a checkpoint
   78324 ** is set if the setStatement parameter is true.  A checkpoint should
   78325 ** be set for operations that might fail (due to a constraint) part of
   78326 ** the way through and which will need to undo some writes without having to
   78327 ** rollback the whole transaction.  For operations where all constraints
   78328 ** can be checked before any changes are made to the database, it is never
   78329 ** necessary to undo a write and the checkpoint should not be set.
   78330 */
   78331 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   78332   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   78333   sqlite3CodeVerifySchema(pParse, iDb);
   78334   pToplevel->writeMask |= 1<<iDb;
   78335   pToplevel->isMultiWrite |= setStatement;
   78336 }
   78337 
   78338 /*
   78339 ** Indicate that the statement currently under construction might write
   78340 ** more than one entry (example: deleting one row then inserting another,
   78341 ** inserting multiple rows in a table, or inserting a row and index entries.)
   78342 ** If an abort occurs after some of these writes have completed, then it will
   78343 ** be necessary to undo the completed writes.
   78344 */
   78345 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   78346   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   78347   pToplevel->isMultiWrite = 1;
   78348 }
   78349 
   78350 /*
   78351 ** The code generator calls this routine if is discovers that it is
   78352 ** possible to abort a statement prior to completion.  In order to
   78353 ** perform this abort without corrupting the database, we need to make
   78354 ** sure that the statement is protected by a statement transaction.
   78355 **
   78356 ** Technically, we only need to set the mayAbort flag if the
   78357 ** isMultiWrite flag was previously set.  There is a time dependency
   78358 ** such that the abort must occur after the multiwrite.  This makes
   78359 ** some statements involving the REPLACE conflict resolution algorithm
   78360 ** go a little faster.  But taking advantage of this time dependency
   78361 ** makes it more difficult to prove that the code is correct (in
   78362 ** particular, it prevents us from writing an effective
   78363 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
   78364 ** to take the safe route and skip the optimization.
   78365 */
   78366 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
   78367   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   78368   pToplevel->mayAbort = 1;
   78369 }
   78370 
   78371 /*
   78372 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
   78373 ** error. The onError parameter determines which (if any) of the statement
   78374 ** and/or current transaction is rolled back.
   78375 */
   78376 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
   78377   Vdbe *v = sqlite3GetVdbe(pParse);
   78378   if( onError==OE_Abort ){
   78379     sqlite3MayAbort(pParse);
   78380   }
   78381   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
   78382 }
   78383 
   78384 /*
   78385 ** Check to see if pIndex uses the collating sequence pColl.  Return
   78386 ** true if it does and false if it does not.
   78387 */
   78388 #ifndef SQLITE_OMIT_REINDEX
   78389 static int collationMatch(const char *zColl, Index *pIndex){
   78390   int i;
   78391   assert( zColl!=0 );
   78392   for(i=0; i<pIndex->nColumn; i++){
   78393     const char *z = pIndex->azColl[i];
   78394     assert( z!=0 );
   78395     if( 0==sqlite3StrICmp(z, zColl) ){
   78396       return 1;
   78397     }
   78398   }
   78399   return 0;
   78400 }
   78401 #endif
   78402 
   78403 /*
   78404 ** Recompute all indices of pTab that use the collating sequence pColl.
   78405 ** If pColl==0 then recompute all indices of pTab.
   78406 */
   78407 #ifndef SQLITE_OMIT_REINDEX
   78408 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
   78409   Index *pIndex;              /* An index associated with pTab */
   78410 
   78411   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   78412     if( zColl==0 || collationMatch(zColl, pIndex) ){
   78413       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   78414       sqlite3BeginWriteOperation(pParse, 0, iDb);
   78415       sqlite3RefillIndex(pParse, pIndex, -1);
   78416     }
   78417   }
   78418 }
   78419 #endif
   78420 
   78421 /*
   78422 ** Recompute all indices of all tables in all databases where the
   78423 ** indices use the collating sequence pColl.  If pColl==0 then recompute
   78424 ** all indices everywhere.
   78425 */
   78426 #ifndef SQLITE_OMIT_REINDEX
   78427 static void reindexDatabases(Parse *pParse, char const *zColl){
   78428   Db *pDb;                    /* A single database */
   78429   int iDb;                    /* The database index number */
   78430   sqlite3 *db = pParse->db;   /* The database connection */
   78431   HashElem *k;                /* For looping over tables in pDb */
   78432   Table *pTab;                /* A table in the database */
   78433 
   78434   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
   78435     assert( pDb!=0 );
   78436     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
   78437       pTab = (Table*)sqliteHashData(k);
   78438       reindexTable(pParse, pTab, zColl);
   78439     }
   78440   }
   78441 }
   78442 #endif
   78443 
   78444 /*
   78445 ** Generate code for the REINDEX command.
   78446 **
   78447 **        REINDEX                            -- 1
   78448 **        REINDEX  <collation>               -- 2
   78449 **        REINDEX  ?<database>.?<tablename>  -- 3
   78450 **        REINDEX  ?<database>.?<indexname>  -- 4
   78451 **
   78452 ** Form 1 causes all indices in all attached databases to be rebuilt.
   78453 ** Form 2 rebuilds all indices in all databases that use the named
   78454 ** collating function.  Forms 3 and 4 rebuild the named index or all
   78455 ** indices associated with the named table.
   78456 */
   78457 #ifndef SQLITE_OMIT_REINDEX
   78458 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
   78459   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
   78460   char *z;                    /* Name of a table or index */
   78461   const char *zDb;            /* Name of the database */
   78462   Table *pTab;                /* A table in the database */
   78463   Index *pIndex;              /* An index associated with pTab */
   78464   int iDb;                    /* The database index number */
   78465   sqlite3 *db = pParse->db;   /* The database connection */
   78466   Token *pObjName;            /* Name of the table or index to be reindexed */
   78467 
   78468   /* Read the database schema. If an error occurs, leave an error message
   78469   ** and code in pParse and return NULL. */
   78470   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   78471     return;
   78472   }
   78473 
   78474   if( pName1==0 ){
   78475     reindexDatabases(pParse, 0);
   78476     return;
   78477   }else if( NEVER(pName2==0) || pName2->z==0 ){
   78478     char *zColl;
   78479     assert( pName1->z );
   78480     zColl = sqlite3NameFromToken(pParse->db, pName1);
   78481     if( !zColl ) return;
   78482     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
   78483     if( pColl ){
   78484       reindexDatabases(pParse, zColl);
   78485       sqlite3DbFree(db, zColl);
   78486       return;
   78487     }
   78488     sqlite3DbFree(db, zColl);
   78489   }
   78490   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
   78491   if( iDb<0 ) return;
   78492   z = sqlite3NameFromToken(db, pObjName);
   78493   if( z==0 ) return;
   78494   zDb = db->aDb[iDb].zName;
   78495   pTab = sqlite3FindTable(db, z, zDb);
   78496   if( pTab ){
   78497     reindexTable(pParse, pTab, 0);
   78498     sqlite3DbFree(db, z);
   78499     return;
   78500   }
   78501   pIndex = sqlite3FindIndex(db, z, zDb);
   78502   sqlite3DbFree(db, z);
   78503   if( pIndex ){
   78504     sqlite3BeginWriteOperation(pParse, 0, iDb);
   78505     sqlite3RefillIndex(pParse, pIndex, -1);
   78506     return;
   78507   }
   78508   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
   78509 }
   78510 #endif
   78511 
   78512 /*
   78513 ** Return a dynamicly allocated KeyInfo structure that can be used
   78514 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
   78515 **
   78516 ** If successful, a pointer to the new structure is returned. In this case
   78517 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
   78518 ** pointer. If an error occurs (out of memory or missing collation
   78519 ** sequence), NULL is returned and the state of pParse updated to reflect
   78520 ** the error.
   78521 */
   78522 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
   78523   int i;
   78524   int nCol = pIdx->nColumn;
   78525   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
   78526   sqlite3 *db = pParse->db;
   78527   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
   78528 
   78529   if( pKey ){
   78530     pKey->db = pParse->db;
   78531     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
   78532     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
   78533     for(i=0; i<nCol; i++){
   78534       char *zColl = pIdx->azColl[i];
   78535       assert( zColl );
   78536       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
   78537       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
   78538     }
   78539     pKey->nField = (u16)nCol;
   78540   }
   78541 
   78542   if( pParse->nErr ){
   78543     sqlite3DbFree(db, pKey);
   78544     pKey = 0;
   78545   }
   78546   return pKey;
   78547 }
   78548 
   78549 /************** End of build.c ***********************************************/
   78550 /************** Begin file callback.c ****************************************/
   78551 /*
   78552 ** 2005 May 23
   78553 **
   78554 ** The author disclaims copyright to this source code.  In place of
   78555 ** a legal notice, here is a blessing:
   78556 **
   78557 **    May you do good and not evil.
   78558 **    May you find forgiveness for yourself and forgive others.
   78559 **    May you share freely, never taking more than you give.
   78560 **
   78561 *************************************************************************
   78562 **
   78563 ** This file contains functions used to access the internal hash tables
   78564 ** of user defined functions and collation sequences.
   78565 */
   78566 
   78567 
   78568 /*
   78569 ** Invoke the 'collation needed' callback to request a collation sequence
   78570 ** in the encoding enc of name zName, length nName.
   78571 */
   78572 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
   78573   assert( !db->xCollNeeded || !db->xCollNeeded16 );
   78574   if( db->xCollNeeded ){
   78575     char *zExternal = sqlite3DbStrDup(db, zName);
   78576     if( !zExternal ) return;
   78577     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
   78578     sqlite3DbFree(db, zExternal);
   78579   }
   78580 #ifndef SQLITE_OMIT_UTF16
   78581   if( db->xCollNeeded16 ){
   78582     char const *zExternal;
   78583     sqlite3_value *pTmp = sqlite3ValueNew(db);
   78584     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
   78585     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
   78586     if( zExternal ){
   78587       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
   78588     }
   78589     sqlite3ValueFree(pTmp);
   78590   }
   78591 #endif
   78592 }
   78593 
   78594 /*
   78595 ** This routine is called if the collation factory fails to deliver a
   78596 ** collation function in the best encoding but there may be other versions
   78597 ** of this collation function (for other text encodings) available. Use one
   78598 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
   78599 ** possible.
   78600 */
   78601 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
   78602   CollSeq *pColl2;
   78603   char *z = pColl->zName;
   78604   int i;
   78605   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
   78606   for(i=0; i<3; i++){
   78607     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
   78608     if( pColl2->xCmp!=0 ){
   78609       memcpy(pColl, pColl2, sizeof(CollSeq));
   78610       pColl->xDel = 0;         /* Do not copy the destructor */
   78611       return SQLITE_OK;
   78612     }
   78613   }
   78614   return SQLITE_ERROR;
   78615 }
   78616 
   78617 /*
   78618 ** This function is responsible for invoking the collation factory callback
   78619 ** or substituting a collation sequence of a different encoding when the
   78620 ** requested collation sequence is not available in the desired encoding.
   78621 **
   78622 ** If it is not NULL, then pColl must point to the database native encoding
   78623 ** collation sequence with name zName, length nName.
   78624 **
   78625 ** The return value is either the collation sequence to be used in database
   78626 ** db for collation type name zName, length nName, or NULL, if no collation
   78627 ** sequence can be found.
   78628 **
   78629 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
   78630 */
   78631 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
   78632   sqlite3* db,          /* The database connection */
   78633   u8 enc,               /* The desired encoding for the collating sequence */
   78634   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
   78635   const char *zName     /* Collating sequence name */
   78636 ){
   78637   CollSeq *p;
   78638 
   78639   p = pColl;
   78640   if( !p ){
   78641     p = sqlite3FindCollSeq(db, enc, zName, 0);
   78642   }
   78643   if( !p || !p->xCmp ){
   78644     /* No collation sequence of this type for this encoding is registered.
   78645     ** Call the collation factory to see if it can supply us with one.
   78646     */
   78647     callCollNeeded(db, enc, zName);
   78648     p = sqlite3FindCollSeq(db, enc, zName, 0);
   78649   }
   78650   if( p && !p->xCmp && synthCollSeq(db, p) ){
   78651     p = 0;
   78652   }
   78653   assert( !p || p->xCmp );
   78654   return p;
   78655 }
   78656 
   78657 /*
   78658 ** This routine is called on a collation sequence before it is used to
   78659 ** check that it is defined. An undefined collation sequence exists when
   78660 ** a database is loaded that contains references to collation sequences
   78661 ** that have not been defined by sqlite3_create_collation() etc.
   78662 **
   78663 ** If required, this routine calls the 'collation needed' callback to
   78664 ** request a definition of the collating sequence. If this doesn't work,
   78665 ** an equivalent collating sequence that uses a text encoding different
   78666 ** from the main database is substituted, if one is available.
   78667 */
   78668 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
   78669   if( pColl ){
   78670     const char *zName = pColl->zName;
   78671     sqlite3 *db = pParse->db;
   78672     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
   78673     if( !p ){
   78674       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
   78675       pParse->nErr++;
   78676       return SQLITE_ERROR;
   78677     }
   78678     assert( p==pColl );
   78679   }
   78680   return SQLITE_OK;
   78681 }
   78682 
   78683 
   78684 
   78685 /*
   78686 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
   78687 ** specified by zName and nName is not found and parameter 'create' is
   78688 ** true, then create a new entry. Otherwise return NULL.
   78689 **
   78690 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
   78691 ** array of three CollSeq structures. The first is the collation sequence
   78692 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
   78693 **
   78694 ** Stored immediately after the three collation sequences is a copy of
   78695 ** the collation sequence name. A pointer to this string is stored in
   78696 ** each collation sequence structure.
   78697 */
   78698 static CollSeq *findCollSeqEntry(
   78699   sqlite3 *db,          /* Database connection */
   78700   const char *zName,    /* Name of the collating sequence */
   78701   int create            /* Create a new entry if true */
   78702 ){
   78703   CollSeq *pColl;
   78704   int nName = sqlite3Strlen30(zName);
   78705   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   78706 
   78707   if( 0==pColl && create ){
   78708     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
   78709     if( pColl ){
   78710       CollSeq *pDel = 0;
   78711       pColl[0].zName = (char*)&pColl[3];
   78712       pColl[0].enc = SQLITE_UTF8;
   78713       pColl[1].zName = (char*)&pColl[3];
   78714       pColl[1].enc = SQLITE_UTF16LE;
   78715       pColl[2].zName = (char*)&pColl[3];
   78716       pColl[2].enc = SQLITE_UTF16BE;
   78717       memcpy(pColl[0].zName, zName, nName);
   78718       pColl[0].zName[nName] = 0;
   78719       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
   78720 
   78721       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
   78722       ** return the pColl pointer to be deleted (because it wasn't added
   78723       ** to the hash table).
   78724       */
   78725       assert( pDel==0 || pDel==pColl );
   78726       if( pDel!=0 ){
   78727         db->mallocFailed = 1;
   78728         sqlite3DbFree(db, pDel);
   78729         pColl = 0;
   78730       }
   78731     }
   78732   }
   78733   return pColl;
   78734 }
   78735 
   78736 /*
   78737 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
   78738 ** Return the CollSeq* pointer for the collation sequence named zName
   78739 ** for the encoding 'enc' from the database 'db'.
   78740 **
   78741 ** If the entry specified is not found and 'create' is true, then create a
   78742 ** new entry.  Otherwise return NULL.
   78743 **
   78744 ** A separate function sqlite3LocateCollSeq() is a wrapper around
   78745 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
   78746 ** if necessary and generates an error message if the collating sequence
   78747 ** cannot be found.
   78748 **
   78749 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
   78750 */
   78751 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
   78752   sqlite3 *db,
   78753   u8 enc,
   78754   const char *zName,
   78755   int create
   78756 ){
   78757   CollSeq *pColl;
   78758   if( zName ){
   78759     pColl = findCollSeqEntry(db, zName, create);
   78760   }else{
   78761     pColl = db->pDfltColl;
   78762   }
   78763   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
   78764   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   78765   if( pColl ) pColl += enc-1;
   78766   return pColl;
   78767 }
   78768 
   78769 /* During the search for the best function definition, this procedure
   78770 ** is called to test how well the function passed as the first argument
   78771 ** matches the request for a function with nArg arguments in a system
   78772 ** that uses encoding enc. The value returned indicates how well the
   78773 ** request is matched. A higher value indicates a better match.
   78774 **
   78775 ** The returned value is always between 0 and 6, as follows:
   78776 **
   78777 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
   78778 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
   78779 **    encoding is requested, or vice versa.
   78780 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
   78781 **    requested, or vice versa.
   78782 ** 3: A variable arguments function using the same text encoding.
   78783 ** 4: A function with the exact number of arguments requested that
   78784 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
   78785 ** 5: A function with the exact number of arguments requested that
   78786 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
   78787 ** 6: An exact match.
   78788 **
   78789 */
   78790 static int matchQuality(FuncDef *p, int nArg, u8 enc){
   78791   int match = 0;
   78792   if( p->nArg==-1 || p->nArg==nArg
   78793    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
   78794   ){
   78795     match = 1;
   78796     if( p->nArg==nArg || nArg==-1 ){
   78797       match = 4;
   78798     }
   78799     if( enc==p->iPrefEnc ){
   78800       match += 2;
   78801     }
   78802     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
   78803              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
   78804       match += 1;
   78805     }
   78806   }
   78807   return match;
   78808 }
   78809 
   78810 /*
   78811 ** Search a FuncDefHash for a function with the given name.  Return
   78812 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
   78813 */
   78814 static FuncDef *functionSearch(
   78815   FuncDefHash *pHash,  /* Hash table to search */
   78816   int h,               /* Hash of the name */
   78817   const char *zFunc,   /* Name of function */
   78818   int nFunc            /* Number of bytes in zFunc */
   78819 ){
   78820   FuncDef *p;
   78821   for(p=pHash->a[h]; p; p=p->pHash){
   78822     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
   78823       return p;
   78824     }
   78825   }
   78826   return 0;
   78827 }
   78828 
   78829 /*
   78830 ** Insert a new FuncDef into a FuncDefHash hash table.
   78831 */
   78832 SQLITE_PRIVATE void sqlite3FuncDefInsert(
   78833   FuncDefHash *pHash,  /* The hash table into which to insert */
   78834   FuncDef *pDef        /* The function definition to insert */
   78835 ){
   78836   FuncDef *pOther;
   78837   int nName = sqlite3Strlen30(pDef->zName);
   78838   u8 c1 = (u8)pDef->zName[0];
   78839   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
   78840   pOther = functionSearch(pHash, h, pDef->zName, nName);
   78841   if( pOther ){
   78842     assert( pOther!=pDef && pOther->pNext!=pDef );
   78843     pDef->pNext = pOther->pNext;
   78844     pOther->pNext = pDef;
   78845   }else{
   78846     pDef->pNext = 0;
   78847     pDef->pHash = pHash->a[h];
   78848     pHash->a[h] = pDef;
   78849   }
   78850 }
   78851 
   78852 
   78853 
   78854 /*
   78855 ** Locate a user function given a name, a number of arguments and a flag
   78856 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
   78857 ** pointer to the FuncDef structure that defines that function, or return
   78858 ** NULL if the function does not exist.
   78859 **
   78860 ** If the createFlag argument is true, then a new (blank) FuncDef
   78861 ** structure is created and liked into the "db" structure if a
   78862 ** no matching function previously existed.  When createFlag is true
   78863 ** and the nArg parameter is -1, then only a function that accepts
   78864 ** any number of arguments will be returned.
   78865 **
   78866 ** If createFlag is false and nArg is -1, then the first valid
   78867 ** function found is returned.  A function is valid if either xFunc
   78868 ** or xStep is non-zero.
   78869 **
   78870 ** If createFlag is false, then a function with the required name and
   78871 ** number of arguments may be returned even if the eTextRep flag does not
   78872 ** match that requested.
   78873 */
   78874 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   78875   sqlite3 *db,       /* An open database */
   78876   const char *zName, /* Name of the function.  Not null-terminated */
   78877   int nName,         /* Number of characters in the name */
   78878   int nArg,          /* Number of arguments.  -1 means any number */
   78879   u8 enc,            /* Preferred text encoding */
   78880   int createFlag     /* Create new entry if true and does not otherwise exist */
   78881 ){
   78882   FuncDef *p;         /* Iterator variable */
   78883   FuncDef *pBest = 0; /* Best match found so far */
   78884   int bestScore = 0;  /* Score of best match */
   78885   int h;              /* Hash value */
   78886 
   78887 
   78888   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   78889   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
   78890 
   78891   /* First search for a match amongst the application-defined functions.
   78892   */
   78893   p = functionSearch(&db->aFunc, h, zName, nName);
   78894   while( p ){
   78895     int score = matchQuality(p, nArg, enc);
   78896     if( score>bestScore ){
   78897       pBest = p;
   78898       bestScore = score;
   78899     }
   78900     p = p->pNext;
   78901   }
   78902 
   78903   /* If no match is found, search the built-in functions.
   78904   **
   78905   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
   78906   ** functions even if a prior app-defined function was found.  And give
   78907   ** priority to built-in functions.
   78908   **
   78909   ** Except, if createFlag is true, that means that we are trying to
   78910   ** install a new function.  Whatever FuncDef structure is returned it will
   78911   ** have fields overwritten with new information appropriate for the
   78912   ** new function.  But the FuncDefs for built-in functions are read-only.
   78913   ** So we must not search for built-ins when creating a new function.
   78914   */
   78915   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
   78916     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   78917     bestScore = 0;
   78918     p = functionSearch(pHash, h, zName, nName);
   78919     while( p ){
   78920       int score = matchQuality(p, nArg, enc);
   78921       if( score>bestScore ){
   78922         pBest = p;
   78923         bestScore = score;
   78924       }
   78925       p = p->pNext;
   78926     }
   78927   }
   78928 
   78929   /* If the createFlag parameter is true and the search did not reveal an
   78930   ** exact match for the name, number of arguments and encoding, then add a
   78931   ** new entry to the hash table and return it.
   78932   */
   78933   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
   78934       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
   78935     pBest->zName = (char *)&pBest[1];
   78936     pBest->nArg = (u16)nArg;
   78937     pBest->iPrefEnc = enc;
   78938     memcpy(pBest->zName, zName, nName);
   78939     pBest->zName[nName] = 0;
   78940     sqlite3FuncDefInsert(&db->aFunc, pBest);
   78941   }
   78942 
   78943   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
   78944     return pBest;
   78945   }
   78946   return 0;
   78947 }
   78948 
   78949 /*
   78950 ** Free all resources held by the schema structure. The void* argument points
   78951 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
   78952 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
   78953 ** of the schema hash tables).
   78954 **
   78955 ** The Schema.cache_size variable is not cleared.
   78956 */
   78957 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
   78958   Hash temp1;
   78959   Hash temp2;
   78960   HashElem *pElem;
   78961   Schema *pSchema = (Schema *)p;
   78962 
   78963   temp1 = pSchema->tblHash;
   78964   temp2 = pSchema->trigHash;
   78965   sqlite3HashInit(&pSchema->trigHash);
   78966   sqlite3HashClear(&pSchema->idxHash);
   78967   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
   78968     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
   78969   }
   78970   sqlite3HashClear(&temp2);
   78971   sqlite3HashInit(&pSchema->tblHash);
   78972   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
   78973     Table *pTab = sqliteHashData(pElem);
   78974     sqlite3DeleteTable(0, pTab);
   78975   }
   78976   sqlite3HashClear(&temp1);
   78977   sqlite3HashClear(&pSchema->fkeyHash);
   78978   pSchema->pSeqTab = 0;
   78979   pSchema->flags &= ~DB_SchemaLoaded;
   78980 }
   78981 
   78982 /*
   78983 ** Find and return the schema associated with a BTree.  Create
   78984 ** a new one if necessary.
   78985 */
   78986 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
   78987   Schema * p;
   78988   if( pBt ){
   78989     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
   78990   }else{
   78991     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   78992   }
   78993   if( !p ){
   78994     db->mallocFailed = 1;
   78995   }else if ( 0==p->file_format ){
   78996     sqlite3HashInit(&p->tblHash);
   78997     sqlite3HashInit(&p->idxHash);
   78998     sqlite3HashInit(&p->trigHash);
   78999     sqlite3HashInit(&p->fkeyHash);
   79000     p->enc = SQLITE_UTF8;
   79001   }
   79002   return p;
   79003 }
   79004 
   79005 /************** End of callback.c ********************************************/
   79006 /************** Begin file delete.c ******************************************/
   79007 /*
   79008 ** 2001 September 15
   79009 **
   79010 ** The author disclaims copyright to this source code.  In place of
   79011 ** a legal notice, here is a blessing:
   79012 **
   79013 **    May you do good and not evil.
   79014 **    May you find forgiveness for yourself and forgive others.
   79015 **    May you share freely, never taking more than you give.
   79016 **
   79017 *************************************************************************
   79018 ** This file contains C code routines that are called by the parser
   79019 ** in order to generate code for DELETE FROM statements.
   79020 */
   79021 
   79022 /*
   79023 ** Look up every table that is named in pSrc.  If any table is not found,
   79024 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
   79025 ** are found, return a pointer to the last table.
   79026 */
   79027 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   79028   struct SrcList_item *pItem = pSrc->a;
   79029   Table *pTab;
   79030   assert( pItem && pSrc->nSrc==1 );
   79031   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   79032   sqlite3DeleteTable(pParse->db, pItem->pTab);
   79033   pItem->pTab = pTab;
   79034   if( pTab ){
   79035     pTab->nRef++;
   79036   }
   79037   if( sqlite3IndexedByLookup(pParse, pItem) ){
   79038     pTab = 0;
   79039   }
   79040   return pTab;
   79041 }
   79042 
   79043 /*
   79044 ** Check to make sure the given table is writable.  If it is not
   79045 ** writable, generate an error message and return 1.  If it is
   79046 ** writable return 0;
   79047 */
   79048 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
   79049   /* A table is not writable under the following circumstances:
   79050   **
   79051   **   1) It is a virtual table and no implementation of the xUpdate method
   79052   **      has been provided, or
   79053   **   2) It is a system table (i.e. sqlite_master), this call is not
   79054   **      part of a nested parse and writable_schema pragma has not
   79055   **      been specified.
   79056   **
   79057   ** In either case leave an error message in pParse and return non-zero.
   79058   */
   79059   if( ( IsVirtual(pTab)
   79060      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
   79061    || ( (pTab->tabFlags & TF_Readonly)!=0
   79062      && (pParse->db->flags & SQLITE_WriteSchema)==0
   79063      && pParse->nested==0 )
   79064   ){
   79065     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
   79066     return 1;
   79067   }
   79068 
   79069 #ifndef SQLITE_OMIT_VIEW
   79070   if( !viewOk && pTab->pSelect ){
   79071     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
   79072     return 1;
   79073   }
   79074 #endif
   79075   return 0;
   79076 }
   79077 
   79078 
   79079 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   79080 /*
   79081 ** Evaluate a view and store its result in an ephemeral table.  The
   79082 ** pWhere argument is an optional WHERE clause that restricts the
   79083 ** set of rows in the view that are to be added to the ephemeral table.
   79084 */
   79085 SQLITE_PRIVATE void sqlite3MaterializeView(
   79086   Parse *pParse,       /* Parsing context */
   79087   Table *pView,        /* View definition */
   79088   Expr *pWhere,        /* Optional WHERE clause to be added */
   79089   int iCur             /* Cursor number for ephemerial table */
   79090 ){
   79091   SelectDest dest;
   79092   Select *pDup;
   79093   sqlite3 *db = pParse->db;
   79094 
   79095   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
   79096   if( pWhere ){
   79097     SrcList *pFrom;
   79098 
   79099     pWhere = sqlite3ExprDup(db, pWhere, 0);
   79100     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
   79101     if( pFrom ){
   79102       assert( pFrom->nSrc==1 );
   79103       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
   79104       pFrom->a[0].pSelect = pDup;
   79105       assert( pFrom->a[0].pOn==0 );
   79106       assert( pFrom->a[0].pUsing==0 );
   79107     }else{
   79108       sqlite3SelectDelete(db, pDup);
   79109     }
   79110     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
   79111   }
   79112   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   79113   sqlite3Select(pParse, pDup, &dest);
   79114   sqlite3SelectDelete(db, pDup);
   79115 }
   79116 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
   79117 
   79118 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
   79119 /*
   79120 ** Generate an expression tree to implement the WHERE, ORDER BY,
   79121 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
   79122 **
   79123 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
   79124 **                            \__________________________/
   79125 **                               pLimitWhere (pInClause)
   79126 */
   79127 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   79128   Parse *pParse,               /* The parser context */
   79129   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
   79130   Expr *pWhere,                /* The WHERE clause.  May be null */
   79131   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
   79132   Expr *pLimit,                /* The LIMIT clause.  May be null */
   79133   Expr *pOffset,               /* The OFFSET clause.  May be null */
   79134   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
   79135 ){
   79136   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
   79137   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
   79138   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
   79139   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
   79140   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   79141   Select *pSelect = NULL;      /* Complete SELECT tree */
   79142 
   79143   /* Check that there isn't an ORDER BY without a LIMIT clause.
   79144   */
   79145   if( pOrderBy && (pLimit == 0) ) {
   79146     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   79147     pParse->parseError = 1;
   79148     goto limit_where_cleanup_2;
   79149   }
   79150 
   79151   /* We only need to generate a select expression if there
   79152   ** is a limit/offset term to enforce.
   79153   */
   79154   if( pLimit == 0 ) {
   79155     /* if pLimit is null, pOffset will always be null as well. */
   79156     assert( pOffset == 0 );
   79157     return pWhere;
   79158   }
   79159 
   79160   /* Generate a select expression tree to enforce the limit/offset
   79161   ** term for the DELETE or UPDATE statement.  For example:
   79162   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   79163   ** becomes:
   79164   **   DELETE FROM table_a WHERE rowid IN (
   79165   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   79166   **   );
   79167   */
   79168 
   79169   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   79170   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
   79171   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
   79172   if( pEList == 0 ) goto limit_where_cleanup_2;
   79173 
   79174   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
   79175   ** and the SELECT subtree. */
   79176   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
   79177   if( pSelectSrc == 0 ) {
   79178     sqlite3ExprListDelete(pParse->db, pEList);
   79179     goto limit_where_cleanup_2;
   79180   }
   79181 
   79182   /* generate the SELECT expression tree. */
   79183   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
   79184                              pOrderBy,0,pLimit,pOffset);
   79185   if( pSelect == 0 ) return 0;
   79186 
   79187   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
   79188   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
   79189   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
   79190   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
   79191   if( pInClause == 0 ) goto limit_where_cleanup_1;
   79192 
   79193   pInClause->x.pSelect = pSelect;
   79194   pInClause->flags |= EP_xIsSelect;
   79195   sqlite3ExprSetHeight(pParse, pInClause);
   79196   return pInClause;
   79197 
   79198   /* something went wrong. clean up anything allocated. */
   79199 limit_where_cleanup_1:
   79200   sqlite3SelectDelete(pParse->db, pSelect);
   79201   return 0;
   79202 
   79203 limit_where_cleanup_2:
   79204   sqlite3ExprDelete(pParse->db, pWhere);
   79205   sqlite3ExprListDelete(pParse->db, pOrderBy);
   79206   sqlite3ExprDelete(pParse->db, pLimit);
   79207   sqlite3ExprDelete(pParse->db, pOffset);
   79208   return 0;
   79209 }
   79210 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
   79211 
   79212 /*
   79213 ** Generate code for a DELETE FROM statement.
   79214 **
   79215 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
   79216 **                 \________/       \________________/
   79217 **                  pTabList              pWhere
   79218 */
   79219 SQLITE_PRIVATE void sqlite3DeleteFrom(
   79220   Parse *pParse,         /* The parser context */
   79221   SrcList *pTabList,     /* The table from which we should delete things */
   79222   Expr *pWhere           /* The WHERE clause.  May be null */
   79223 ){
   79224   Vdbe *v;               /* The virtual database engine */
   79225   Table *pTab;           /* The table from which records will be deleted */
   79226   const char *zDb;       /* Name of database holding pTab */
   79227   int end, addr = 0;     /* A couple addresses of generated code */
   79228   int i;                 /* Loop counter */
   79229   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   79230   Index *pIdx;           /* For looping over indices of the table */
   79231   int iCur;              /* VDBE Cursor number for pTab */
   79232   sqlite3 *db;           /* Main database structure */
   79233   AuthContext sContext;  /* Authorization context */
   79234   NameContext sNC;       /* Name context to resolve expressions in */
   79235   int iDb;               /* Database number */
   79236   int memCnt = -1;       /* Memory cell used for change counting */
   79237   int rcauth;            /* Value returned by authorization callback */
   79238 
   79239 #ifndef SQLITE_OMIT_TRIGGER
   79240   int isView;                  /* True if attempting to delete from a view */
   79241   Trigger *pTrigger;           /* List of table triggers, if required */
   79242 #endif
   79243 
   79244   memset(&sContext, 0, sizeof(sContext));
   79245   db = pParse->db;
   79246   if( pParse->nErr || db->mallocFailed ){
   79247     goto delete_from_cleanup;
   79248   }
   79249   assert( pTabList->nSrc==1 );
   79250 
   79251   /* Locate the table which we want to delete.  This table has to be
   79252   ** put in an SrcList structure because some of the subroutines we
   79253   ** will be calling are designed to work with multiple tables and expect
   79254   ** an SrcList* parameter instead of just a Table* parameter.
   79255   */
   79256   pTab = sqlite3SrcListLookup(pParse, pTabList);
   79257   if( pTab==0 )  goto delete_from_cleanup;
   79258 
   79259   /* Figure out if we have any triggers and if the table being
   79260   ** deleted from is a view
   79261   */
   79262 #ifndef SQLITE_OMIT_TRIGGER
   79263   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   79264   isView = pTab->pSelect!=0;
   79265 #else
   79266 # define pTrigger 0
   79267 # define isView 0
   79268 #endif
   79269 #ifdef SQLITE_OMIT_VIEW
   79270 # undef isView
   79271 # define isView 0
   79272 #endif
   79273 
   79274   /* If pTab is really a view, make sure it has been initialized.
   79275   */
   79276   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   79277     goto delete_from_cleanup;
   79278   }
   79279 
   79280   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
   79281     goto delete_from_cleanup;
   79282   }
   79283   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   79284   assert( iDb<db->nDb );
   79285   zDb = db->aDb[iDb].zName;
   79286   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
   79287   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   79288   if( rcauth==SQLITE_DENY ){
   79289     goto delete_from_cleanup;
   79290   }
   79291   assert(!isView || pTrigger);
   79292 
   79293   /* Assign  cursor number to the table and all its indices.
   79294   */
   79295   assert( pTabList->nSrc==1 );
   79296   iCur = pTabList->a[0].iCursor = pParse->nTab++;
   79297   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   79298     pParse->nTab++;
   79299   }
   79300 
   79301   /* Start the view context
   79302   */
   79303   if( isView ){
   79304     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   79305   }
   79306 
   79307   /* Begin generating code.
   79308   */
   79309   v = sqlite3GetVdbe(pParse);
   79310   if( v==0 ){
   79311     goto delete_from_cleanup;
   79312   }
   79313   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   79314   sqlite3BeginWriteOperation(pParse, 1, iDb);
   79315 
   79316   /* If we are trying to delete from a view, realize that view into
   79317   ** a ephemeral table.
   79318   */
   79319 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   79320   if( isView ){
   79321     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   79322   }
   79323 #endif
   79324 
   79325   /* Resolve the column names in the WHERE clause.
   79326   */
   79327   memset(&sNC, 0, sizeof(sNC));
   79328   sNC.pParse = pParse;
   79329   sNC.pSrcList = pTabList;
   79330   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   79331     goto delete_from_cleanup;
   79332   }
   79333 
   79334   /* Initialize the counter of the number of rows deleted, if
   79335   ** we are counting rows.
   79336   */
   79337   if( db->flags & SQLITE_CountRows ){
   79338     memCnt = ++pParse->nMem;
   79339     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
   79340   }
   79341 
   79342 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   79343   /* Special case: A DELETE without a WHERE clause deletes everything.
   79344   ** It is easier just to erase the whole table. Prior to version 3.6.5,
   79345   ** this optimization caused the row change count (the value returned by
   79346   ** API function sqlite3_count_changes) to be set incorrectly.  */
   79347   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
   79348    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
   79349   ){
   79350     assert( !isView );
   79351     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
   79352                       pTab->zName, P4_STATIC);
   79353     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   79354       assert( pIdx->pSchema==pTab->pSchema );
   79355       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
   79356     }
   79357   }else
   79358 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   79359   /* The usual case: There is a WHERE clause so we have to scan through
   79360   ** the table and pick which records to delete.
   79361   */
   79362   {
   79363     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
   79364     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
   79365     int regRowid;                   /* Actual register containing rowids */
   79366 
   79367     /* Collect rowids of every row to be deleted.
   79368     */
   79369     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
   79370     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
   79371     if( pWInfo==0 ) goto delete_from_cleanup;
   79372     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
   79373     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
   79374     if( db->flags & SQLITE_CountRows ){
   79375       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
   79376     }
   79377     sqlite3WhereEnd(pWInfo);
   79378 
   79379     /* Delete every item whose key was written to the list during the
   79380     ** database scan.  We have to delete items after the scan is complete
   79381     ** because deleting an item can change the scan order.  */
   79382     end = sqlite3VdbeMakeLabel(v);
   79383 
   79384     /* Unless this is a view, open cursors for the table we are
   79385     ** deleting from and all its indices. If this is a view, then the
   79386     ** only effect this statement has is to fire the INSTEAD OF
   79387     ** triggers.  */
   79388     if( !isView ){
   79389       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
   79390     }
   79391 
   79392     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
   79393 
   79394     /* Delete the row */
   79395 #ifndef SQLITE_OMIT_VIRTUALTABLE
   79396     if( IsVirtual(pTab) ){
   79397       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   79398       sqlite3VtabMakeWritable(pParse, pTab);
   79399       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
   79400       sqlite3MayAbort(pParse);
   79401     }else
   79402 #endif
   79403     {
   79404       int count = (pParse->nested==0);    /* True to count changes */
   79405       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
   79406     }
   79407 
   79408     /* End of the delete loop */
   79409     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   79410     sqlite3VdbeResolveLabel(v, end);
   79411 
   79412     /* Close the cursors open on the table and its indexes. */
   79413     if( !isView && !IsVirtual(pTab) ){
   79414       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   79415         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
   79416       }
   79417       sqlite3VdbeAddOp1(v, OP_Close, iCur);
   79418     }
   79419   }
   79420 
   79421   /* Update the sqlite_sequence table by storing the content of the
   79422   ** maximum rowid counter values recorded while inserting into
   79423   ** autoincrement tables.
   79424   */
   79425   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   79426     sqlite3AutoincrementEnd(pParse);
   79427   }
   79428 
   79429   /* Return the number of rows that were deleted. If this routine is
   79430   ** generating code because of a call to sqlite3NestedParse(), do not
   79431   ** invoke the callback function.
   79432   */
   79433   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   79434     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
   79435     sqlite3VdbeSetNumCols(v, 1);
   79436     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
   79437   }
   79438 
   79439 delete_from_cleanup:
   79440   sqlite3AuthContextPop(&sContext);
   79441   sqlite3SrcListDelete(db, pTabList);
   79442   sqlite3ExprDelete(db, pWhere);
   79443   return;
   79444 }
   79445 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   79446 ** thely may interfere with compilation of other functions in this file
   79447 ** (or in another file, if this file becomes part of the amalgamation).  */
   79448 #ifdef isView
   79449  #undef isView
   79450 #endif
   79451 #ifdef pTrigger
   79452  #undef pTrigger
   79453 #endif
   79454 
   79455 /*
   79456 ** This routine generates VDBE code that causes a single row of a
   79457 ** single table to be deleted.
   79458 **
   79459 ** The VDBE must be in a particular state when this routine is called.
   79460 ** These are the requirements:
   79461 **
   79462 **   1.  A read/write cursor pointing to pTab, the table containing the row
   79463 **       to be deleted, must be opened as cursor number $iCur.
   79464 **
   79465 **   2.  Read/write cursors for all indices of pTab must be open as
   79466 **       cursor number base+i for the i-th index.
   79467 **
   79468 **   3.  The record number of the row to be deleted must be stored in
   79469 **       memory cell iRowid.
   79470 **
   79471 ** This routine generates code to remove both the table record and all
   79472 ** index entries that point to that record.
   79473 */
   79474 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   79475   Parse *pParse,     /* Parsing context */
   79476   Table *pTab,       /* Table containing the row to be deleted */
   79477   int iCur,          /* Cursor number for the table */
   79478   int iRowid,        /* Memory cell that contains the rowid to delete */
   79479   int count,         /* If non-zero, increment the row change counter */
   79480   Trigger *pTrigger, /* List of triggers to (potentially) fire */
   79481   int onconf         /* Default ON CONFLICT policy for triggers */
   79482 ){
   79483   Vdbe *v = pParse->pVdbe;        /* Vdbe */
   79484   int iOld = 0;                   /* First register in OLD.* array */
   79485   int iLabel;                     /* Label resolved to end of generated code */
   79486 
   79487   /* Vdbe is guaranteed to have been allocated by this stage. */
   79488   assert( v );
   79489 
   79490   /* Seek cursor iCur to the row to delete. If this row no longer exists
   79491   ** (this can happen if a trigger program has already deleted it), do
   79492   ** not attempt to delete it or fire any DELETE triggers.  */
   79493   iLabel = sqlite3VdbeMakeLabel(v);
   79494   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   79495 
   79496   /* If there are any triggers to fire, allocate a range of registers to
   79497   ** use for the old.* references in the triggers.  */
   79498   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   79499     u32 mask;                     /* Mask of OLD.* columns in use */
   79500     int iCol;                     /* Iterator used while populating OLD.* */
   79501 
   79502     /* TODO: Could use temporary registers here. Also could attempt to
   79503     ** avoid copying the contents of the rowid register.  */
   79504     mask = sqlite3TriggerColmask(
   79505         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
   79506     );
   79507     mask |= sqlite3FkOldmask(pParse, pTab);
   79508     iOld = pParse->nMem+1;
   79509     pParse->nMem += (1 + pTab->nCol);
   79510 
   79511     /* Populate the OLD.* pseudo-table register array. These values will be
   79512     ** used by any BEFORE and AFTER triggers that exist.  */
   79513     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
   79514     for(iCol=0; iCol<pTab->nCol; iCol++){
   79515       if( mask==0xffffffff || mask&(1<<iCol) ){
   79516         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
   79517       }
   79518     }
   79519 
   79520     /* Invoke BEFORE DELETE trigger programs. */
   79521     sqlite3CodeRowTrigger(pParse, pTrigger,
   79522         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
   79523     );
   79524 
   79525     /* Seek the cursor to the row to be deleted again. It may be that
   79526     ** the BEFORE triggers coded above have already removed the row
   79527     ** being deleted. Do not attempt to delete the row a second time, and
   79528     ** do not fire AFTER triggers.  */
   79529     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
   79530 
   79531     /* Do FK processing. This call checks that any FK constraints that
   79532     ** refer to this table (i.e. constraints attached to other tables)
   79533     ** are not violated by deleting this row.  */
   79534     sqlite3FkCheck(pParse, pTab, iOld, 0);
   79535   }
   79536 
   79537   /* Delete the index and table entries. Skip this step if pTab is really
   79538   ** a view (in which case the only effect of the DELETE statement is to
   79539   ** fire the INSTEAD OF triggers).  */
   79540   if( pTab->pSelect==0 ){
   79541     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
   79542     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
   79543     if( count ){
   79544       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
   79545     }
   79546   }
   79547 
   79548   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   79549   ** handle rows (possibly in other tables) that refer via a foreign key
   79550   ** to the row just deleted. */
   79551   sqlite3FkActions(pParse, pTab, 0, iOld);
   79552 
   79553   /* Invoke AFTER DELETE trigger programs. */
   79554   sqlite3CodeRowTrigger(pParse, pTrigger,
   79555       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   79556   );
   79557 
   79558   /* Jump here if the row had already been deleted before any BEFORE
   79559   ** trigger programs were invoked. Or if a trigger program throws a
   79560   ** RAISE(IGNORE) exception.  */
   79561   sqlite3VdbeResolveLabel(v, iLabel);
   79562 }
   79563 
   79564 /*
   79565 ** This routine generates VDBE code that causes the deletion of all
   79566 ** index entries associated with a single row of a single table.
   79567 **
   79568 ** The VDBE must be in a particular state when this routine is called.
   79569 ** These are the requirements:
   79570 **
   79571 **   1.  A read/write cursor pointing to pTab, the table containing the row
   79572 **       to be deleted, must be opened as cursor number "iCur".
   79573 **
   79574 **   2.  Read/write cursors for all indices of pTab must be open as
   79575 **       cursor number iCur+i for the i-th index.
   79576 **
   79577 **   3.  The "iCur" cursor must be pointing to the row that is to be
   79578 **       deleted.
   79579 */
   79580 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
   79581   Parse *pParse,     /* Parsing and code generating context */
   79582   Table *pTab,       /* Table containing the row to be deleted */
   79583   int iCur,          /* Cursor number for the table */
   79584   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   79585 ){
   79586   int i;
   79587   Index *pIdx;
   79588   int r1;
   79589 
   79590   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   79591     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
   79592     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
   79593     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
   79594   }
   79595 }
   79596 
   79597 /*
   79598 ** Generate code that will assemble an index key and put it in register
   79599 ** regOut.  The key with be for index pIdx which is an index on pTab.
   79600 ** iCur is the index of a cursor open on the pTab table and pointing to
   79601 ** the entry that needs indexing.
   79602 **
   79603 ** Return a register number which is the first in a block of
   79604 ** registers that holds the elements of the index key.  The
   79605 ** block of registers has already been deallocated by the time
   79606 ** this routine returns.
   79607 */
   79608 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   79609   Parse *pParse,     /* Parsing context */
   79610   Index *pIdx,       /* The index for which to generate a key */
   79611   int iCur,          /* Cursor number for the pIdx->pTable table */
   79612   int regOut,        /* Write the new index key to this register */
   79613   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
   79614 ){
   79615   Vdbe *v = pParse->pVdbe;
   79616   int j;
   79617   Table *pTab = pIdx->pTable;
   79618   int regBase;
   79619   int nCol;
   79620 
   79621   nCol = pIdx->nColumn;
   79622   regBase = sqlite3GetTempRange(pParse, nCol+1);
   79623   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
   79624   for(j=0; j<nCol; j++){
   79625     int idx = pIdx->aiColumn[j];
   79626     if( idx==pTab->iPKey ){
   79627       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
   79628     }else{
   79629       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
   79630       sqlite3ColumnDefault(v, pTab, idx, -1);
   79631     }
   79632   }
   79633   if( doMakeRec ){
   79634     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
   79635     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   79636   }
   79637   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
   79638   return regBase;
   79639 }
   79640 
   79641 /************** End of delete.c **********************************************/
   79642 /************** Begin file func.c ********************************************/
   79643 /*
   79644 ** 2002 February 23
   79645 **
   79646 ** The author disclaims copyright to this source code.  In place of
   79647 ** a legal notice, here is a blessing:
   79648 **
   79649 **    May you do good and not evil.
   79650 **    May you find forgiveness for yourself and forgive others.
   79651 **    May you share freely, never taking more than you give.
   79652 **
   79653 *************************************************************************
   79654 ** This file contains the C functions that implement various SQL
   79655 ** functions of SQLite.
   79656 **
   79657 ** There is only one exported symbol in this file - the function
   79658 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
   79659 ** All other code has file scope.
   79660 */
   79661 
   79662 /*
   79663 ** Return the collating function associated with a function.
   79664 */
   79665 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
   79666   return context->pColl;
   79667 }
   79668 
   79669 /*
   79670 ** Implementation of the non-aggregate min() and max() functions
   79671 */
   79672 static void minmaxFunc(
   79673   sqlite3_context *context,
   79674   int argc,
   79675   sqlite3_value **argv
   79676 ){
   79677   int i;
   79678   int mask;    /* 0 for min() or 0xffffffff for max() */
   79679   int iBest;
   79680   CollSeq *pColl;
   79681 
   79682   assert( argc>1 );
   79683   mask = sqlite3_user_data(context)==0 ? 0 : -1;
   79684   pColl = sqlite3GetFuncCollSeq(context);
   79685   assert( pColl );
   79686   assert( mask==-1 || mask==0 );
   79687   iBest = 0;
   79688   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   79689   for(i=1; i<argc; i++){
   79690     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
   79691     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
   79692       testcase( mask==0 );
   79693       iBest = i;
   79694     }
   79695   }
   79696   sqlite3_result_value(context, argv[iBest]);
   79697 }
   79698 
   79699 /*
   79700 ** Return the type of the argument.
   79701 */
   79702 static void typeofFunc(
   79703   sqlite3_context *context,
   79704   int NotUsed,
   79705   sqlite3_value **argv
   79706 ){
   79707   const char *z = 0;
   79708   UNUSED_PARAMETER(NotUsed);
   79709   switch( sqlite3_value_type(argv[0]) ){
   79710     case SQLITE_INTEGER: z = "integer"; break;
   79711     case SQLITE_TEXT:    z = "text";    break;
   79712     case SQLITE_FLOAT:   z = "real";    break;
   79713     case SQLITE_BLOB:    z = "blob";    break;
   79714     default:             z = "null";    break;
   79715   }
   79716   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
   79717 }
   79718 
   79719 
   79720 /*
   79721 ** Implementation of the length() function
   79722 */
   79723 static void lengthFunc(
   79724   sqlite3_context *context,
   79725   int argc,
   79726   sqlite3_value **argv
   79727 ){
   79728   int len;
   79729 
   79730   assert( argc==1 );
   79731   UNUSED_PARAMETER(argc);
   79732   switch( sqlite3_value_type(argv[0]) ){
   79733     case SQLITE_BLOB:
   79734     case SQLITE_INTEGER:
   79735     case SQLITE_FLOAT: {
   79736       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
   79737       break;
   79738     }
   79739     case SQLITE_TEXT: {
   79740       const unsigned char *z = sqlite3_value_text(argv[0]);
   79741       if( z==0 ) return;
   79742       len = 0;
   79743       while( *z ){
   79744         len++;
   79745         SQLITE_SKIP_UTF8(z);
   79746       }
   79747       sqlite3_result_int(context, len);
   79748       break;
   79749     }
   79750     default: {
   79751       sqlite3_result_null(context);
   79752       break;
   79753     }
   79754   }
   79755 }
   79756 
   79757 /*
   79758 ** Implementation of the abs() function.
   79759 **
   79760 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
   79761 ** the numeric argument X.
   79762 */
   79763 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   79764   assert( argc==1 );
   79765   UNUSED_PARAMETER(argc);
   79766   switch( sqlite3_value_type(argv[0]) ){
   79767     case SQLITE_INTEGER: {
   79768       i64 iVal = sqlite3_value_int64(argv[0]);
   79769       if( iVal<0 ){
   79770         if( (iVal<<1)==0 ){
   79771           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
   79772           ** abs(X) throws an integer overflow error since there is no
   79773           ** equivalent positive 64-bit two complement value. */
   79774           sqlite3_result_error(context, "integer overflow", -1);
   79775           return;
   79776         }
   79777         iVal = -iVal;
   79778       }
   79779       sqlite3_result_int64(context, iVal);
   79780       break;
   79781     }
   79782     case SQLITE_NULL: {
   79783       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
   79784       sqlite3_result_null(context);
   79785       break;
   79786     }
   79787     default: {
   79788       /* Because sqlite3_value_double() returns 0.0 if the argument is not
   79789       ** something that can be converted into a number, we have:
   79790       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
   79791       ** cannot be converted to a numeric value.
   79792       */
   79793       double rVal = sqlite3_value_double(argv[0]);
   79794       if( rVal<0 ) rVal = -rVal;
   79795       sqlite3_result_double(context, rVal);
   79796       break;
   79797     }
   79798   }
   79799 }
   79800 
   79801 /*
   79802 ** Implementation of the substr() function.
   79803 **
   79804 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
   79805 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
   79806 ** of x.  If x is text, then we actually count UTF-8 characters.
   79807 ** If x is a blob, then we count bytes.
   79808 **
   79809 ** If p1 is negative, then we begin abs(p1) from the end of x[].
   79810 **
   79811 ** If p2 is negative, return the p2 characters preceeding p1.
   79812 */
   79813 static void substrFunc(
   79814   sqlite3_context *context,
   79815   int argc,
   79816   sqlite3_value **argv
   79817 ){
   79818   const unsigned char *z;
   79819   const unsigned char *z2;
   79820   int len;
   79821   int p0type;
   79822   i64 p1, p2;
   79823   int negP2 = 0;
   79824 
   79825   assert( argc==3 || argc==2 );
   79826   if( sqlite3_value_type(argv[1])==SQLITE_NULL
   79827    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
   79828   ){
   79829     return;
   79830   }
   79831   p0type = sqlite3_value_type(argv[0]);
   79832   p1 = sqlite3_value_int(argv[1]);
   79833   if( p0type==SQLITE_BLOB ){
   79834     len = sqlite3_value_bytes(argv[0]);
   79835     z = sqlite3_value_blob(argv[0]);
   79836     if( z==0 ) return;
   79837     assert( len==sqlite3_value_bytes(argv[0]) );
   79838   }else{
   79839     z = sqlite3_value_text(argv[0]);
   79840     if( z==0 ) return;
   79841     len = 0;
   79842     if( p1<0 ){
   79843       for(z2=z; *z2; len++){
   79844         SQLITE_SKIP_UTF8(z2);
   79845       }
   79846     }
   79847   }
   79848   if( argc==3 ){
   79849     p2 = sqlite3_value_int(argv[2]);
   79850     if( p2<0 ){
   79851       p2 = -p2;
   79852       negP2 = 1;
   79853     }
   79854   }else{
   79855     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
   79856   }
   79857   if( p1<0 ){
   79858     p1 += len;
   79859     if( p1<0 ){
   79860       p2 += p1;
   79861       if( p2<0 ) p2 = 0;
   79862       p1 = 0;
   79863     }
   79864   }else if( p1>0 ){
   79865     p1--;
   79866   }else if( p2>0 ){
   79867     p2--;
   79868   }
   79869   if( negP2 ){
   79870     p1 -= p2;
   79871     if( p1<0 ){
   79872       p2 += p1;
   79873       p1 = 0;
   79874     }
   79875   }
   79876   assert( p1>=0 && p2>=0 );
   79877   if( p0type!=SQLITE_BLOB ){
   79878     while( *z && p1 ){
   79879       SQLITE_SKIP_UTF8(z);
   79880       p1--;
   79881     }
   79882     for(z2=z; *z2 && p2; p2--){
   79883       SQLITE_SKIP_UTF8(z2);
   79884     }
   79885     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
   79886   }else{
   79887     if( p1+p2>len ){
   79888       p2 = len-p1;
   79889       if( p2<0 ) p2 = 0;
   79890     }
   79891     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
   79892   }
   79893 }
   79894 
   79895 /*
   79896 ** Implementation of the round() function
   79897 */
   79898 #ifndef SQLITE_OMIT_FLOATING_POINT
   79899 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   79900   int n = 0;
   79901   double r;
   79902   char *zBuf;
   79903   assert( argc==1 || argc==2 );
   79904   if( argc==2 ){
   79905     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
   79906     n = sqlite3_value_int(argv[1]);
   79907     if( n>30 ) n = 30;
   79908     if( n<0 ) n = 0;
   79909   }
   79910   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   79911   r = sqlite3_value_double(argv[0]);
   79912   /* If Y==0 and X will fit in a 64-bit int,
   79913   ** handle the rounding directly,
   79914   ** otherwise use printf.
   79915   */
   79916   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
   79917     r = (double)((sqlite_int64)(r+0.5));
   79918   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
   79919     r = -(double)((sqlite_int64)((-r)+0.5));
   79920   }else{
   79921     zBuf = sqlite3_mprintf("%.*f",n,r);
   79922     if( zBuf==0 ){
   79923       sqlite3_result_error_nomem(context);
   79924       return;
   79925     }
   79926     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
   79927     sqlite3_free(zBuf);
   79928   }
   79929   sqlite3_result_double(context, r);
   79930 }
   79931 #endif
   79932 
   79933 /*
   79934 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
   79935 ** allocation fails, call sqlite3_result_error_nomem() to notify
   79936 ** the database handle that malloc() has failed and return NULL.
   79937 ** If nByte is larger than the maximum string or blob length, then
   79938 ** raise an SQLITE_TOOBIG exception and return NULL.
   79939 */
   79940 static void *contextMalloc(sqlite3_context *context, i64 nByte){
   79941   char *z;
   79942   sqlite3 *db = sqlite3_context_db_handle(context);
   79943   assert( nByte>0 );
   79944   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
   79945   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   79946   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   79947     sqlite3_result_error_toobig(context);
   79948     z = 0;
   79949   }else{
   79950     z = sqlite3Malloc((int)nByte);
   79951     if( !z ){
   79952       sqlite3_result_error_nomem(context);
   79953     }
   79954   }
   79955   return z;
   79956 }
   79957 
   79958 /*
   79959 ** Implementation of the upper() and lower() SQL functions.
   79960 */
   79961 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   79962   char *z1;
   79963   const char *z2;
   79964   int i, n;
   79965   UNUSED_PARAMETER(argc);
   79966   z2 = (char*)sqlite3_value_text(argv[0]);
   79967   n = sqlite3_value_bytes(argv[0]);
   79968   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   79969   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   79970   if( z2 ){
   79971     z1 = contextMalloc(context, ((i64)n)+1);
   79972     if( z1 ){
   79973       memcpy(z1, z2, n+1);
   79974       for(i=0; z1[i]; i++){
   79975         z1[i] = (char)sqlite3Toupper(z1[i]);
   79976       }
   79977       sqlite3_result_text(context, z1, -1, sqlite3_free);
   79978     }
   79979   }
   79980 }
   79981 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   79982   u8 *z1;
   79983   const char *z2;
   79984   int i, n;
   79985   UNUSED_PARAMETER(argc);
   79986   z2 = (char*)sqlite3_value_text(argv[0]);
   79987   n = sqlite3_value_bytes(argv[0]);
   79988   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
   79989   assert( z2==(char*)sqlite3_value_text(argv[0]) );
   79990   if( z2 ){
   79991     z1 = contextMalloc(context, ((i64)n)+1);
   79992     if( z1 ){
   79993       memcpy(z1, z2, n+1);
   79994       for(i=0; z1[i]; i++){
   79995         z1[i] = sqlite3Tolower(z1[i]);
   79996       }
   79997       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
   79998     }
   79999   }
   80000 }
   80001 
   80002 
   80003 #if 0  /* This function is never used. */
   80004 /*
   80005 ** The COALESCE() and IFNULL() functions used to be implemented as shown
   80006 ** here.  But now they are implemented as VDBE code so that unused arguments
   80007 ** do not have to be computed.  This legacy implementation is retained as
   80008 ** comment.
   80009 */
   80010 /*
   80011 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
   80012 ** All three do the same thing.  They return the first non-NULL
   80013 ** argument.
   80014 */
   80015 static void ifnullFunc(
   80016   sqlite3_context *context,
   80017   int argc,
   80018   sqlite3_value **argv
   80019 ){
   80020   int i;
   80021   for(i=0; i<argc; i++){
   80022     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
   80023       sqlite3_result_value(context, argv[i]);
   80024       break;
   80025     }
   80026   }
   80027 }
   80028 #endif /* NOT USED */
   80029 #define ifnullFunc versionFunc   /* Substitute function - never called */
   80030 
   80031 /*
   80032 ** Implementation of random().  Return a random integer.
   80033 */
   80034 static void randomFunc(
   80035   sqlite3_context *context,
   80036   int NotUsed,
   80037   sqlite3_value **NotUsed2
   80038 ){
   80039   sqlite_int64 r;
   80040   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80041   sqlite3_randomness(sizeof(r), &r);
   80042   if( r<0 ){
   80043     /* We need to prevent a random number of 0x8000000000000000
   80044     ** (or -9223372036854775808) since when you do abs() of that
   80045     ** number of you get the same value back again.  To do this
   80046     ** in a way that is testable, mask the sign bit off of negative
   80047     ** values, resulting in a positive value.  Then take the
   80048     ** 2s complement of that positive value.  The end result can
   80049     ** therefore be no less than -9223372036854775807.
   80050     */
   80051     r = -(r ^ (((sqlite3_int64)1)<<63));
   80052   }
   80053   sqlite3_result_int64(context, r);
   80054 }
   80055 
   80056 /*
   80057 ** Implementation of randomblob(N).  Return a random blob
   80058 ** that is N bytes long.
   80059 */
   80060 static void randomBlob(
   80061   sqlite3_context *context,
   80062   int argc,
   80063   sqlite3_value **argv
   80064 ){
   80065   int n;
   80066   unsigned char *p;
   80067   assert( argc==1 );
   80068   UNUSED_PARAMETER(argc);
   80069   n = sqlite3_value_int(argv[0]);
   80070   if( n<1 ){
   80071     n = 1;
   80072   }
   80073   p = contextMalloc(context, n);
   80074   if( p ){
   80075     sqlite3_randomness(n, p);
   80076     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
   80077   }
   80078 }
   80079 
   80080 /*
   80081 ** Implementation of the last_insert_rowid() SQL function.  The return
   80082 ** value is the same as the sqlite3_last_insert_rowid() API function.
   80083 */
   80084 static void last_insert_rowid(
   80085   sqlite3_context *context,
   80086   int NotUsed,
   80087   sqlite3_value **NotUsed2
   80088 ){
   80089   sqlite3 *db = sqlite3_context_db_handle(context);
   80090   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80091   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
   80092   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
   80093   ** function. */
   80094   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
   80095 }
   80096 
   80097 /*
   80098 ** Implementation of the changes() SQL function.
   80099 **
   80100 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
   80101 ** around the sqlite3_changes() C/C++ function and hence follows the same
   80102 ** rules for counting changes.
   80103 */
   80104 static void changes(
   80105   sqlite3_context *context,
   80106   int NotUsed,
   80107   sqlite3_value **NotUsed2
   80108 ){
   80109   sqlite3 *db = sqlite3_context_db_handle(context);
   80110   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80111   sqlite3_result_int(context, sqlite3_changes(db));
   80112 }
   80113 
   80114 /*
   80115 ** Implementation of the total_changes() SQL function.  The return value is
   80116 ** the same as the sqlite3_total_changes() API function.
   80117 */
   80118 static void total_changes(
   80119   sqlite3_context *context,
   80120   int NotUsed,
   80121   sqlite3_value **NotUsed2
   80122 ){
   80123   sqlite3 *db = sqlite3_context_db_handle(context);
   80124   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80125   /* IMP: R-52756-41993 This function is a wrapper around the
   80126   ** sqlite3_total_changes() C/C++ interface. */
   80127   sqlite3_result_int(context, sqlite3_total_changes(db));
   80128 }
   80129 
   80130 /*
   80131 ** A structure defining how to do GLOB-style comparisons.
   80132 */
   80133 struct compareInfo {
   80134   u8 matchAll;
   80135   u8 matchOne;
   80136   u8 matchSet;
   80137   u8 noCase;
   80138 };
   80139 
   80140 /*
   80141 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   80142 ** character is exactly one byte in size.  Also, all characters are
   80143 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   80144 ** whereas only characters less than 0x80 do in ASCII.
   80145 */
   80146 #if defined(SQLITE_EBCDIC)
   80147 # define sqlite3Utf8Read(A,C)    (*(A++))
   80148 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
   80149 #else
   80150 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
   80151 #endif
   80152 
   80153 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   80154 /* The correct SQL-92 behavior is for the LIKE operator to ignore
   80155 ** case.  Thus  'a' LIKE 'A' would be true. */
   80156 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   80157 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   80158 ** is case sensitive causing 'a' LIKE 'A' to be false */
   80159 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   80160 
   80161 /*
   80162 ** Compare two UTF-8 strings for equality where the first string can
   80163 ** potentially be a "glob" expression.  Return true (1) if they
   80164 ** are the same and false (0) if they are different.
   80165 **
   80166 ** Globbing rules:
   80167 **
   80168 **      '*'       Matches any sequence of zero or more characters.
   80169 **
   80170 **      '?'       Matches exactly one character.
   80171 **
   80172 **     [...]      Matches one character from the enclosed list of
   80173 **                characters.
   80174 **
   80175 **     [^...]     Matches one character not in the enclosed list.
   80176 **
   80177 ** With the [...] and [^...] matching, a ']' character can be included
   80178 ** in the list by making it the first character after '[' or '^'.  A
   80179 ** range of characters can be specified using '-'.  Example:
   80180 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   80181 ** it the last character in the list.
   80182 **
   80183 ** This routine is usually quick, but can be N**2 in the worst case.
   80184 **
   80185 ** Hints: to match '*' or '?', put them in "[]".  Like this:
   80186 **
   80187 **         abc[*]xyz        Matches "abc*xyz" only
   80188 */
   80189 static int patternCompare(
   80190   const u8 *zPattern,              /* The glob pattern */
   80191   const u8 *zString,               /* The string to compare against the glob */
   80192   const struct compareInfo *pInfo, /* Information about how to do the compare */
   80193   const int esc                    /* The escape character */
   80194 ){
   80195   int c, c2;
   80196   int invert;
   80197   int seen;
   80198   u8 matchOne = pInfo->matchOne;
   80199   u8 matchAll = pInfo->matchAll;
   80200   u8 matchSet = pInfo->matchSet;
   80201   u8 noCase = pInfo->noCase;
   80202   int prevEscape = 0;     /* True if the previous character was 'escape' */
   80203 
   80204   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
   80205     if( !prevEscape && c==matchAll ){
   80206       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
   80207                || c == matchOne ){
   80208         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
   80209           return 0;
   80210         }
   80211       }
   80212       if( c==0 ){
   80213         return 1;
   80214       }else if( c==esc ){
   80215         c = sqlite3Utf8Read(zPattern, &zPattern);
   80216         if( c==0 ){
   80217           return 0;
   80218         }
   80219       }else if( c==matchSet ){
   80220         assert( esc==0 );         /* This is GLOB, not LIKE */
   80221         assert( matchSet<0x80 );  /* '[' is a single-byte character */
   80222         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   80223           SQLITE_SKIP_UTF8(zString);
   80224         }
   80225         return *zString!=0;
   80226       }
   80227       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
   80228         if( noCase ){
   80229           GlogUpperToLower(c2);
   80230           GlogUpperToLower(c);
   80231           while( c2 != 0 && c2 != c ){
   80232             c2 = sqlite3Utf8Read(zString, &zString);
   80233             GlogUpperToLower(c2);
   80234           }
   80235         }else{
   80236           while( c2 != 0 && c2 != c ){
   80237             c2 = sqlite3Utf8Read(zString, &zString);
   80238           }
   80239         }
   80240         if( c2==0 ) return 0;
   80241         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   80242       }
   80243       return 0;
   80244     }else if( !prevEscape && c==matchOne ){
   80245       if( sqlite3Utf8Read(zString, &zString)==0 ){
   80246         return 0;
   80247       }
   80248     }else if( c==matchSet ){
   80249       int prior_c = 0;
   80250       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   80251       seen = 0;
   80252       invert = 0;
   80253       c = sqlite3Utf8Read(zString, &zString);
   80254       if( c==0 ) return 0;
   80255       c2 = sqlite3Utf8Read(zPattern, &zPattern);
   80256       if( c2=='^' ){
   80257         invert = 1;
   80258         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   80259       }
   80260       if( c2==']' ){
   80261         if( c==']' ) seen = 1;
   80262         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   80263       }
   80264       while( c2 && c2!=']' ){
   80265         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
   80266           c2 = sqlite3Utf8Read(zPattern, &zPattern);
   80267           if( c>=prior_c && c<=c2 ) seen = 1;
   80268           prior_c = 0;
   80269         }else{
   80270           if( c==c2 ){
   80271             seen = 1;
   80272           }
   80273           prior_c = c2;
   80274         }
   80275         c2 = sqlite3Utf8Read(zPattern, &zPattern);
   80276       }
   80277       if( c2==0 || (seen ^ invert)==0 ){
   80278         return 0;
   80279       }
   80280     }else if( esc==c && !prevEscape ){
   80281       prevEscape = 1;
   80282     }else{
   80283       c2 = sqlite3Utf8Read(zString, &zString);
   80284       if( noCase ){
   80285         GlogUpperToLower(c);
   80286         GlogUpperToLower(c2);
   80287       }
   80288       if( c!=c2 ){
   80289         return 0;
   80290       }
   80291       prevEscape = 0;
   80292     }
   80293   }
   80294   return *zString==0;
   80295 }
   80296 
   80297 /*
   80298 ** Count the number of times that the LIKE operator (or GLOB which is
   80299 ** just a variation of LIKE) gets called.  This is used for testing
   80300 ** only.
   80301 */
   80302 #ifdef SQLITE_TEST
   80303 SQLITE_API int sqlite3_like_count = 0;
   80304 #endif
   80305 
   80306 
   80307 /*
   80308 ** Implementation of the like() SQL function.  This function implements
   80309 ** the build-in LIKE operator.  The first argument to the function is the
   80310 ** pattern and the second argument is the string.  So, the SQL statements:
   80311 **
   80312 **       A LIKE B
   80313 **
   80314 ** is implemented as like(B,A).
   80315 **
   80316 ** This same function (with a different compareInfo structure) computes
   80317 ** the GLOB operator.
   80318 */
   80319 static void likeFunc(
   80320   sqlite3_context *context,
   80321   int argc,
   80322   sqlite3_value **argv
   80323 ){
   80324   const unsigned char *zA, *zB;
   80325   int escape = 0;
   80326   int nPat;
   80327   sqlite3 *db = sqlite3_context_db_handle(context);
   80328 
   80329   zB = sqlite3_value_text(argv[0]);
   80330   zA = sqlite3_value_text(argv[1]);
   80331 
   80332   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   80333   ** of deep recursion and N*N behavior in patternCompare().
   80334   */
   80335   nPat = sqlite3_value_bytes(argv[0]);
   80336   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
   80337   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
   80338   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
   80339     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   80340     return;
   80341   }
   80342   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
   80343 
   80344   if( argc==3 ){
   80345     /* The escape character string must consist of a single UTF-8 character.
   80346     ** Otherwise, return an error.
   80347     */
   80348     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
   80349     if( zEsc==0 ) return;
   80350     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
   80351       sqlite3_result_error(context,
   80352           "ESCAPE expression must be a single character", -1);
   80353       return;
   80354     }
   80355     escape = sqlite3Utf8Read(zEsc, &zEsc);
   80356   }
   80357   if( zA && zB ){
   80358     struct compareInfo *pInfo = sqlite3_user_data(context);
   80359 #ifdef SQLITE_TEST
   80360     sqlite3_like_count++;
   80361 #endif
   80362 
   80363     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
   80364   }
   80365 }
   80366 
   80367 /*
   80368 ** Implementation of the NULLIF(x,y) function.  The result is the first
   80369 ** argument if the arguments are different.  The result is NULL if the
   80370 ** arguments are equal to each other.
   80371 */
   80372 static void nullifFunc(
   80373   sqlite3_context *context,
   80374   int NotUsed,
   80375   sqlite3_value **argv
   80376 ){
   80377   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   80378   UNUSED_PARAMETER(NotUsed);
   80379   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
   80380     sqlite3_result_value(context, argv[0]);
   80381   }
   80382 }
   80383 
   80384 /*
   80385 ** Implementation of the sqlite_version() function.  The result is the version
   80386 ** of the SQLite library that is running.
   80387 */
   80388 static void versionFunc(
   80389   sqlite3_context *context,
   80390   int NotUsed,
   80391   sqlite3_value **NotUsed2
   80392 ){
   80393   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80394   /* IMP: R-48699-48617 This function is an SQL wrapper around the
   80395   ** sqlite3_libversion() C-interface. */
   80396   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
   80397 }
   80398 
   80399 /*
   80400 ** Implementation of the sqlite_source_id() function. The result is a string
   80401 ** that identifies the particular version of the source code used to build
   80402 ** SQLite.
   80403 */
   80404 static void sourceidFunc(
   80405   sqlite3_context *context,
   80406   int NotUsed,
   80407   sqlite3_value **NotUsed2
   80408 ){
   80409   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   80410   /* IMP: R-24470-31136 This function is an SQL wrapper around the
   80411   ** sqlite3_sourceid() C interface. */
   80412   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
   80413 }
   80414 
   80415 /*
   80416 ** Implementation of the sqlite_compileoption_used() function.
   80417 ** The result is an integer that identifies if the compiler option
   80418 ** was used to build SQLite.
   80419 */
   80420 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   80421 static void compileoptionusedFunc(
   80422   sqlite3_context *context,
   80423   int argc,
   80424   sqlite3_value **argv
   80425 ){
   80426   const char *zOptName;
   80427   assert( argc==1 );
   80428   UNUSED_PARAMETER(argc);
   80429   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
   80430   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
   80431   ** function.
   80432   */
   80433   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
   80434     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
   80435   }
   80436 }
   80437 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   80438 
   80439 /*
   80440 ** Implementation of the sqlite_compileoption_get() function.
   80441 ** The result is a string that identifies the compiler options
   80442 ** used to build SQLite.
   80443 */
   80444 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   80445 static void compileoptiongetFunc(
   80446   sqlite3_context *context,
   80447   int argc,
   80448   sqlite3_value **argv
   80449 ){
   80450   int n;
   80451   assert( argc==1 );
   80452   UNUSED_PARAMETER(argc);
   80453   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
   80454   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
   80455   */
   80456   n = sqlite3_value_int(argv[0]);
   80457   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
   80458 }
   80459 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   80460 
   80461 /* Array for converting from half-bytes (nybbles) into ASCII hex
   80462 ** digits. */
   80463 static const char hexdigits[] = {
   80464   '0', '1', '2', '3', '4', '5', '6', '7',
   80465   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
   80466 };
   80467 
   80468 /*
   80469 ** EXPERIMENTAL - This is not an official function.  The interface may
   80470 ** change.  This function may disappear.  Do not write code that depends
   80471 ** on this function.
   80472 **
   80473 ** Implementation of the QUOTE() function.  This function takes a single
   80474 ** argument.  If the argument is numeric, the return value is the same as
   80475 ** the argument.  If the argument is NULL, the return value is the string
   80476 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
   80477 ** single-quote escapes.
   80478 */
   80479 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   80480   assert( argc==1 );
   80481   UNUSED_PARAMETER(argc);
   80482   switch( sqlite3_value_type(argv[0]) ){
   80483     case SQLITE_INTEGER:
   80484     case SQLITE_FLOAT: {
   80485       sqlite3_result_value(context, argv[0]);
   80486       break;
   80487     }
   80488     case SQLITE_BLOB: {
   80489       char *zText = 0;
   80490       char const *zBlob = sqlite3_value_blob(argv[0]);
   80491       int nBlob = sqlite3_value_bytes(argv[0]);
   80492       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
   80493       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
   80494       if( zText ){
   80495         int i;
   80496         for(i=0; i<nBlob; i++){
   80497           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
   80498           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
   80499         }
   80500         zText[(nBlob*2)+2] = '\'';
   80501         zText[(nBlob*2)+3] = '\0';
   80502         zText[0] = 'X';
   80503         zText[1] = '\'';
   80504         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
   80505         sqlite3_free(zText);
   80506       }
   80507       break;
   80508     }
   80509     case SQLITE_TEXT: {
   80510       int i,j;
   80511       u64 n;
   80512       const unsigned char *zArg = sqlite3_value_text(argv[0]);
   80513       char *z;
   80514 
   80515       if( zArg==0 ) return;
   80516       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
   80517       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
   80518       if( z ){
   80519         z[0] = '\'';
   80520         for(i=0, j=1; zArg[i]; i++){
   80521           z[j++] = zArg[i];
   80522           if( zArg[i]=='\'' ){
   80523             z[j++] = '\'';
   80524           }
   80525         }
   80526         z[j++] = '\'';
   80527         z[j] = 0;
   80528         sqlite3_result_text(context, z, j, sqlite3_free);
   80529       }
   80530       break;
   80531     }
   80532     default: {
   80533       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
   80534       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
   80535       break;
   80536     }
   80537   }
   80538 }
   80539 
   80540 /*
   80541 ** The hex() function.  Interpret the argument as a blob.  Return
   80542 ** a hexadecimal rendering as text.
   80543 */
   80544 static void hexFunc(
   80545   sqlite3_context *context,
   80546   int argc,
   80547   sqlite3_value **argv
   80548 ){
   80549   int i, n;
   80550   const unsigned char *pBlob;
   80551   char *zHex, *z;
   80552   assert( argc==1 );
   80553   UNUSED_PARAMETER(argc);
   80554   pBlob = sqlite3_value_blob(argv[0]);
   80555   n = sqlite3_value_bytes(argv[0]);
   80556   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
   80557   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
   80558   if( zHex ){
   80559     for(i=0; i<n; i++, pBlob++){
   80560       unsigned char c = *pBlob;
   80561       *(z++) = hexdigits[(c>>4)&0xf];
   80562       *(z++) = hexdigits[c&0xf];
   80563     }
   80564     *z = 0;
   80565     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
   80566   }
   80567 }
   80568 
   80569 /*
   80570 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
   80571 */
   80572 static void zeroblobFunc(
   80573   sqlite3_context *context,
   80574   int argc,
   80575   sqlite3_value **argv
   80576 ){
   80577   i64 n;
   80578   sqlite3 *db = sqlite3_context_db_handle(context);
   80579   assert( argc==1 );
   80580   UNUSED_PARAMETER(argc);
   80581   n = sqlite3_value_int64(argv[0]);
   80582   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
   80583   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
   80584   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   80585     sqlite3_result_error_toobig(context);
   80586   }else{
   80587     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
   80588   }
   80589 }
   80590 
   80591 /*
   80592 ** The replace() function.  Three arguments are all strings: call
   80593 ** them A, B, and C. The result is also a string which is derived
   80594 ** from A by replacing every occurance of B with C.  The match
   80595 ** must be exact.  Collating sequences are not used.
   80596 */
   80597 static void replaceFunc(
   80598   sqlite3_context *context,
   80599   int argc,
   80600   sqlite3_value **argv
   80601 ){
   80602   const unsigned char *zStr;        /* The input string A */
   80603   const unsigned char *zPattern;    /* The pattern string B */
   80604   const unsigned char *zRep;        /* The replacement string C */
   80605   unsigned char *zOut;              /* The output */
   80606   int nStr;                /* Size of zStr */
   80607   int nPattern;            /* Size of zPattern */
   80608   int nRep;                /* Size of zRep */
   80609   i64 nOut;                /* Maximum size of zOut */
   80610   int loopLimit;           /* Last zStr[] that might match zPattern[] */
   80611   int i, j;                /* Loop counters */
   80612 
   80613   assert( argc==3 );
   80614   UNUSED_PARAMETER(argc);
   80615   zStr = sqlite3_value_text(argv[0]);
   80616   if( zStr==0 ) return;
   80617   nStr = sqlite3_value_bytes(argv[0]);
   80618   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
   80619   zPattern = sqlite3_value_text(argv[1]);
   80620   if( zPattern==0 ){
   80621     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
   80622             || sqlite3_context_db_handle(context)->mallocFailed );
   80623     return;
   80624   }
   80625   if( zPattern[0]==0 ){
   80626     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
   80627     sqlite3_result_value(context, argv[0]);
   80628     return;
   80629   }
   80630   nPattern = sqlite3_value_bytes(argv[1]);
   80631   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
   80632   zRep = sqlite3_value_text(argv[2]);
   80633   if( zRep==0 ) return;
   80634   nRep = sqlite3_value_bytes(argv[2]);
   80635   assert( zRep==sqlite3_value_text(argv[2]) );
   80636   nOut = nStr + 1;
   80637   assert( nOut<SQLITE_MAX_LENGTH );
   80638   zOut = contextMalloc(context, (i64)nOut);
   80639   if( zOut==0 ){
   80640     return;
   80641   }
   80642   loopLimit = nStr - nPattern;
   80643   for(i=j=0; i<=loopLimit; i++){
   80644     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
   80645       zOut[j++] = zStr[i];
   80646     }else{
   80647       u8 *zOld;
   80648       sqlite3 *db = sqlite3_context_db_handle(context);
   80649       nOut += nRep - nPattern;
   80650       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
   80651       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
   80652       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
   80653         sqlite3_result_error_toobig(context);
   80654         sqlite3_free(zOut);
   80655         return;
   80656       }
   80657       zOld = zOut;
   80658       zOut = sqlite3_realloc(zOut, (int)nOut);
   80659       if( zOut==0 ){
   80660         sqlite3_result_error_nomem(context);
   80661         sqlite3_free(zOld);
   80662         return;
   80663       }
   80664       memcpy(&zOut[j], zRep, nRep);
   80665       j += nRep;
   80666       i += nPattern-1;
   80667     }
   80668   }
   80669   assert( j+nStr-i+1==nOut );
   80670   memcpy(&zOut[j], &zStr[i], nStr-i);
   80671   j += nStr - i;
   80672   assert( j<=nOut );
   80673   zOut[j] = 0;
   80674   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
   80675 }
   80676 
   80677 /*
   80678 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
   80679 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
   80680 */
   80681 static void trimFunc(
   80682   sqlite3_context *context,
   80683   int argc,
   80684   sqlite3_value **argv
   80685 ){
   80686   const unsigned char *zIn;         /* Input string */
   80687   const unsigned char *zCharSet;    /* Set of characters to trim */
   80688   int nIn;                          /* Number of bytes in input */
   80689   int flags;                        /* 1: trimleft  2: trimright  3: trim */
   80690   int i;                            /* Loop counter */
   80691   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
   80692   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
   80693   int nChar;                        /* Number of characters in zCharSet */
   80694 
   80695   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
   80696     return;
   80697   }
   80698   zIn = sqlite3_value_text(argv[0]);
   80699   if( zIn==0 ) return;
   80700   nIn = sqlite3_value_bytes(argv[0]);
   80701   assert( zIn==sqlite3_value_text(argv[0]) );
   80702   if( argc==1 ){
   80703     static const unsigned char lenOne[] = { 1 };
   80704     static unsigned char * const azOne[] = { (u8*)" " };
   80705     nChar = 1;
   80706     aLen = (u8*)lenOne;
   80707     azChar = (unsigned char **)azOne;
   80708     zCharSet = 0;
   80709   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
   80710     return;
   80711   }else{
   80712     const unsigned char *z;
   80713     for(z=zCharSet, nChar=0; *z; nChar++){
   80714       SQLITE_SKIP_UTF8(z);
   80715     }
   80716     if( nChar>0 ){
   80717       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
   80718       if( azChar==0 ){
   80719         return;
   80720       }
   80721       aLen = (unsigned char*)&azChar[nChar];
   80722       for(z=zCharSet, nChar=0; *z; nChar++){
   80723         azChar[nChar] = (unsigned char *)z;
   80724         SQLITE_SKIP_UTF8(z);
   80725         aLen[nChar] = (u8)(z - azChar[nChar]);
   80726       }
   80727     }
   80728   }
   80729   if( nChar>0 ){
   80730     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
   80731     if( flags & 1 ){
   80732       while( nIn>0 ){
   80733         int len = 0;
   80734         for(i=0; i<nChar; i++){
   80735           len = aLen[i];
   80736           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
   80737         }
   80738         if( i>=nChar ) break;
   80739         zIn += len;
   80740         nIn -= len;
   80741       }
   80742     }
   80743     if( flags & 2 ){
   80744       while( nIn>0 ){
   80745         int len = 0;
   80746         for(i=0; i<nChar; i++){
   80747           len = aLen[i];
   80748           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
   80749         }
   80750         if( i>=nChar ) break;
   80751         nIn -= len;
   80752       }
   80753     }
   80754     if( zCharSet ){
   80755       sqlite3_free(azChar);
   80756     }
   80757   }
   80758   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
   80759 }
   80760 
   80761 
   80762 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
   80763 ** is only available if the SQLITE_SOUNDEX compile-time option is used
   80764 ** when SQLite is built.
   80765 */
   80766 #ifdef SQLITE_SOUNDEX
   80767 /*
   80768 ** Compute the soundex encoding of a word.
   80769 **
   80770 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
   80771 ** soundex encoding of the string X.
   80772 */
   80773 static void soundexFunc(
   80774   sqlite3_context *context,
   80775   int argc,
   80776   sqlite3_value **argv
   80777 ){
   80778   char zResult[8];
   80779   const u8 *zIn;
   80780   int i, j;
   80781   static const unsigned char iCode[] = {
   80782     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   80783     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   80784     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   80785     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
   80786     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   80787     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   80788     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
   80789     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
   80790   };
   80791   assert( argc==1 );
   80792   zIn = (u8*)sqlite3_value_text(argv[0]);
   80793   if( zIn==0 ) zIn = (u8*)"";
   80794   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
   80795   if( zIn[i] ){
   80796     u8 prevcode = iCode[zIn[i]&0x7f];
   80797     zResult[0] = sqlite3Toupper(zIn[i]);
   80798     for(j=1; j<4 && zIn[i]; i++){
   80799       int code = iCode[zIn[i]&0x7f];
   80800       if( code>0 ){
   80801         if( code!=prevcode ){
   80802           prevcode = code;
   80803           zResult[j++] = code + '0';
   80804         }
   80805       }else{
   80806         prevcode = 0;
   80807       }
   80808     }
   80809     while( j<4 ){
   80810       zResult[j++] = '0';
   80811     }
   80812     zResult[j] = 0;
   80813     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
   80814   }else{
   80815     /* IMP: R-64894-50321 The string "?000" is returned if the argument
   80816     ** is NULL or contains no ASCII alphabetic characters. */
   80817     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
   80818   }
   80819 }
   80820 #endif /* SQLITE_SOUNDEX */
   80821 
   80822 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   80823 /*
   80824 ** A function that loads a shared-library extension then returns NULL.
   80825 */
   80826 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
   80827   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
   80828   const char *zProc;
   80829   sqlite3 *db = sqlite3_context_db_handle(context);
   80830   char *zErrMsg = 0;
   80831 
   80832   if( argc==2 ){
   80833     zProc = (const char *)sqlite3_value_text(argv[1]);
   80834   }else{
   80835     zProc = 0;
   80836   }
   80837   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
   80838     sqlite3_result_error(context, zErrMsg, -1);
   80839     sqlite3_free(zErrMsg);
   80840   }
   80841 }
   80842 #endif
   80843 
   80844 
   80845 /*
   80846 ** An instance of the following structure holds the context of a
   80847 ** sum() or avg() aggregate computation.
   80848 */
   80849 typedef struct SumCtx SumCtx;
   80850 struct SumCtx {
   80851   double rSum;      /* Floating point sum */
   80852   i64 iSum;         /* Integer sum */
   80853   i64 cnt;          /* Number of elements summed */
   80854   u8 overflow;      /* True if integer overflow seen */
   80855   u8 approx;        /* True if non-integer value was input to the sum */
   80856 };
   80857 
   80858 /*
   80859 ** Routines used to compute the sum, average, and total.
   80860 **
   80861 ** The SUM() function follows the (broken) SQL standard which means
   80862 ** that it returns NULL if it sums over no inputs.  TOTAL returns
   80863 ** 0.0 in that case.  In addition, TOTAL always returns a float where
   80864 ** SUM might return an integer if it never encounters a floating point
   80865 ** value.  TOTAL never fails, but SUM might through an exception if
   80866 ** it overflows an integer.
   80867 */
   80868 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   80869   SumCtx *p;
   80870   int type;
   80871   assert( argc==1 );
   80872   UNUSED_PARAMETER(argc);
   80873   p = sqlite3_aggregate_context(context, sizeof(*p));
   80874   type = sqlite3_value_numeric_type(argv[0]);
   80875   if( p && type!=SQLITE_NULL ){
   80876     p->cnt++;
   80877     if( type==SQLITE_INTEGER ){
   80878       i64 v = sqlite3_value_int64(argv[0]);
   80879       p->rSum += v;
   80880       if( (p->approx|p->overflow)==0 ){
   80881         i64 iNewSum = p->iSum + v;
   80882         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
   80883         int s2 = (int)(v       >> (sizeof(i64)*8-1));
   80884         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
   80885         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
   80886         p->iSum = iNewSum;
   80887       }
   80888     }else{
   80889       p->rSum += sqlite3_value_double(argv[0]);
   80890       p->approx = 1;
   80891     }
   80892   }
   80893 }
   80894 static void sumFinalize(sqlite3_context *context){
   80895   SumCtx *p;
   80896   p = sqlite3_aggregate_context(context, 0);
   80897   if( p && p->cnt>0 ){
   80898     if( p->overflow ){
   80899       sqlite3_result_error(context,"integer overflow",-1);
   80900     }else if( p->approx ){
   80901       sqlite3_result_double(context, p->rSum);
   80902     }else{
   80903       sqlite3_result_int64(context, p->iSum);
   80904     }
   80905   }
   80906 }
   80907 static void avgFinalize(sqlite3_context *context){
   80908   SumCtx *p;
   80909   p = sqlite3_aggregate_context(context, 0);
   80910   if( p && p->cnt>0 ){
   80911     sqlite3_result_double(context, p->rSum/(double)p->cnt);
   80912   }
   80913 }
   80914 static void totalFinalize(sqlite3_context *context){
   80915   SumCtx *p;
   80916   p = sqlite3_aggregate_context(context, 0);
   80917   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   80918   sqlite3_result_double(context, p ? p->rSum : (double)0);
   80919 }
   80920 
   80921 /*
   80922 ** The following structure keeps track of state information for the
   80923 ** count() aggregate function.
   80924 */
   80925 typedef struct CountCtx CountCtx;
   80926 struct CountCtx {
   80927   i64 n;
   80928 };
   80929 
   80930 /*
   80931 ** Routines to implement the count() aggregate function.
   80932 */
   80933 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
   80934   CountCtx *p;
   80935   p = sqlite3_aggregate_context(context, sizeof(*p));
   80936   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
   80937     p->n++;
   80938   }
   80939 
   80940 #ifndef SQLITE_OMIT_DEPRECATED
   80941   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
   80942   ** sure it still operates correctly, verify that its count agrees with our
   80943   ** internal count when using count(*) and when the total count can be
   80944   ** expressed as a 32-bit integer. */
   80945   assert( argc==1 || p==0 || p->n>0x7fffffff
   80946           || p->n==sqlite3_aggregate_count(context) );
   80947 #endif
   80948 }
   80949 static void countFinalize(sqlite3_context *context){
   80950   CountCtx *p;
   80951   p = sqlite3_aggregate_context(context, 0);
   80952   sqlite3_result_int64(context, p ? p->n : 0);
   80953 }
   80954 
   80955 /*
   80956 ** Routines to implement min() and max() aggregate functions.
   80957 */
   80958 static void minmaxStep(
   80959   sqlite3_context *context,
   80960   int NotUsed,
   80961   sqlite3_value **argv
   80962 ){
   80963   Mem *pArg  = (Mem *)argv[0];
   80964   Mem *pBest;
   80965   UNUSED_PARAMETER(NotUsed);
   80966 
   80967   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   80968   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
   80969   if( !pBest ) return;
   80970 
   80971   if( pBest->flags ){
   80972     int max;
   80973     int cmp;
   80974     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
   80975     /* This step function is used for both the min() and max() aggregates,
   80976     ** the only difference between the two being that the sense of the
   80977     ** comparison is inverted. For the max() aggregate, the
   80978     ** sqlite3_user_data() function returns (void *)-1. For min() it
   80979     ** returns (void *)db, where db is the sqlite3* database pointer.
   80980     ** Therefore the next statement sets variable 'max' to 1 for the max()
   80981     ** aggregate, or 0 for min().
   80982     */
   80983     max = sqlite3_user_data(context)!=0;
   80984     cmp = sqlite3MemCompare(pBest, pArg, pColl);
   80985     if( (max && cmp<0) || (!max && cmp>0) ){
   80986       sqlite3VdbeMemCopy(pBest, pArg);
   80987     }
   80988   }else{
   80989     sqlite3VdbeMemCopy(pBest, pArg);
   80990   }
   80991 }
   80992 static void minMaxFinalize(sqlite3_context *context){
   80993   sqlite3_value *pRes;
   80994   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
   80995   if( pRes ){
   80996     if( ALWAYS(pRes->flags) ){
   80997       sqlite3_result_value(context, pRes);
   80998     }
   80999     sqlite3VdbeMemRelease(pRes);
   81000   }
   81001 }
   81002 
   81003 /*
   81004 ** group_concat(EXPR, ?SEPARATOR?)
   81005 */
   81006 static void groupConcatStep(
   81007   sqlite3_context *context,
   81008   int argc,
   81009   sqlite3_value **argv
   81010 ){
   81011   const char *zVal;
   81012   StrAccum *pAccum;
   81013   const char *zSep;
   81014   int nVal, nSep;
   81015   assert( argc==1 || argc==2 );
   81016   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
   81017   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
   81018 
   81019   if( pAccum ){
   81020     sqlite3 *db = sqlite3_context_db_handle(context);
   81021     int firstTerm = pAccum->useMalloc==0;
   81022     pAccum->useMalloc = 2;
   81023     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
   81024     if( !firstTerm ){
   81025       if( argc==2 ){
   81026         zSep = (char*)sqlite3_value_text(argv[1]);
   81027         nSep = sqlite3_value_bytes(argv[1]);
   81028       }else{
   81029         zSep = ",";
   81030         nSep = 1;
   81031       }
   81032       sqlite3StrAccumAppend(pAccum, zSep, nSep);
   81033     }
   81034     zVal = (char*)sqlite3_value_text(argv[0]);
   81035     nVal = sqlite3_value_bytes(argv[0]);
   81036     sqlite3StrAccumAppend(pAccum, zVal, nVal);
   81037   }
   81038 }
   81039 static void groupConcatFinalize(sqlite3_context *context){
   81040   StrAccum *pAccum;
   81041   pAccum = sqlite3_aggregate_context(context, 0);
   81042   if( pAccum ){
   81043     if( pAccum->tooBig ){
   81044       sqlite3_result_error_toobig(context);
   81045     }else if( pAccum->mallocFailed ){
   81046       sqlite3_result_error_nomem(context);
   81047     }else{
   81048       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
   81049                           sqlite3_free);
   81050     }
   81051   }
   81052 }
   81053 
   81054 /*
   81055 ** This routine does per-connection function registration.  Most
   81056 ** of the built-in functions above are part of the global function set.
   81057 ** This routine only deals with those that are not global.
   81058 */
   81059 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
   81060   int rc = sqlite3_overload_function(db, "MATCH", 2);
   81061   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   81062   if( rc==SQLITE_NOMEM ){
   81063     db->mallocFailed = 1;
   81064   }
   81065 }
   81066 
   81067 /*
   81068 ** Set the LIKEOPT flag on the 2-argument function with the given name.
   81069 */
   81070 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
   81071   FuncDef *pDef;
   81072   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
   81073                              2, SQLITE_UTF8, 0);
   81074   if( ALWAYS(pDef) ){
   81075     pDef->flags = flagVal;
   81076   }
   81077 }
   81078 
   81079 /*
   81080 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
   81081 ** parameter determines whether or not the LIKE operator is case
   81082 ** sensitive.  GLOB is always case sensitive.
   81083 */
   81084 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
   81085   struct compareInfo *pInfo;
   81086   if( caseSensitive ){
   81087     pInfo = (struct compareInfo*)&likeInfoAlt;
   81088   }else{
   81089     pInfo = (struct compareInfo*)&likeInfoNorm;
   81090   }
   81091   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
   81092   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
   81093   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
   81094       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
   81095   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
   81096   setLikeOptFlag(db, "like",
   81097       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
   81098 }
   81099 
   81100 /*
   81101 ** pExpr points to an expression which implements a function.  If
   81102 ** it is appropriate to apply the LIKE optimization to that function
   81103 ** then set aWc[0] through aWc[2] to the wildcard characters and
   81104 ** return TRUE.  If the function is not a LIKE-style function then
   81105 ** return FALSE.
   81106 */
   81107 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
   81108   FuncDef *pDef;
   81109   if( pExpr->op!=TK_FUNCTION
   81110    || !pExpr->x.pList
   81111    || pExpr->x.pList->nExpr!=2
   81112   ){
   81113     return 0;
   81114   }
   81115   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   81116   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
   81117                              sqlite3Strlen30(pExpr->u.zToken),
   81118                              2, SQLITE_UTF8, 0);
   81119   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
   81120     return 0;
   81121   }
   81122 
   81123   /* The memcpy() statement assumes that the wildcard characters are
   81124   ** the first three statements in the compareInfo structure.  The
   81125   ** asserts() that follow verify that assumption
   81126   */
   81127   memcpy(aWc, pDef->pUserData, 3);
   81128   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
   81129   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
   81130   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   81131   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
   81132   return 1;
   81133 }
   81134 
   81135 /*
   81136 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
   81137 ** to the global function hash table.  This occurs at start-time (as
   81138 ** a consequence of calling sqlite3_initialize()).
   81139 **
   81140 ** After this routine runs
   81141 */
   81142 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
   81143   /*
   81144   ** The following array holds FuncDef structures for all of the functions
   81145   ** defined in this file.
   81146   **
   81147   ** The array cannot be constant since changes are made to the
   81148   ** FuncDef.pHash elements at start-time.  The elements of this array
   81149   ** are read-only after initialization is complete.
   81150   */
   81151   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
   81152     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
   81153     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
   81154     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
   81155     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
   81156     FUNCTION(trim,               1, 3, 0, trimFunc         ),
   81157     FUNCTION(trim,               2, 3, 0, trimFunc         ),
   81158     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
   81159     FUNCTION(min,                0, 0, 1, 0                ),
   81160     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
   81161     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
   81162     FUNCTION(max,                0, 1, 1, 0                ),
   81163     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
   81164     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
   81165     FUNCTION(length,             1, 0, 0, lengthFunc       ),
   81166     FUNCTION(substr,             2, 0, 0, substrFunc       ),
   81167     FUNCTION(substr,             3, 0, 0, substrFunc       ),
   81168     FUNCTION(abs,                1, 0, 0, absFunc          ),
   81169 #ifndef SQLITE_OMIT_FLOATING_POINT
   81170     FUNCTION(round,              1, 0, 0, roundFunc        ),
   81171     FUNCTION(round,              2, 0, 0, roundFunc        ),
   81172 #endif
   81173     FUNCTION(upper,              1, 0, 0, upperFunc        ),
   81174     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
   81175     FUNCTION(coalesce,           1, 0, 0, 0                ),
   81176     FUNCTION(coalesce,           0, 0, 0, 0                ),
   81177 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
   81178     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
   81179     FUNCTION(hex,                1, 0, 0, hexFunc          ),
   81180 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
   81181     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
   81182     FUNCTION(random,             0, 0, 0, randomFunc       ),
   81183     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
   81184     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
   81185     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
   81186     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
   81187 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   81188     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
   81189     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
   81190 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   81191     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
   81192     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
   81193     FUNCTION(changes,            0, 0, 0, changes          ),
   81194     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
   81195     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
   81196     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
   81197   #ifdef SQLITE_SOUNDEX
   81198     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
   81199   #endif
   81200   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   81201     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
   81202     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
   81203   #endif
   81204     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
   81205     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
   81206     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
   81207  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
   81208     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
   81209     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
   81210     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
   81211     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
   81212 
   81213     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   81214   #ifdef SQLITE_CASE_SENSITIVE_LIKE
   81215     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   81216     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
   81217   #else
   81218     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
   81219     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
   81220   #endif
   81221   };
   81222 
   81223   int i;
   81224   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   81225   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
   81226 
   81227   for(i=0; i<ArraySize(aBuiltinFunc); i++){
   81228     sqlite3FuncDefInsert(pHash, &aFunc[i]);
   81229   }
   81230   sqlite3RegisterDateTimeFunctions();
   81231 #ifndef SQLITE_OMIT_ALTERTABLE
   81232   sqlite3AlterFunctions();
   81233 #endif
   81234 }
   81235 
   81236 /************** End of func.c ************************************************/
   81237 /************** Begin file fkey.c ********************************************/
   81238 /*
   81239 **
   81240 ** The author disclaims copyright to this source code.  In place of
   81241 ** a legal notice, here is a blessing:
   81242 **
   81243 **    May you do good and not evil.
   81244 **    May you find forgiveness for yourself and forgive others.
   81245 **    May you share freely, never taking more than you give.
   81246 **
   81247 *************************************************************************
   81248 ** This file contains code used by the compiler to add foreign key
   81249 ** support to compiled SQL statements.
   81250 */
   81251 
   81252 #ifndef SQLITE_OMIT_FOREIGN_KEY
   81253 #ifndef SQLITE_OMIT_TRIGGER
   81254 
   81255 /*
   81256 ** Deferred and Immediate FKs
   81257 ** --------------------------
   81258 **
   81259 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
   81260 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
   81261 ** is returned and the current statement transaction rolled back. If a
   81262 ** deferred foreign key constraint is violated, no action is taken
   81263 ** immediately. However if the application attempts to commit the
   81264 ** transaction before fixing the constraint violation, the attempt fails.
   81265 **
   81266 ** Deferred constraints are implemented using a simple counter associated
   81267 ** with the database handle. The counter is set to zero each time a
   81268 ** database transaction is opened. Each time a statement is executed
   81269 ** that causes a foreign key violation, the counter is incremented. Each
   81270 ** time a statement is executed that removes an existing violation from
   81271 ** the database, the counter is decremented. When the transaction is
   81272 ** committed, the commit fails if the current value of the counter is
   81273 ** greater than zero. This scheme has two big drawbacks:
   81274 **
   81275 **   * When a commit fails due to a deferred foreign key constraint,
   81276 **     there is no way to tell which foreign constraint is not satisfied,
   81277 **     or which row it is not satisfied for.
   81278 **
   81279 **   * If the database contains foreign key violations when the
   81280 **     transaction is opened, this may cause the mechanism to malfunction.
   81281 **
   81282 ** Despite these problems, this approach is adopted as it seems simpler
   81283 ** than the alternatives.
   81284 **
   81285 ** INSERT operations:
   81286 **
   81287 **   I.1) For each FK for which the table is the child table, search
   81288 **        the parent table for a match. If none is found increment the
   81289 **        constraint counter.
   81290 **
   81291 **   I.2) For each FK for which the table is the parent table,
   81292 **        search the child table for rows that correspond to the new
   81293 **        row in the parent table. Decrement the counter for each row
   81294 **        found (as the constraint is now satisfied).
   81295 **
   81296 ** DELETE operations:
   81297 **
   81298 **   D.1) For each FK for which the table is the child table,
   81299 **        search the parent table for a row that corresponds to the
   81300 **        deleted row in the child table. If such a row is not found,
   81301 **        decrement the counter.
   81302 **
   81303 **   D.2) For each FK for which the table is the parent table, search
   81304 **        the child table for rows that correspond to the deleted row
   81305 **        in the parent table. For each found increment the counter.
   81306 **
   81307 ** UPDATE operations:
   81308 **
   81309 **   An UPDATE command requires that all 4 steps above are taken, but only
   81310 **   for FK constraints for which the affected columns are actually
   81311 **   modified (values must be compared at runtime).
   81312 **
   81313 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
   81314 ** This simplifies the implementation a bit.
   81315 **
   81316 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
   81317 ** resolution is considered to delete rows before the new row is inserted.
   81318 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
   81319 ** is thrown, even if the FK constraint would be satisfied after the new
   81320 ** row is inserted.
   81321 **
   81322 ** Immediate constraints are usually handled similarly. The only difference
   81323 ** is that the counter used is stored as part of each individual statement
   81324 ** object (struct Vdbe). If, after the statement has run, its immediate
   81325 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
   81326 ** and the statement transaction is rolled back. An exception is an INSERT
   81327 ** statement that inserts a single row only (no triggers). In this case,
   81328 ** instead of using a counter, an exception is thrown immediately if the
   81329 ** INSERT violates a foreign key constraint. This is necessary as such
   81330 ** an INSERT does not open a statement transaction.
   81331 **
   81332 ** TODO: How should dropping a table be handled? How should renaming a
   81333 ** table be handled?
   81334 **
   81335 **
   81336 ** Query API Notes
   81337 ** ---------------
   81338 **
   81339 ** Before coding an UPDATE or DELETE row operation, the code-generator
   81340 ** for those two operations needs to know whether or not the operation
   81341 ** requires any FK processing and, if so, which columns of the original
   81342 ** row are required by the FK processing VDBE code (i.e. if FKs were
   81343 ** implemented using triggers, which of the old.* columns would be
   81344 ** accessed). No information is required by the code-generator before
   81345 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
   81346 ** generation code to query for this information are:
   81347 **
   81348 **   sqlite3FkRequired() - Test to see if FK processing is required.
   81349 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
   81350 **
   81351 **
   81352 ** Externally accessible module functions
   81353 ** --------------------------------------
   81354 **
   81355 **   sqlite3FkCheck()    - Check for foreign key violations.
   81356 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
   81357 **   sqlite3FkDelete()   - Delete an FKey structure.
   81358 */
   81359 
   81360 /*
   81361 ** VDBE Calling Convention
   81362 ** -----------------------
   81363 **
   81364 ** Example:
   81365 **
   81366 **   For the following INSERT statement:
   81367 **
   81368 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
   81369 **     INSERT INTO t1 VALUES(1, 2, 3.1);
   81370 **
   81371 **   Register (x):        2    (type integer)
   81372 **   Register (x+1):      1    (type integer)
   81373 **   Register (x+2):      NULL (type NULL)
   81374 **   Register (x+3):      3.1  (type real)
   81375 */
   81376 
   81377 /*
   81378 ** A foreign key constraint requires that the key columns in the parent
   81379 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
   81380 ** Given that pParent is the parent table for foreign key constraint pFKey,
   81381 ** search the schema a unique index on the parent key columns.
   81382 **
   81383 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
   81384 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
   81385 ** is set to point to the unique index.
   81386 **
   81387 ** If the parent key consists of a single column (the foreign key constraint
   81388 ** is not a composite foreign key), output variable *paiCol is set to NULL.
   81389 ** Otherwise, it is set to point to an allocated array of size N, where
   81390 ** N is the number of columns in the parent key. The first element of the
   81391 ** array is the index of the child table column that is mapped by the FK
   81392 ** constraint to the parent table column stored in the left-most column
   81393 ** of index *ppIdx. The second element of the array is the index of the
   81394 ** child table column that corresponds to the second left-most column of
   81395 ** *ppIdx, and so on.
   81396 **
   81397 ** If the required index cannot be found, either because:
   81398 **
   81399 **   1) The named parent key columns do not exist, or
   81400 **
   81401 **   2) The named parent key columns do exist, but are not subject to a
   81402 **      UNIQUE or PRIMARY KEY constraint, or
   81403 **
   81404 **   3) No parent key columns were provided explicitly as part of the
   81405 **      foreign key definition, and the parent table does not have a
   81406 **      PRIMARY KEY, or
   81407 **
   81408 **   4) No parent key columns were provided explicitly as part of the
   81409 **      foreign key definition, and the PRIMARY KEY of the parent table
   81410 **      consists of a a different number of columns to the child key in
   81411 **      the child table.
   81412 **
   81413 ** then non-zero is returned, and a "foreign key mismatch" error loaded
   81414 ** into pParse. If an OOM error occurs, non-zero is returned and the
   81415 ** pParse->db->mallocFailed flag is set.
   81416 */
   81417 static int locateFkeyIndex(
   81418   Parse *pParse,                  /* Parse context to store any error in */
   81419   Table *pParent,                 /* Parent table of FK constraint pFKey */
   81420   FKey *pFKey,                    /* Foreign key to find index for */
   81421   Index **ppIdx,                  /* OUT: Unique index on parent table */
   81422   int **paiCol                    /* OUT: Map of index columns in pFKey */
   81423 ){
   81424   Index *pIdx = 0;                    /* Value to return via *ppIdx */
   81425   int *aiCol = 0;                     /* Value to return via *paiCol */
   81426   int nCol = pFKey->nCol;             /* Number of columns in parent key */
   81427   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
   81428 
   81429   /* The caller is responsible for zeroing output parameters. */
   81430   assert( ppIdx && *ppIdx==0 );
   81431   assert( !paiCol || *paiCol==0 );
   81432   assert( pParse );
   81433 
   81434   /* If this is a non-composite (single column) foreign key, check if it
   81435   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
   81436   ** and *paiCol set to zero and return early.
   81437   **
   81438   ** Otherwise, for a composite foreign key (more than one column), allocate
   81439   ** space for the aiCol array (returned via output parameter *paiCol).
   81440   ** Non-composite foreign keys do not require the aiCol array.
   81441   */
   81442   if( nCol==1 ){
   81443     /* The FK maps to the IPK if any of the following are true:
   81444     **
   81445     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
   81446     **      mapped to the primary key of table pParent, or
   81447     **   2) The FK is explicitly mapped to a column declared as INTEGER
   81448     **      PRIMARY KEY.
   81449     */
   81450     if( pParent->iPKey>=0 ){
   81451       if( !zKey ) return 0;
   81452       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   81453     }
   81454   }else if( paiCol ){
   81455     assert( nCol>1 );
   81456     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
   81457     if( !aiCol ) return 1;
   81458     *paiCol = aiCol;
   81459   }
   81460 
   81461   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   81462     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
   81463       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
   81464       ** of columns. If each indexed column corresponds to a foreign key
   81465       ** column of pFKey, then this index is a winner.  */
   81466 
   81467       if( zKey==0 ){
   81468         /* If zKey is NULL, then this foreign key is implicitly mapped to
   81469         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
   81470         ** identified by the test (Index.autoIndex==2).  */
   81471         if( pIdx->autoIndex==2 ){
   81472           if( aiCol ){
   81473             int i;
   81474             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
   81475           }
   81476           break;
   81477         }
   81478       }else{
   81479         /* If zKey is non-NULL, then this foreign key was declared to
   81480         ** map to an explicit list of columns in table pParent. Check if this
   81481         ** index matches those columns. Also, check that the index uses
   81482         ** the default collation sequences for each column. */
   81483         int i, j;
   81484         for(i=0; i<nCol; i++){
   81485           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
   81486           char *zDfltColl;                  /* Def. collation for column */
   81487           char *zIdxCol;                    /* Name of indexed column */
   81488 
   81489           /* If the index uses a collation sequence that is different from
   81490           ** the default collation sequence for the column, this index is
   81491           ** unusable. Bail out early in this case.  */
   81492           zDfltColl = pParent->aCol[iCol].zColl;
   81493           if( !zDfltColl ){
   81494             zDfltColl = "BINARY";
   81495           }
   81496           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
   81497 
   81498           zIdxCol = pParent->aCol[iCol].zName;
   81499           for(j=0; j<nCol; j++){
   81500             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
   81501               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
   81502               break;
   81503             }
   81504           }
   81505           if( j==nCol ) break;
   81506         }
   81507         if( i==nCol ) break;      /* pIdx is usable */
   81508       }
   81509     }
   81510   }
   81511 
   81512   if( !pIdx ){
   81513     if( !pParse->disableTriggers ){
   81514       sqlite3ErrorMsg(pParse, "foreign key mismatch");
   81515     }
   81516     sqlite3DbFree(pParse->db, aiCol);
   81517     return 1;
   81518   }
   81519 
   81520   *ppIdx = pIdx;
   81521   return 0;
   81522 }
   81523 
   81524 /*
   81525 ** This function is called when a row is inserted into or deleted from the
   81526 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
   81527 ** on the child table of pFKey, this function is invoked twice for each row
   81528 ** affected - once to "delete" the old row, and then again to "insert" the
   81529 ** new row.
   81530 **
   81531 ** Each time it is called, this function generates VDBE code to locate the
   81532 ** row in the parent table that corresponds to the row being inserted into
   81533 ** or deleted from the child table. If the parent row can be found, no
   81534 ** special action is taken. Otherwise, if the parent row can *not* be
   81535 ** found in the parent table:
   81536 **
   81537 **   Operation | FK type   | Action taken
   81538 **   --------------------------------------------------------------------------
   81539 **   INSERT      immediate   Increment the "immediate constraint counter".
   81540 **
   81541 **   DELETE      immediate   Decrement the "immediate constraint counter".
   81542 **
   81543 **   INSERT      deferred    Increment the "deferred constraint counter".
   81544 **
   81545 **   DELETE      deferred    Decrement the "deferred constraint counter".
   81546 **
   81547 ** These operations are identified in the comment at the top of this file
   81548 ** (fkey.c) as "I.1" and "D.1".
   81549 */
   81550 static void fkLookupParent(
   81551   Parse *pParse,        /* Parse context */
   81552   int iDb,              /* Index of database housing pTab */
   81553   Table *pTab,          /* Parent table of FK pFKey */
   81554   Index *pIdx,          /* Unique index on parent key columns in pTab */
   81555   FKey *pFKey,          /* Foreign key constraint */
   81556   int *aiCol,           /* Map from parent key columns to child table columns */
   81557   int regData,          /* Address of array containing child table row */
   81558   int nIncr,            /* Increment constraint counter by this */
   81559   int isIgnore          /* If true, pretend pTab contains all NULL values */
   81560 ){
   81561   int i;                                    /* Iterator variable */
   81562   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
   81563   int iCur = pParse->nTab - 1;              /* Cursor number to use */
   81564   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
   81565 
   81566   /* If nIncr is less than zero, then check at runtime if there are any
   81567   ** outstanding constraints to resolve. If there are not, there is no need
   81568   ** to check if deleting this row resolves any outstanding violations.
   81569   **
   81570   ** Check if any of the key columns in the child table row are NULL. If
   81571   ** any are, then the constraint is considered satisfied. No need to
   81572   ** search for a matching row in the parent table.  */
   81573   if( nIncr<0 ){
   81574     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
   81575   }
   81576   for(i=0; i<pFKey->nCol; i++){
   81577     int iReg = aiCol[i] + regData + 1;
   81578     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
   81579   }
   81580 
   81581   if( isIgnore==0 ){
   81582     if( pIdx==0 ){
   81583       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   81584       ** column of the parent table (table pTab).  */
   81585       int iMustBeInt;               /* Address of MustBeInt instruction */
   81586       int regTemp = sqlite3GetTempReg(pParse);
   81587 
   81588       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
   81589       ** apply the affinity of the parent key). If this fails, then there
   81590       ** is no matching parent key. Before using MustBeInt, make a copy of
   81591       ** the value. Otherwise, the value inserted into the child key column
   81592       ** will have INTEGER affinity applied to it, which may not be correct.  */
   81593       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   81594       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
   81595 
   81596       /* If the parent table is the same as the child table, and we are about
   81597       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   81598       ** then check if the row being inserted matches itself. If so, do not
   81599       ** increment the constraint-counter.  */
   81600       if( pTab==pFKey->pFrom && nIncr==1 ){
   81601         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
   81602       }
   81603 
   81604       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   81605       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
   81606       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   81607       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   81608       sqlite3VdbeJumpHere(v, iMustBeInt);
   81609       sqlite3ReleaseTempReg(pParse, regTemp);
   81610     }else{
   81611       int nCol = pFKey->nCol;
   81612       int regTemp = sqlite3GetTempRange(pParse, nCol);
   81613       int regRec = sqlite3GetTempReg(pParse);
   81614       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   81615 
   81616       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
   81617       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
   81618       for(i=0; i<nCol; i++){
   81619         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
   81620       }
   81621 
   81622       /* If the parent table is the same as the child table, and we are about
   81623       ** to increment the constraint-counter (i.e. this is an INSERT operation),
   81624       ** then check if the row being inserted matches itself. If so, do not
   81625       ** increment the constraint-counter.  */
   81626       if( pTab==pFKey->pFrom && nIncr==1 ){
   81627         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
   81628         for(i=0; i<nCol; i++){
   81629           int iChild = aiCol[i]+1+regData;
   81630           int iParent = pIdx->aiColumn[i]+1+regData;
   81631           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
   81632         }
   81633         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   81634       }
   81635 
   81636       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
   81637       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   81638       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
   81639 
   81640       sqlite3ReleaseTempReg(pParse, regRec);
   81641       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   81642     }
   81643   }
   81644 
   81645   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   81646     /* Special case: If this is an INSERT statement that will insert exactly
   81647     ** one row into the table, raise a constraint immediately instead of
   81648     ** incrementing a counter. This is necessary as the VM code is being
   81649     ** generated for will not open a statement transaction.  */
   81650     assert( nIncr==1 );
   81651     sqlite3HaltConstraint(
   81652         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   81653     );
   81654   }else{
   81655     if( nIncr>0 && pFKey->isDeferred==0 ){
   81656       sqlite3ParseToplevel(pParse)->mayAbort = 1;
   81657     }
   81658     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   81659   }
   81660 
   81661   sqlite3VdbeResolveLabel(v, iOk);
   81662   sqlite3VdbeAddOp1(v, OP_Close, iCur);
   81663 }
   81664 
   81665 /*
   81666 ** This function is called to generate code executed when a row is deleted
   81667 ** from the parent table of foreign key constraint pFKey and, if pFKey is
   81668 ** deferred, when a row is inserted into the same table. When generating
   81669 ** code for an SQL UPDATE operation, this function may be called twice -
   81670 ** once to "delete" the old row and once to "insert" the new row.
   81671 **
   81672 ** The code generated by this function scans through the rows in the child
   81673 ** table that correspond to the parent table row being deleted or inserted.
   81674 ** For each child row found, one of the following actions is taken:
   81675 **
   81676 **   Operation | FK type   | Action taken
   81677 **   --------------------------------------------------------------------------
   81678 **   DELETE      immediate   Increment the "immediate constraint counter".
   81679 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   81680 **                           throw a "foreign key constraint failed" exception.
   81681 **
   81682 **   INSERT      immediate   Decrement the "immediate constraint counter".
   81683 **
   81684 **   DELETE      deferred    Increment the "deferred constraint counter".
   81685 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
   81686 **                           throw a "foreign key constraint failed" exception.
   81687 **
   81688 **   INSERT      deferred    Decrement the "deferred constraint counter".
   81689 **
   81690 ** These operations are identified in the comment at the top of this file
   81691 ** (fkey.c) as "I.2" and "D.2".
   81692 */
   81693 static void fkScanChildren(
   81694   Parse *pParse,                  /* Parse context */
   81695   SrcList *pSrc,                  /* SrcList containing the table to scan */
   81696   Table *pTab,
   81697   Index *pIdx,                    /* Foreign key index */
   81698   FKey *pFKey,                    /* Foreign key relationship */
   81699   int *aiCol,                     /* Map from pIdx cols to child table cols */
   81700   int regData,                    /* Referenced table data starts here */
   81701   int nIncr                       /* Amount to increment deferred counter by */
   81702 ){
   81703   sqlite3 *db = pParse->db;       /* Database handle */
   81704   int i;                          /* Iterator variable */
   81705   Expr *pWhere = 0;               /* WHERE clause to scan with */
   81706   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   81707   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
   81708   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
   81709   Vdbe *v = sqlite3GetVdbe(pParse);
   81710 
   81711   assert( !pIdx || pIdx->pTable==pTab );
   81712 
   81713   if( nIncr<0 ){
   81714     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
   81715   }
   81716 
   81717   /* Create an Expr object representing an SQL expression like:
   81718   **
   81719   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   81720   **
   81721   ** The collation sequence used for the comparison should be that of
   81722   ** the parent key columns. The affinity of the parent key column should
   81723   ** be applied to each child key value before the comparison takes place.
   81724   */
   81725   for(i=0; i<pFKey->nCol; i++){
   81726     Expr *pLeft;                  /* Value from parent table row */
   81727     Expr *pRight;                 /* Column ref to child table */
   81728     Expr *pEq;                    /* Expression (pLeft = pRight) */
   81729     int iCol;                     /* Index of column in child table */
   81730     const char *zCol;             /* Name of column in child table */
   81731 
   81732     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   81733     if( pLeft ){
   81734       /* Set the collation sequence and affinity of the LHS of each TK_EQ
   81735       ** expression to the parent key column defaults.  */
   81736       if( pIdx ){
   81737         Column *pCol;
   81738         iCol = pIdx->aiColumn[i];
   81739         pCol = &pTab->aCol[iCol];
   81740         if( pTab->iPKey==iCol ) iCol = -1;
   81741         pLeft->iTable = regData+iCol+1;
   81742         pLeft->affinity = pCol->affinity;
   81743         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
   81744       }else{
   81745         pLeft->iTable = regData;
   81746         pLeft->affinity = SQLITE_AFF_INTEGER;
   81747       }
   81748     }
   81749     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   81750     assert( iCol>=0 );
   81751     zCol = pFKey->pFrom->aCol[iCol].zName;
   81752     pRight = sqlite3Expr(db, TK_ID, zCol);
   81753     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
   81754     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   81755   }
   81756 
   81757   /* If the child table is the same as the parent table, and this scan
   81758   ** is taking place as part of a DELETE operation (operation D.2), omit the
   81759   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
   81760   ** clause, where $rowid is the rowid of the row being deleted.  */
   81761   if( pTab==pFKey->pFrom && nIncr>0 ){
   81762     Expr *pEq;                    /* Expression (pLeft = pRight) */
   81763     Expr *pLeft;                  /* Value from parent table row */
   81764     Expr *pRight;                 /* Column ref to child table */
   81765     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
   81766     pRight = sqlite3Expr(db, TK_COLUMN, 0);
   81767     if( pLeft && pRight ){
   81768       pLeft->iTable = regData;
   81769       pLeft->affinity = SQLITE_AFF_INTEGER;
   81770       pRight->iTable = pSrc->a[0].iCursor;
   81771       pRight->iColumn = -1;
   81772     }
   81773     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
   81774     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   81775   }
   81776 
   81777   /* Resolve the references in the WHERE clause. */
   81778   memset(&sNameContext, 0, sizeof(NameContext));
   81779   sNameContext.pSrcList = pSrc;
   81780   sNameContext.pParse = pParse;
   81781   sqlite3ResolveExprNames(&sNameContext, pWhere);
   81782 
   81783   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   81784   ** clause. If the constraint is not deferred, throw an exception for
   81785   ** each row found. Otherwise, for deferred constraints, increment the
   81786   ** deferred constraint counter by nIncr for each row selected.  */
   81787   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
   81788   if( nIncr>0 && pFKey->isDeferred==0 ){
   81789     sqlite3ParseToplevel(pParse)->mayAbort = 1;
   81790   }
   81791   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
   81792   if( pWInfo ){
   81793     sqlite3WhereEnd(pWInfo);
   81794   }
   81795 
   81796   /* Clean up the WHERE clause constructed above. */
   81797   sqlite3ExprDelete(db, pWhere);
   81798   if( iFkIfZero ){
   81799     sqlite3VdbeJumpHere(v, iFkIfZero);
   81800   }
   81801 }
   81802 
   81803 /*
   81804 ** This function returns a pointer to the head of a linked list of FK
   81805 ** constraints for which table pTab is the parent table. For example,
   81806 ** given the following schema:
   81807 **
   81808 **   CREATE TABLE t1(a PRIMARY KEY);
   81809 **   CREATE TABLE t2(b REFERENCES t1(a);
   81810 **
   81811 ** Calling this function with table "t1" as an argument returns a pointer
   81812 ** to the FKey structure representing the foreign key constraint on table
   81813 ** "t2". Calling this function with "t2" as the argument would return a
   81814 ** NULL pointer (as there are no FK constraints for which t2 is the parent
   81815 ** table).
   81816 */
   81817 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
   81818   int nName = sqlite3Strlen30(pTab->zName);
   81819   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
   81820 }
   81821 
   81822 /*
   81823 ** The second argument is a Trigger structure allocated by the
   81824 ** fkActionTrigger() routine. This function deletes the Trigger structure
   81825 ** and all of its sub-components.
   81826 **
   81827 ** The Trigger structure or any of its sub-components may be allocated from
   81828 ** the lookaside buffer belonging to database handle dbMem.
   81829 */
   81830 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
   81831   if( p ){
   81832     TriggerStep *pStep = p->step_list;
   81833     sqlite3ExprDelete(dbMem, pStep->pWhere);
   81834     sqlite3ExprListDelete(dbMem, pStep->pExprList);
   81835     sqlite3SelectDelete(dbMem, pStep->pSelect);
   81836     sqlite3ExprDelete(dbMem, p->pWhen);
   81837     sqlite3DbFree(dbMem, p);
   81838   }
   81839 }
   81840 
   81841 /*
   81842 ** This function is called to generate code that runs when table pTab is
   81843 ** being dropped from the database. The SrcList passed as the second argument
   81844 ** to this function contains a single entry guaranteed to resolve to
   81845 ** table pTab.
   81846 **
   81847 ** Normally, no code is required. However, if either
   81848 **
   81849 **   (a) The table is the parent table of a FK constraint, or
   81850 **   (b) The table is the child table of a deferred FK constraint and it is
   81851 **       determined at runtime that there are outstanding deferred FK
   81852 **       constraint violations in the database,
   81853 **
   81854 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
   81855 ** the table from the database. Triggers are disabled while running this
   81856 ** DELETE, but foreign key actions are not.
   81857 */
   81858 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
   81859   sqlite3 *db = pParse->db;
   81860   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
   81861     int iSkip = 0;
   81862     Vdbe *v = sqlite3GetVdbe(pParse);
   81863 
   81864     assert( v );                  /* VDBE has already been allocated */
   81865     if( sqlite3FkReferences(pTab)==0 ){
   81866       /* Search for a deferred foreign key constraint for which this table
   81867       ** is the child table. If one cannot be found, return without
   81868       ** generating any VDBE code. If one can be found, then jump over
   81869       ** the entire DELETE if there are no outstanding deferred constraints
   81870       ** when this statement is run.  */
   81871       FKey *p;
   81872       for(p=pTab->pFKey; p; p=p->pNextFrom){
   81873         if( p->isDeferred ) break;
   81874       }
   81875       if( !p ) return;
   81876       iSkip = sqlite3VdbeMakeLabel(v);
   81877       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
   81878     }
   81879 
   81880     pParse->disableTriggers = 1;
   81881     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   81882     pParse->disableTriggers = 0;
   81883 
   81884     /* If the DELETE has generated immediate foreign key constraint
   81885     ** violations, halt the VDBE and return an error at this point, before
   81886     ** any modifications to the schema are made. This is because statement
   81887     ** transactions are not able to rollback schema changes.  */
   81888     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
   81889     sqlite3HaltConstraint(
   81890         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
   81891     );
   81892 
   81893     if( iSkip ){
   81894       sqlite3VdbeResolveLabel(v, iSkip);
   81895     }
   81896   }
   81897 }
   81898 
   81899 /*
   81900 ** This function is called when inserting, deleting or updating a row of
   81901 ** table pTab to generate VDBE code to perform foreign key constraint
   81902 ** processing for the operation.
   81903 **
   81904 ** For a DELETE operation, parameter regOld is passed the index of the
   81905 ** first register in an array of (pTab->nCol+1) registers containing the
   81906 ** rowid of the row being deleted, followed by each of the column values
   81907 ** of the row being deleted, from left to right. Parameter regNew is passed
   81908 ** zero in this case.
   81909 **
   81910 ** For an INSERT operation, regOld is passed zero and regNew is passed the
   81911 ** first register of an array of (pTab->nCol+1) registers containing the new
   81912 ** row data.
   81913 **
   81914 ** For an UPDATE operation, this function is called twice. Once before
   81915 ** the original record is deleted from the table using the calling convention
   81916 ** described for DELETE. Then again after the original record is deleted
   81917 ** but before the new record is inserted using the INSERT convention.
   81918 */
   81919 SQLITE_PRIVATE void sqlite3FkCheck(
   81920   Parse *pParse,                  /* Parse context */
   81921   Table *pTab,                    /* Row is being deleted from this table */
   81922   int regOld,                     /* Previous row data is stored here */
   81923   int regNew                      /* New row data is stored here */
   81924 ){
   81925   sqlite3 *db = pParse->db;       /* Database handle */
   81926   Vdbe *v;                        /* VM to write code to */
   81927   FKey *pFKey;                    /* Used to iterate through FKs */
   81928   int iDb;                        /* Index of database containing pTab */
   81929   const char *zDb;                /* Name of database containing pTab */
   81930   int isIgnoreErrors = pParse->disableTriggers;
   81931 
   81932   /* Exactly one of regOld and regNew should be non-zero. */
   81933   assert( (regOld==0)!=(regNew==0) );
   81934 
   81935   /* If foreign-keys are disabled, this function is a no-op. */
   81936   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
   81937 
   81938   v = sqlite3GetVdbe(pParse);
   81939   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   81940   zDb = db->aDb[iDb].zName;
   81941 
   81942   /* Loop through all the foreign key constraints for which pTab is the
   81943   ** child table (the table that the foreign key definition is part of).  */
   81944   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
   81945     Table *pTo;                   /* Parent table of foreign key pFKey */
   81946     Index *pIdx = 0;              /* Index on key columns in pTo */
   81947     int *aiFree = 0;
   81948     int *aiCol;
   81949     int iCol;
   81950     int i;
   81951     int isIgnore = 0;
   81952 
   81953     /* Find the parent table of this foreign key. Also find a unique index
   81954     ** on the parent key columns in the parent table. If either of these
   81955     ** schema items cannot be located, set an error in pParse and return
   81956     ** early.  */
   81957     if( pParse->disableTriggers ){
   81958       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
   81959     }else{
   81960       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
   81961     }
   81962     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
   81963       if( !isIgnoreErrors || db->mallocFailed ) return;
   81964       continue;
   81965     }
   81966     assert( pFKey->nCol==1 || (aiFree && pIdx) );
   81967 
   81968     if( aiFree ){
   81969       aiCol = aiFree;
   81970     }else{
   81971       iCol = pFKey->aCol[0].iFrom;
   81972       aiCol = &iCol;
   81973     }
   81974     for(i=0; i<pFKey->nCol; i++){
   81975       if( aiCol[i]==pTab->iPKey ){
   81976         aiCol[i] = -1;
   81977       }
   81978 #ifndef SQLITE_OMIT_AUTHORIZATION
   81979       /* Request permission to read the parent key columns. If the
   81980       ** authorization callback returns SQLITE_IGNORE, behave as if any
   81981       ** values read from the parent table are NULL. */
   81982       if( db->xAuth ){
   81983         int rcauth;
   81984         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
   81985         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
   81986         isIgnore = (rcauth==SQLITE_IGNORE);
   81987       }
   81988 #endif
   81989     }
   81990 
   81991     /* Take a shared-cache advisory read-lock on the parent table. Allocate
   81992     ** a cursor to use to search the unique index on the parent key columns
   81993     ** in the parent table.  */
   81994     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
   81995     pParse->nTab++;
   81996 
   81997     if( regOld!=0 ){
   81998       /* A row is being removed from the child table. Search for the parent.
   81999       ** If the parent does not exist, removing the child row resolves an
   82000       ** outstanding foreign key constraint violation. */
   82001       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
   82002     }
   82003     if( regNew!=0 ){
   82004       /* A row is being added to the child table. If a parent row cannot
   82005       ** be found, adding the child row has violated the FK constraint. */
   82006       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
   82007     }
   82008 
   82009     sqlite3DbFree(db, aiFree);
   82010   }
   82011 
   82012   /* Loop through all the foreign key constraints that refer to this table */
   82013   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   82014     Index *pIdx = 0;              /* Foreign key index for pFKey */
   82015     SrcList *pSrc;
   82016     int *aiCol = 0;
   82017 
   82018     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
   82019       assert( regOld==0 && regNew!=0 );
   82020       /* Inserting a single row into a parent table cannot cause an immediate
   82021       ** foreign key violation. So do nothing in this case.  */
   82022       continue;
   82023     }
   82024 
   82025     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
   82026       if( !isIgnoreErrors || db->mallocFailed ) return;
   82027       continue;
   82028     }
   82029     assert( aiCol || pFKey->nCol==1 );
   82030 
   82031     /* Create a SrcList structure containing a single table (the table
   82032     ** the foreign key that refers to this table is attached to). This
   82033     ** is required for the sqlite3WhereXXX() interface.  */
   82034     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   82035     if( pSrc ){
   82036       struct SrcList_item *pItem = pSrc->a;
   82037       pItem->pTab = pFKey->pFrom;
   82038       pItem->zName = pFKey->pFrom->zName;
   82039       pItem->pTab->nRef++;
   82040       pItem->iCursor = pParse->nTab++;
   82041 
   82042       if( regNew!=0 ){
   82043         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
   82044       }
   82045       if( regOld!=0 ){
   82046         /* If there is a RESTRICT action configured for the current operation
   82047         ** on the parent table of this FK, then throw an exception
   82048         ** immediately if the FK constraint is violated, even if this is a
   82049         ** deferred trigger. That's what RESTRICT means. To defer checking
   82050         ** the constraint, the FK should specify NO ACTION (represented
   82051         ** using OE_None). NO ACTION is the default.  */
   82052         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
   82053       }
   82054       pItem->zName = 0;
   82055       sqlite3SrcListDelete(db, pSrc);
   82056     }
   82057     sqlite3DbFree(db, aiCol);
   82058   }
   82059 }
   82060 
   82061 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
   82062 
   82063 /*
   82064 ** This function is called before generating code to update or delete a
   82065 ** row contained in table pTab.
   82066 */
   82067 SQLITE_PRIVATE u32 sqlite3FkOldmask(
   82068   Parse *pParse,                  /* Parse context */
   82069   Table *pTab                     /* Table being modified */
   82070 ){
   82071   u32 mask = 0;
   82072   if( pParse->db->flags&SQLITE_ForeignKeys ){
   82073     FKey *p;
   82074     int i;
   82075     for(p=pTab->pFKey; p; p=p->pNextFrom){
   82076       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
   82077     }
   82078     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   82079       Index *pIdx = 0;
   82080       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
   82081       if( pIdx ){
   82082         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
   82083       }
   82084     }
   82085   }
   82086   return mask;
   82087 }
   82088 
   82089 /*
   82090 ** This function is called before generating code to update or delete a
   82091 ** row contained in table pTab. If the operation is a DELETE, then
   82092 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
   82093 ** to an array of size N, where N is the number of columns in table pTab.
   82094 ** If the i'th column is not modified by the UPDATE, then the corresponding
   82095 ** entry in the aChange[] array is set to -1. If the column is modified,
   82096 ** the value is 0 or greater. Parameter chngRowid is set to true if the
   82097 ** UPDATE statement modifies the rowid fields of the table.
   82098 **
   82099 ** If any foreign key processing will be required, this function returns
   82100 ** true. If there is no foreign key related processing, this function
   82101 ** returns false.
   82102 */
   82103 SQLITE_PRIVATE int sqlite3FkRequired(
   82104   Parse *pParse,                  /* Parse context */
   82105   Table *pTab,                    /* Table being modified */
   82106   int *aChange,                   /* Non-NULL for UPDATE operations */
   82107   int chngRowid                   /* True for UPDATE that affects rowid */
   82108 ){
   82109   if( pParse->db->flags&SQLITE_ForeignKeys ){
   82110     if( !aChange ){
   82111       /* A DELETE operation. Foreign key processing is required if the
   82112       ** table in question is either the child or parent table for any
   82113       ** foreign key constraint.  */
   82114       return (sqlite3FkReferences(pTab) || pTab->pFKey);
   82115     }else{
   82116       /* This is an UPDATE. Foreign key processing is only required if the
   82117       ** operation modifies one or more child or parent key columns. */
   82118       int i;
   82119       FKey *p;
   82120 
   82121       /* Check if any child key columns are being modified. */
   82122       for(p=pTab->pFKey; p; p=p->pNextFrom){
   82123         for(i=0; i<p->nCol; i++){
   82124           int iChildKey = p->aCol[i].iFrom;
   82125           if( aChange[iChildKey]>=0 ) return 1;
   82126           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
   82127         }
   82128       }
   82129 
   82130       /* Check if any parent key columns are being modified. */
   82131       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
   82132         for(i=0; i<p->nCol; i++){
   82133           char *zKey = p->aCol[i].zCol;
   82134           int iKey;
   82135           for(iKey=0; iKey<pTab->nCol; iKey++){
   82136             Column *pCol = &pTab->aCol[iKey];
   82137             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
   82138               if( aChange[iKey]>=0 ) return 1;
   82139               if( iKey==pTab->iPKey && chngRowid ) return 1;
   82140             }
   82141           }
   82142         }
   82143       }
   82144     }
   82145   }
   82146   return 0;
   82147 }
   82148 
   82149 /*
   82150 ** This function is called when an UPDATE or DELETE operation is being
   82151 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
   82152 ** If the current operation is an UPDATE, then the pChanges parameter is
   82153 ** passed a pointer to the list of columns being modified. If it is a
   82154 ** DELETE, pChanges is passed a NULL pointer.
   82155 **
   82156 ** It returns a pointer to a Trigger structure containing a trigger
   82157 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
   82158 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
   82159 ** returned (these actions require no special handling by the triggers
   82160 ** sub-system, code for them is created by fkScanChildren()).
   82161 **
   82162 ** For example, if pFKey is the foreign key and pTab is table "p" in
   82163 ** the following schema:
   82164 **
   82165 **   CREATE TABLE p(pk PRIMARY KEY);
   82166 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
   82167 **
   82168 ** then the returned trigger structure is equivalent to:
   82169 **
   82170 **   CREATE TRIGGER ... DELETE ON p BEGIN
   82171 **     DELETE FROM c WHERE ck = old.pk;
   82172 **   END;
   82173 **
   82174 ** The returned pointer is cached as part of the foreign key object. It
   82175 ** is eventually freed along with the rest of the foreign key object by
   82176 ** sqlite3FkDelete().
   82177 */
   82178 static Trigger *fkActionTrigger(
   82179   Parse *pParse,                  /* Parse context */
   82180   Table *pTab,                    /* Table being updated or deleted from */
   82181   FKey *pFKey,                    /* Foreign key to get action for */
   82182   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
   82183 ){
   82184   sqlite3 *db = pParse->db;       /* Database handle */
   82185   int action;                     /* One of OE_None, OE_Cascade etc. */
   82186   Trigger *pTrigger;              /* Trigger definition to return */
   82187   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
   82188 
   82189   action = pFKey->aAction[iAction];
   82190   pTrigger = pFKey->apTrigger[iAction];
   82191 
   82192   if( action!=OE_None && !pTrigger ){
   82193     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
   82194     char const *zFrom;            /* Name of child table */
   82195     int nFrom;                    /* Length in bytes of zFrom */
   82196     Index *pIdx = 0;              /* Parent key index for this FK */
   82197     int *aiCol = 0;               /* child table cols -> parent key cols */
   82198     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
   82199     Expr *pWhere = 0;             /* WHERE clause of trigger step */
   82200     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
   82201     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
   82202     int i;                        /* Iterator variable */
   82203     Expr *pWhen = 0;              /* WHEN clause for the trigger */
   82204 
   82205     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
   82206     assert( aiCol || pFKey->nCol==1 );
   82207 
   82208     for(i=0; i<pFKey->nCol; i++){
   82209       Token tOld = { "old", 3 };  /* Literal "old" token */
   82210       Token tNew = { "new", 3 };  /* Literal "new" token */
   82211       Token tFromCol;             /* Name of column in child table */
   82212       Token tToCol;               /* Name of column in parent table */
   82213       int iFromCol;               /* Idx of column in child table */
   82214       Expr *pEq;                  /* tFromCol = OLD.tToCol */
   82215 
   82216       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
   82217       assert( iFromCol>=0 );
   82218       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
   82219       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
   82220 
   82221       tToCol.n = sqlite3Strlen30(tToCol.z);
   82222       tFromCol.n = sqlite3Strlen30(tFromCol.z);
   82223 
   82224       /* Create the expression "OLD.zToCol = zFromCol". It is important
   82225       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
   82226       ** that the affinity and collation sequence associated with the
   82227       ** parent table are used for the comparison. */
   82228       pEq = sqlite3PExpr(pParse, TK_EQ,
   82229           sqlite3PExpr(pParse, TK_DOT,
   82230             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   82231             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   82232           , 0),
   82233           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
   82234       , 0);
   82235       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
   82236 
   82237       /* For ON UPDATE, construct the next term of the WHEN clause.
   82238       ** The final WHEN clause will be like this:
   82239       **
   82240       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
   82241       */
   82242       if( pChanges ){
   82243         pEq = sqlite3PExpr(pParse, TK_IS,
   82244             sqlite3PExpr(pParse, TK_DOT,
   82245               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
   82246               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   82247               0),
   82248             sqlite3PExpr(pParse, TK_DOT,
   82249               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   82250               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
   82251               0),
   82252             0);
   82253         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
   82254       }
   82255 
   82256       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
   82257         Expr *pNew;
   82258         if( action==OE_Cascade ){
   82259           pNew = sqlite3PExpr(pParse, TK_DOT,
   82260             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
   82261             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
   82262           , 0);
   82263         }else if( action==OE_SetDflt ){
   82264           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
   82265           if( pDflt ){
   82266             pNew = sqlite3ExprDup(db, pDflt, 0);
   82267           }else{
   82268             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   82269           }
   82270         }else{
   82271           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
   82272         }
   82273         pList = sqlite3ExprListAppend(pParse, pList, pNew);
   82274         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
   82275       }
   82276     }
   82277     sqlite3DbFree(db, aiCol);
   82278 
   82279     zFrom = pFKey->pFrom->zName;
   82280     nFrom = sqlite3Strlen30(zFrom);
   82281 
   82282     if( action==OE_Restrict ){
   82283       Token tFrom;
   82284       Expr *pRaise;
   82285 
   82286       tFrom.z = zFrom;
   82287       tFrom.n = nFrom;
   82288       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
   82289       if( pRaise ){
   82290         pRaise->affinity = OE_Abort;
   82291       }
   82292       pSelect = sqlite3SelectNew(pParse,
   82293           sqlite3ExprListAppend(pParse, 0, pRaise),
   82294           sqlite3SrcListAppend(db, 0, &tFrom, 0),
   82295           pWhere,
   82296           0, 0, 0, 0, 0, 0
   82297       );
   82298       pWhere = 0;
   82299     }
   82300 
   82301     /* Disable lookaside memory allocation */
   82302     enableLookaside = db->lookaside.bEnabled;
   82303     db->lookaside.bEnabled = 0;
   82304 
   82305     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
   82306         sizeof(Trigger) +         /* struct Trigger */
   82307         sizeof(TriggerStep) +     /* Single step in trigger program */
   82308         nFrom + 1                 /* Space for pStep->target.z */
   82309     );
   82310     if( pTrigger ){
   82311       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
   82312       pStep->target.z = (char *)&pStep[1];
   82313       pStep->target.n = nFrom;
   82314       memcpy((char *)pStep->target.z, zFrom, nFrom);
   82315 
   82316       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   82317       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
   82318       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   82319       if( pWhen ){
   82320         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
   82321         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   82322       }
   82323     }
   82324 
   82325     /* Re-enable the lookaside buffer, if it was disabled earlier. */
   82326     db->lookaside.bEnabled = enableLookaside;
   82327 
   82328     sqlite3ExprDelete(db, pWhere);
   82329     sqlite3ExprDelete(db, pWhen);
   82330     sqlite3ExprListDelete(db, pList);
   82331     sqlite3SelectDelete(db, pSelect);
   82332     if( db->mallocFailed==1 ){
   82333       fkTriggerDelete(db, pTrigger);
   82334       return 0;
   82335     }
   82336 
   82337     switch( action ){
   82338       case OE_Restrict:
   82339         pStep->op = TK_SELECT;
   82340         break;
   82341       case OE_Cascade:
   82342         if( !pChanges ){
   82343           pStep->op = TK_DELETE;
   82344           break;
   82345         }
   82346       default:
   82347         pStep->op = TK_UPDATE;
   82348     }
   82349     pStep->pTrig = pTrigger;
   82350     pTrigger->pSchema = pTab->pSchema;
   82351     pTrigger->pTabSchema = pTab->pSchema;
   82352     pFKey->apTrigger[iAction] = pTrigger;
   82353     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
   82354   }
   82355 
   82356   return pTrigger;
   82357 }
   82358 
   82359 /*
   82360 ** This function is called when deleting or updating a row to implement
   82361 ** any required CASCADE, SET NULL or SET DEFAULT actions.
   82362 */
   82363 SQLITE_PRIVATE void sqlite3FkActions(
   82364   Parse *pParse,                  /* Parse context */
   82365   Table *pTab,                    /* Table being updated or deleted from */
   82366   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
   82367   int regOld                      /* Address of array containing old row */
   82368 ){
   82369   /* If foreign-key support is enabled, iterate through all FKs that
   82370   ** refer to table pTab. If there is an action associated with the FK
   82371   ** for this operation (either update or delete), invoke the associated
   82372   ** trigger sub-program.  */
   82373   if( pParse->db->flags&SQLITE_ForeignKeys ){
   82374     FKey *pFKey;                  /* Iterator variable */
   82375     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
   82376       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
   82377       if( pAction ){
   82378         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
   82379       }
   82380     }
   82381   }
   82382 }
   82383 
   82384 #endif /* ifndef SQLITE_OMIT_TRIGGER */
   82385 
   82386 /*
   82387 ** Free all memory associated with foreign key definitions attached to
   82388 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
   82389 ** hash table.
   82390 */
   82391 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
   82392   FKey *pFKey;                    /* Iterator variable */
   82393   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
   82394 
   82395   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
   82396 
   82397     /* Remove the FK from the fkeyHash hash table. */
   82398     if( !db || db->pnBytesFreed==0 ){
   82399       if( pFKey->pPrevTo ){
   82400         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
   82401       }else{
   82402         void *p = (void *)pFKey->pNextTo;
   82403         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
   82404         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
   82405       }
   82406       if( pFKey->pNextTo ){
   82407         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
   82408       }
   82409     }
   82410 
   82411     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
   82412     ** classified as either immediate or deferred.
   82413     */
   82414     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
   82415 
   82416     /* Delete any triggers created to implement actions for this FK. */
   82417 #ifndef SQLITE_OMIT_TRIGGER
   82418     fkTriggerDelete(db, pFKey->apTrigger[0]);
   82419     fkTriggerDelete(db, pFKey->apTrigger[1]);
   82420 #endif
   82421 
   82422     pNext = pFKey->pNextFrom;
   82423     sqlite3DbFree(db, pFKey);
   82424   }
   82425 }
   82426 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
   82427 
   82428 /************** End of fkey.c ************************************************/
   82429 /************** Begin file insert.c ******************************************/
   82430 /*
   82431 ** 2001 September 15
   82432 **
   82433 ** The author disclaims copyright to this source code.  In place of
   82434 ** a legal notice, here is a blessing:
   82435 **
   82436 **    May you do good and not evil.
   82437 **    May you find forgiveness for yourself and forgive others.
   82438 **    May you share freely, never taking more than you give.
   82439 **
   82440 *************************************************************************
   82441 ** This file contains C code routines that are called by the parser
   82442 ** to handle INSERT statements in SQLite.
   82443 */
   82444 
   82445 /*
   82446 ** Generate code that will open a table for reading.
   82447 */
   82448 SQLITE_PRIVATE void sqlite3OpenTable(
   82449   Parse *p,       /* Generate code into this VDBE */
   82450   int iCur,       /* The cursor number of the table */
   82451   int iDb,        /* The database index in sqlite3.aDb[] */
   82452   Table *pTab,    /* The table to be opened */
   82453   int opcode      /* OP_OpenRead or OP_OpenWrite */
   82454 ){
   82455   Vdbe *v;
   82456   if( IsVirtual(pTab) ) return;
   82457   v = sqlite3GetVdbe(p);
   82458   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
   82459   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
   82460   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
   82461   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
   82462   VdbeComment((v, "%s", pTab->zName));
   82463 }
   82464 
   82465 /*
   82466 ** Return a pointer to the column affinity string associated with index
   82467 ** pIdx. A column affinity string has one character for each column in
   82468 ** the table, according to the affinity of the column:
   82469 **
   82470 **  Character      Column affinity
   82471 **  ------------------------------
   82472 **  'a'            TEXT
   82473 **  'b'            NONE
   82474 **  'c'            NUMERIC
   82475 **  'd'            INTEGER
   82476 **  'e'            REAL
   82477 **
   82478 ** An extra 'b' is appended to the end of the string to cover the
   82479 ** rowid that appears as the last column in every index.
   82480 **
   82481 ** Memory for the buffer containing the column index affinity string
   82482 ** is managed along with the rest of the Index structure. It will be
   82483 ** released when sqlite3DeleteIndex() is called.
   82484 */
   82485 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
   82486   if( !pIdx->zColAff ){
   82487     /* The first time a column affinity string for a particular index is
   82488     ** required, it is allocated and populated here. It is then stored as
   82489     ** a member of the Index structure for subsequent use.
   82490     **
   82491     ** The column affinity string will eventually be deleted by
   82492     ** sqliteDeleteIndex() when the Index structure itself is cleaned
   82493     ** up.
   82494     */
   82495     int n;
   82496     Table *pTab = pIdx->pTable;
   82497     sqlite3 *db = sqlite3VdbeDb(v);
   82498     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
   82499     if( !pIdx->zColAff ){
   82500       db->mallocFailed = 1;
   82501       return 0;
   82502     }
   82503     for(n=0; n<pIdx->nColumn; n++){
   82504       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
   82505     }
   82506     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
   82507     pIdx->zColAff[n] = 0;
   82508   }
   82509 
   82510   return pIdx->zColAff;
   82511 }
   82512 
   82513 /*
   82514 ** Set P4 of the most recently inserted opcode to a column affinity
   82515 ** string for table pTab. A column affinity string has one character
   82516 ** for each column indexed by the index, according to the affinity of the
   82517 ** column:
   82518 **
   82519 **  Character      Column affinity
   82520 **  ------------------------------
   82521 **  'a'            TEXT
   82522 **  'b'            NONE
   82523 **  'c'            NUMERIC
   82524 **  'd'            INTEGER
   82525 **  'e'            REAL
   82526 */
   82527 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
   82528   /* The first time a column affinity string for a particular table
   82529   ** is required, it is allocated and populated here. It is then
   82530   ** stored as a member of the Table structure for subsequent use.
   82531   **
   82532   ** The column affinity string will eventually be deleted by
   82533   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
   82534   */
   82535   if( !pTab->zColAff ){
   82536     char *zColAff;
   82537     int i;
   82538     sqlite3 *db = sqlite3VdbeDb(v);
   82539 
   82540     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   82541     if( !zColAff ){
   82542       db->mallocFailed = 1;
   82543       return;
   82544     }
   82545 
   82546     for(i=0; i<pTab->nCol; i++){
   82547       zColAff[i] = pTab->aCol[i].affinity;
   82548     }
   82549     zColAff[pTab->nCol] = '\0';
   82550 
   82551     pTab->zColAff = zColAff;
   82552   }
   82553 
   82554   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
   82555 }
   82556 
   82557 /*
   82558 ** Return non-zero if the table pTab in database iDb or any of its indices
   82559 ** have been opened at any point in the VDBE program beginning at location
   82560 ** iStartAddr throught the end of the program.  This is used to see if
   82561 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
   82562 ** run without using temporary table for the results of the SELECT.
   82563 */
   82564 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
   82565   Vdbe *v = sqlite3GetVdbe(p);
   82566   int i;
   82567   int iEnd = sqlite3VdbeCurrentAddr(v);
   82568 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82569   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   82570 #endif
   82571 
   82572   for(i=iStartAddr; i<iEnd; i++){
   82573     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   82574     assert( pOp!=0 );
   82575     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   82576       Index *pIndex;
   82577       int tnum = pOp->p2;
   82578       if( tnum==pTab->tnum ){
   82579         return 1;
   82580       }
   82581       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
   82582         if( tnum==pIndex->tnum ){
   82583           return 1;
   82584         }
   82585       }
   82586     }
   82587 #ifndef SQLITE_OMIT_VIRTUALTABLE
   82588     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
   82589       assert( pOp->p4.pVtab!=0 );
   82590       assert( pOp->p4type==P4_VTAB );
   82591       return 1;
   82592     }
   82593 #endif
   82594   }
   82595   return 0;
   82596 }
   82597 
   82598 #ifndef SQLITE_OMIT_AUTOINCREMENT
   82599 /*
   82600 ** Locate or create an AutoincInfo structure associated with table pTab
   82601 ** which is in database iDb.  Return the register number for the register
   82602 ** that holds the maximum rowid.
   82603 **
   82604 ** There is at most one AutoincInfo structure per table even if the
   82605 ** same table is autoincremented multiple times due to inserts within
   82606 ** triggers.  A new AutoincInfo structure is created if this is the
   82607 ** first use of table pTab.  On 2nd and subsequent uses, the original
   82608 ** AutoincInfo structure is used.
   82609 **
   82610 ** Three memory locations are allocated:
   82611 **
   82612 **   (1)  Register to hold the name of the pTab table.
   82613 **   (2)  Register to hold the maximum ROWID of pTab.
   82614 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
   82615 **
   82616 ** The 2nd register is the one that is returned.  That is all the
   82617 ** insert routine needs to know about.
   82618 */
   82619 static int autoIncBegin(
   82620   Parse *pParse,      /* Parsing context */
   82621   int iDb,            /* Index of the database holding pTab */
   82622   Table *pTab         /* The table we are writing to */
   82623 ){
   82624   int memId = 0;      /* Register holding maximum rowid */
   82625   if( pTab->tabFlags & TF_Autoincrement ){
   82626     Parse *pToplevel = sqlite3ParseToplevel(pParse);
   82627     AutoincInfo *pInfo;
   82628 
   82629     pInfo = pToplevel->pAinc;
   82630     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   82631     if( pInfo==0 ){
   82632       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
   82633       if( pInfo==0 ) return 0;
   82634       pInfo->pNext = pToplevel->pAinc;
   82635       pToplevel->pAinc = pInfo;
   82636       pInfo->pTab = pTab;
   82637       pInfo->iDb = iDb;
   82638       pToplevel->nMem++;                  /* Register to hold name of table */
   82639       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
   82640       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
   82641     }
   82642     memId = pInfo->regCtr;
   82643   }
   82644   return memId;
   82645 }
   82646 
   82647 /*
   82648 ** This routine generates code that will initialize all of the
   82649 ** register used by the autoincrement tracker.
   82650 */
   82651 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   82652   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
   82653   sqlite3 *db = pParse->db;  /* The database connection */
   82654   Db *pDb;                   /* Database only autoinc table */
   82655   int memId;                 /* Register holding max rowid */
   82656   int addr;                  /* A VDBE address */
   82657   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
   82658 
   82659   /* This routine is never called during trigger-generation.  It is
   82660   ** only called from the top-level */
   82661   assert( pParse->pTriggerTab==0 );
   82662   assert( pParse==sqlite3ParseToplevel(pParse) );
   82663 
   82664   assert( v );   /* We failed long ago if this is not so */
   82665   for(p = pParse->pAinc; p; p = p->pNext){
   82666     pDb = &db->aDb[p->iDb];
   82667     memId = p->regCtr;
   82668     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   82669     addr = sqlite3VdbeCurrentAddr(v);
   82670     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   82671     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
   82672     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   82673     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
   82674     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   82675     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   82676     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   82677     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   82678     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
   82679     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   82680     sqlite3VdbeAddOp0(v, OP_Close);
   82681   }
   82682 }
   82683 
   82684 /*
   82685 ** Update the maximum rowid for an autoincrement calculation.
   82686 **
   82687 ** This routine should be called when the top of the stack holds a
   82688 ** new rowid that is about to be inserted.  If that new rowid is
   82689 ** larger than the maximum rowid in the memId memory cell, then the
   82690 ** memory cell is updated.  The stack is unchanged.
   82691 */
   82692 static void autoIncStep(Parse *pParse, int memId, int regRowid){
   82693   if( memId>0 ){
   82694     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
   82695   }
   82696 }
   82697 
   82698 /*
   82699 ** This routine generates the code needed to write autoincrement
   82700 ** maximum rowid values back into the sqlite_sequence register.
   82701 ** Every statement that might do an INSERT into an autoincrement
   82702 ** table (either directly or through triggers) needs to call this
   82703 ** routine just before the "exit" code.
   82704 */
   82705 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
   82706   AutoincInfo *p;
   82707   Vdbe *v = pParse->pVdbe;
   82708   sqlite3 *db = pParse->db;
   82709 
   82710   assert( v );
   82711   for(p = pParse->pAinc; p; p = p->pNext){
   82712     Db *pDb = &db->aDb[p->iDb];
   82713     int j1, j2, j3, j4, j5;
   82714     int iRec;
   82715     int memId = p->regCtr;
   82716 
   82717     iRec = sqlite3GetTempReg(pParse);
   82718     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   82719     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
   82720     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
   82721     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
   82722     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
   82723     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
   82724     sqlite3VdbeJumpHere(v, j2);
   82725     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   82726     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
   82727     sqlite3VdbeJumpHere(v, j4);
   82728     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   82729     sqlite3VdbeJumpHere(v, j1);
   82730     sqlite3VdbeJumpHere(v, j5);
   82731     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   82732     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   82733     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   82734     sqlite3VdbeAddOp0(v, OP_Close);
   82735     sqlite3ReleaseTempReg(pParse, iRec);
   82736   }
   82737 }
   82738 #else
   82739 /*
   82740 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   82741 ** above are all no-ops
   82742 */
   82743 # define autoIncBegin(A,B,C) (0)
   82744 # define autoIncStep(A,B,C)
   82745 #endif /* SQLITE_OMIT_AUTOINCREMENT */
   82746 
   82747 
   82748 /* Forward declaration */
   82749 static int xferOptimization(
   82750   Parse *pParse,        /* Parser context */
   82751   Table *pDest,         /* The table we are inserting into */
   82752   Select *pSelect,      /* A SELECT statement to use as the data source */
   82753   int onError,          /* How to handle constraint errors */
   82754   int iDbDest           /* The database of pDest */
   82755 );
   82756 
   82757 /*
   82758 ** This routine is call to handle SQL of the following forms:
   82759 **
   82760 **    insert into TABLE (IDLIST) values(EXPRLIST)
   82761 **    insert into TABLE (IDLIST) select
   82762 **
   82763 ** The IDLIST following the table name is always optional.  If omitted,
   82764 ** then a list of all columns for the table is substituted.  The IDLIST
   82765 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
   82766 **
   82767 ** The pList parameter holds EXPRLIST in the first form of the INSERT
   82768 ** statement above, and pSelect is NULL.  For the second form, pList is
   82769 ** NULL and pSelect is a pointer to the select statement used to generate
   82770 ** data for the insert.
   82771 **
   82772 ** The code generated follows one of four templates.  For a simple
   82773 ** select with data coming from a VALUES clause, the code executes
   82774 ** once straight down through.  Pseudo-code follows (we call this
   82775 ** the "1st template"):
   82776 **
   82777 **         open write cursor to <table> and its indices
   82778 **         puts VALUES clause expressions onto the stack
   82779 **         write the resulting record into <table>
   82780 **         cleanup
   82781 **
   82782 ** The three remaining templates assume the statement is of the form
   82783 **
   82784 **   INSERT INTO <table> SELECT ...
   82785 **
   82786 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
   82787 ** in other words if the SELECT pulls all columns from a single table
   82788 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
   82789 ** if <table2> and <table1> are distinct tables but have identical
   82790 ** schemas, including all the same indices, then a special optimization
   82791 ** is invoked that copies raw records from <table2> over to <table1>.
   82792 ** See the xferOptimization() function for the implementation of this
   82793 ** template.  This is the 2nd template.
   82794 **
   82795 **         open a write cursor to <table>
   82796 **         open read cursor on <table2>
   82797 **         transfer all records in <table2> over to <table>
   82798 **         close cursors
   82799 **         foreach index on <table>
   82800 **           open a write cursor on the <table> index
   82801 **           open a read cursor on the corresponding <table2> index
   82802 **           transfer all records from the read to the write cursors
   82803 **           close cursors
   82804 **         end foreach
   82805 **
   82806 ** The 3rd template is for when the second template does not apply
   82807 ** and the SELECT clause does not read from <table> at any time.
   82808 ** The generated code follows this template:
   82809 **
   82810 **         EOF <- 0
   82811 **         X <- A
   82812 **         goto B
   82813 **      A: setup for the SELECT
   82814 **         loop over the rows in the SELECT
   82815 **           load values into registers R..R+n
   82816 **           yield X
   82817 **         end loop
   82818 **         cleanup after the SELECT
   82819 **         EOF <- 1
   82820 **         yield X
   82821 **         goto A
   82822 **      B: open write cursor to <table> and its indices
   82823 **      C: yield X
   82824 **         if EOF goto D
   82825 **         insert the select result into <table> from R..R+n
   82826 **         goto C
   82827 **      D: cleanup
   82828 **
   82829 ** The 4th template is used if the insert statement takes its
   82830 ** values from a SELECT but the data is being inserted into a table
   82831 ** that is also read as part of the SELECT.  In the third form,
   82832 ** we have to use a intermediate table to store the results of
   82833 ** the select.  The template is like this:
   82834 **
   82835 **         EOF <- 0
   82836 **         X <- A
   82837 **         goto B
   82838 **      A: setup for the SELECT
   82839 **         loop over the tables in the SELECT
   82840 **           load value into register R..R+n
   82841 **           yield X
   82842 **         end loop
   82843 **         cleanup after the SELECT
   82844 **         EOF <- 1
   82845 **         yield X
   82846 **         halt-error
   82847 **      B: open temp table
   82848 **      L: yield X
   82849 **         if EOF goto M
   82850 **         insert row from R..R+n into temp table
   82851 **         goto L
   82852 **      M: open write cursor to <table> and its indices
   82853 **         rewind temp table
   82854 **      C: loop over rows of intermediate table
   82855 **           transfer values form intermediate table into <table>
   82856 **         end loop
   82857 **      D: cleanup
   82858 */
   82859 SQLITE_PRIVATE void sqlite3Insert(
   82860   Parse *pParse,        /* Parser context */
   82861   SrcList *pTabList,    /* Name of table into which we are inserting */
   82862   ExprList *pList,      /* List of values to be inserted */
   82863   Select *pSelect,      /* A SELECT statement to use as the data source */
   82864   IdList *pColumn,      /* Column names corresponding to IDLIST. */
   82865   int onError           /* How to handle constraint errors */
   82866 ){
   82867   sqlite3 *db;          /* The main database structure */
   82868   Table *pTab;          /* The table to insert into.  aka TABLE */
   82869   char *zTab;           /* Name of the table into which we are inserting */
   82870   const char *zDb;      /* Name of the database holding this table */
   82871   int i, j, idx;        /* Loop counters */
   82872   Vdbe *v;              /* Generate code into this virtual machine */
   82873   Index *pIdx;          /* For looping over indices of the table */
   82874   int nColumn;          /* Number of columns in the data */
   82875   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   82876   int baseCur = 0;      /* VDBE Cursor number for pTab */
   82877   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   82878   int endOfLoop;        /* Label for the end of the insertion loop */
   82879   int useTempTable = 0; /* Store SELECT results in intermediate table */
   82880   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   82881   int addrInsTop = 0;   /* Jump to label "D" */
   82882   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   82883   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   82884   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   82885   int iDb;              /* Index of database holding TABLE */
   82886   Db *pDb;              /* The database containing table being inserted into */
   82887   int appendFlag = 0;   /* True if the insert is likely to be an append */
   82888 
   82889   /* Register allocations */
   82890   int regFromSelect = 0;/* Base register for data coming from SELECT */
   82891   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   82892   int regRowCount = 0;  /* Memory cell used for the row counter */
   82893   int regIns;           /* Block of regs holding rowid+data being inserted */
   82894   int regRowid;         /* registers holding insert rowid */
   82895   int regData;          /* register holding first column to insert */
   82896   int regRecord;        /* Holds the assemblied row record */
   82897   int regEof = 0;       /* Register recording end of SELECT data */
   82898   int *aRegIdx = 0;     /* One register allocated to each index */
   82899 
   82900 #ifndef SQLITE_OMIT_TRIGGER
   82901   int isView;                 /* True if attempting to insert into a view */
   82902   Trigger *pTrigger;          /* List of triggers on pTab, if required */
   82903   int tmask;                  /* Mask of trigger times */
   82904 #endif
   82905 
   82906   db = pParse->db;
   82907   memset(&dest, 0, sizeof(dest));
   82908   if( pParse->nErr || db->mallocFailed ){
   82909     goto insert_cleanup;
   82910   }
   82911 
   82912   /* Locate the table into which we will be inserting new information.
   82913   */
   82914   assert( pTabList->nSrc==1 );
   82915   zTab = pTabList->a[0].zName;
   82916   if( NEVER(zTab==0) ) goto insert_cleanup;
   82917   pTab = sqlite3SrcListLookup(pParse, pTabList);
   82918   if( pTab==0 ){
   82919     goto insert_cleanup;
   82920   }
   82921   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   82922   assert( iDb<db->nDb );
   82923   pDb = &db->aDb[iDb];
   82924   zDb = pDb->zName;
   82925   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
   82926     goto insert_cleanup;
   82927   }
   82928 
   82929   /* Figure out if we have any triggers and if the table being
   82930   ** inserted into is a view
   82931   */
   82932 #ifndef SQLITE_OMIT_TRIGGER
   82933   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
   82934   isView = pTab->pSelect!=0;
   82935 #else
   82936 # define pTrigger 0
   82937 # define tmask 0
   82938 # define isView 0
   82939 #endif
   82940 #ifdef SQLITE_OMIT_VIEW
   82941 # undef isView
   82942 # define isView 0
   82943 #endif
   82944   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
   82945 
   82946   /* If pTab is really a view, make sure it has been initialized.
   82947   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
   82948   ** module table).
   82949   */
   82950   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   82951     goto insert_cleanup;
   82952   }
   82953 
   82954   /* Ensure that:
   82955   *  (a) the table is not read-only,
   82956   *  (b) that if it is a view then ON INSERT triggers exist
   82957   */
   82958   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   82959     goto insert_cleanup;
   82960   }
   82961 
   82962   /* Allocate a VDBE
   82963   */
   82964   v = sqlite3GetVdbe(pParse);
   82965   if( v==0 ) goto insert_cleanup;
   82966   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   82967   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
   82968 
   82969 #ifndef SQLITE_OMIT_XFER_OPT
   82970   /* If the statement is of the form
   82971   **
   82972   **       INSERT INTO <table1> SELECT * FROM <table2>;
   82973   **
   82974   ** Then special optimizations can be applied that make the transfer
   82975   ** very fast and which reduce fragmentation of indices.
   82976   **
   82977   ** This is the 2nd template.
   82978   */
   82979   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
   82980     assert( !pTrigger );
   82981     assert( pList==0 );
   82982     goto insert_end;
   82983   }
   82984 #endif /* SQLITE_OMIT_XFER_OPT */
   82985 
   82986   /* If this is an AUTOINCREMENT table, look up the sequence number in the
   82987   ** sqlite_sequence table and store it in memory cell regAutoinc.
   82988   */
   82989   regAutoinc = autoIncBegin(pParse, iDb, pTab);
   82990 
   82991   /* Figure out how many columns of data are supplied.  If the data
   82992   ** is coming from a SELECT statement, then generate a co-routine that
   82993   ** produces a single row of the SELECT on each invocation.  The
   82994   ** co-routine is the common header to the 3rd and 4th templates.
   82995   */
   82996   if( pSelect ){
   82997     /* Data is coming from a SELECT.  Generate code to implement that SELECT
   82998     ** as a co-routine.  The code is common to both the 3rd and 4th
   82999     ** templates:
   83000     **
   83001     **         EOF <- 0
   83002     **         X <- A
   83003     **         goto B
   83004     **      A: setup for the SELECT
   83005     **         loop over the tables in the SELECT
   83006     **           load value into register R..R+n
   83007     **           yield X
   83008     **         end loop
   83009     **         cleanup after the SELECT
   83010     **         EOF <- 1
   83011     **         yield X
   83012     **         halt-error
   83013     **
   83014     ** On each invocation of the co-routine, it puts a single row of the
   83015     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
   83016     ** (These output registers are allocated by sqlite3Select().)  When
   83017     ** the SELECT completes, it sets the EOF flag stored in regEof.
   83018     */
   83019     int rc, j1;
   83020 
   83021     regEof = ++pParse->nMem;
   83022     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
   83023     VdbeComment((v, "SELECT eof flag"));
   83024     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
   83025     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
   83026     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
   83027     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   83028     VdbeComment((v, "Jump over SELECT coroutine"));
   83029 
   83030     /* Resolve the expressions in the SELECT statement and execute it. */
   83031     rc = sqlite3Select(pParse, pSelect, &dest);
   83032     assert( pParse->nErr==0 || rc );
   83033     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
   83034       goto insert_cleanup;
   83035     }
   83036     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
   83037     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
   83038     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
   83039     VdbeComment((v, "End of SELECT coroutine"));
   83040     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
   83041 
   83042     regFromSelect = dest.iMem;
   83043     assert( pSelect->pEList );
   83044     nColumn = pSelect->pEList->nExpr;
   83045     assert( dest.nMem==nColumn );
   83046 
   83047     /* Set useTempTable to TRUE if the result of the SELECT statement
   83048     ** should be written into a temporary table (template 4).  Set to
   83049     ** FALSE if each* row of the SELECT can be written directly into
   83050     ** the destination table (template 3).
   83051     **
   83052     ** A temp table must be used if the table being updated is also one
   83053     ** of the tables being read by the SELECT statement.  Also use a
   83054     ** temp table in the case of row triggers.
   83055     */
   83056     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
   83057       useTempTable = 1;
   83058     }
   83059 
   83060     if( useTempTable ){
   83061       /* Invoke the coroutine to extract information from the SELECT
   83062       ** and add it to a transient table srcTab.  The code generated
   83063       ** here is from the 4th template:
   83064       **
   83065       **      B: open temp table
   83066       **      L: yield X
   83067       **         if EOF goto M
   83068       **         insert row from R..R+n into temp table
   83069       **         goto L
   83070       **      M: ...
   83071       */
   83072       int regRec;          /* Register to hold packed record */
   83073       int regTempRowid;    /* Register to hold temp table ROWID */
   83074       int addrTop;         /* Label "L" */
   83075       int addrIf;          /* Address of jump to M */
   83076 
   83077       srcTab = pParse->nTab++;
   83078       regRec = sqlite3GetTempReg(pParse);
   83079       regTempRowid = sqlite3GetTempReg(pParse);
   83080       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   83081       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   83082       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
   83083       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   83084       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   83085       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   83086       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   83087       sqlite3VdbeJumpHere(v, addrIf);
   83088       sqlite3ReleaseTempReg(pParse, regRec);
   83089       sqlite3ReleaseTempReg(pParse, regTempRowid);
   83090     }
   83091   }else{
   83092     /* This is the case if the data for the INSERT is coming from a VALUES
   83093     ** clause
   83094     */
   83095     NameContext sNC;
   83096     memset(&sNC, 0, sizeof(sNC));
   83097     sNC.pParse = pParse;
   83098     srcTab = -1;
   83099     assert( useTempTable==0 );
   83100     nColumn = pList ? pList->nExpr : 0;
   83101     for(i=0; i<nColumn; i++){
   83102       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   83103         goto insert_cleanup;
   83104       }
   83105     }
   83106   }
   83107 
   83108   /* Make sure the number of columns in the source data matches the number
   83109   ** of columns to be inserted into the table.
   83110   */
   83111   if( IsVirtual(pTab) ){
   83112     for(i=0; i<pTab->nCol; i++){
   83113       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
   83114     }
   83115   }
   83116   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
   83117     sqlite3ErrorMsg(pParse,
   83118        "table %S has %d columns but %d values were supplied",
   83119        pTabList, 0, pTab->nCol-nHidden, nColumn);
   83120     goto insert_cleanup;
   83121   }
   83122   if( pColumn!=0 && nColumn!=pColumn->nId ){
   83123     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   83124     goto insert_cleanup;
   83125   }
   83126 
   83127   /* If the INSERT statement included an IDLIST term, then make sure
   83128   ** all elements of the IDLIST really are columns of the table and
   83129   ** remember the column indices.
   83130   **
   83131   ** If the table has an INTEGER PRIMARY KEY column and that column
   83132   ** is named in the IDLIST, then record in the keyColumn variable
   83133   ** the index into IDLIST of the primary key column.  keyColumn is
   83134   ** the index of the primary key as it appears in IDLIST, not as
   83135   ** is appears in the original table.  (The index of the primary
   83136   ** key in the original table is pTab->iPKey.)
   83137   */
   83138   if( pColumn ){
   83139     for(i=0; i<pColumn->nId; i++){
   83140       pColumn->a[i].idx = -1;
   83141     }
   83142     for(i=0; i<pColumn->nId; i++){
   83143       for(j=0; j<pTab->nCol; j++){
   83144         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   83145           pColumn->a[i].idx = j;
   83146           if( j==pTab->iPKey ){
   83147             keyColumn = i;
   83148           }
   83149           break;
   83150         }
   83151       }
   83152       if( j>=pTab->nCol ){
   83153         if( sqlite3IsRowid(pColumn->a[i].zName) ){
   83154           keyColumn = i;
   83155         }else{
   83156           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   83157               pTabList, 0, pColumn->a[i].zName);
   83158           pParse->checkSchema = 1;
   83159           goto insert_cleanup;
   83160         }
   83161       }
   83162     }
   83163   }
   83164 
   83165   /* If there is no IDLIST term but the table has an integer primary
   83166   ** key, the set the keyColumn variable to the primary key column index
   83167   ** in the original table definition.
   83168   */
   83169   if( pColumn==0 && nColumn>0 ){
   83170     keyColumn = pTab->iPKey;
   83171   }
   83172 
   83173   /* Initialize the count of rows to be inserted
   83174   */
   83175   if( db->flags & SQLITE_CountRows ){
   83176     regRowCount = ++pParse->nMem;
   83177     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   83178   }
   83179 
   83180   /* If this is not a view, open the table and and all indices */
   83181   if( !isView ){
   83182     int nIdx;
   83183 
   83184     baseCur = pParse->nTab;
   83185     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
   83186     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
   83187     if( aRegIdx==0 ){
   83188       goto insert_cleanup;
   83189     }
   83190     for(i=0; i<nIdx; i++){
   83191       aRegIdx[i] = ++pParse->nMem;
   83192     }
   83193   }
   83194 
   83195   /* This is the top of the main insertion loop */
   83196   if( useTempTable ){
   83197     /* This block codes the top of loop only.  The complete loop is the
   83198     ** following pseudocode (template 4):
   83199     **
   83200     **         rewind temp table
   83201     **      C: loop over rows of intermediate table
   83202     **           transfer values form intermediate table into <table>
   83203     **         end loop
   83204     **      D: ...
   83205     */
   83206     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
   83207     addrCont = sqlite3VdbeCurrentAddr(v);
   83208   }else if( pSelect ){
   83209     /* This block codes the top of loop only.  The complete loop is the
   83210     ** following pseudocode (template 3):
   83211     **
   83212     **      C: yield X
   83213     **         if EOF goto D
   83214     **         insert the select result into <table> from R..R+n
   83215     **         goto C
   83216     **      D: ...
   83217     */
   83218     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
   83219     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
   83220   }
   83221 
   83222   /* Allocate registers for holding the rowid of the new row,
   83223   ** the content of the new row, and the assemblied row record.
   83224   */
   83225   regRecord = ++pParse->nMem;
   83226   regRowid = regIns = pParse->nMem+1;
   83227   pParse->nMem += pTab->nCol + 1;
   83228   if( IsVirtual(pTab) ){
   83229     regRowid++;
   83230     pParse->nMem++;
   83231   }
   83232   regData = regRowid+1;
   83233 
   83234   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   83235   */
   83236   endOfLoop = sqlite3VdbeMakeLabel(v);
   83237   if( tmask & TRIGGER_BEFORE ){
   83238     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   83239 
   83240     /* build the NEW.* reference row.  Note that if there is an INTEGER
   83241     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
   83242     ** translated into a unique ID for the row.  But on a BEFORE trigger,
   83243     ** we do not know what the unique ID will be (because the insert has
   83244     ** not happened yet) so we substitute a rowid of -1
   83245     */
   83246     if( keyColumn<0 ){
   83247       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   83248     }else{
   83249       int j1;
   83250       if( useTempTable ){
   83251         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
   83252       }else{
   83253         assert( pSelect==0 );  /* Otherwise useTempTable is true */
   83254         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
   83255       }
   83256       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
   83257       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   83258       sqlite3VdbeJumpHere(v, j1);
   83259       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
   83260     }
   83261 
   83262     /* Cannot have triggers on a virtual table. If it were possible,
   83263     ** this block would have to account for hidden column.
   83264     */
   83265     assert( !IsVirtual(pTab) );
   83266 
   83267     /* Create the new column data
   83268     */
   83269     for(i=0; i<pTab->nCol; i++){
   83270       if( pColumn==0 ){
   83271         j = i;
   83272       }else{
   83273         for(j=0; j<pColumn->nId; j++){
   83274           if( pColumn->a[j].idx==i ) break;
   83275         }
   83276       }
   83277       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
   83278         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
   83279       }else if( useTempTable ){
   83280         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
   83281       }else{
   83282         assert( pSelect==0 ); /* Otherwise useTempTable is true */
   83283         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
   83284       }
   83285     }
   83286 
   83287     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   83288     ** do not attempt any conversions before assembling the record.
   83289     ** If this is a real table, attempt conversions as required by the
   83290     ** table column affinities.
   83291     */
   83292     if( !isView ){
   83293       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   83294       sqlite3TableAffinityStr(v, pTab);
   83295     }
   83296 
   83297     /* Fire BEFORE or INSTEAD OF triggers */
   83298     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
   83299         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   83300 
   83301     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   83302   }
   83303 
   83304   /* Push the record number for the new entry onto the stack.  The
   83305   ** record number is a randomly generate integer created by NewRowid
   83306   ** except when the table has an INTEGER PRIMARY KEY column, in which
   83307   ** case the record number is the same as that column.
   83308   */
   83309   if( !isView ){
   83310     if( IsVirtual(pTab) ){
   83311       /* The row that the VUpdate opcode will delete: none */
   83312       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   83313     }
   83314     if( keyColumn>=0 ){
   83315       if( useTempTable ){
   83316         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
   83317       }else if( pSelect ){
   83318         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
   83319       }else{
   83320         VdbeOp *pOp;
   83321         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
   83322         pOp = sqlite3VdbeGetOp(v, -1);
   83323         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   83324           appendFlag = 1;
   83325           pOp->opcode = OP_NewRowid;
   83326           pOp->p1 = baseCur;
   83327           pOp->p2 = regRowid;
   83328           pOp->p3 = regAutoinc;
   83329         }
   83330       }
   83331       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   83332       ** to generate a unique primary key value.
   83333       */
   83334       if( !appendFlag ){
   83335         int j1;
   83336         if( !IsVirtual(pTab) ){
   83337           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
   83338           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   83339           sqlite3VdbeJumpHere(v, j1);
   83340         }else{
   83341           j1 = sqlite3VdbeCurrentAddr(v);
   83342           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
   83343         }
   83344         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
   83345       }
   83346     }else if( IsVirtual(pTab) ){
   83347       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   83348     }else{
   83349       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
   83350       appendFlag = 1;
   83351     }
   83352     autoIncStep(pParse, regAutoinc, regRowid);
   83353 
   83354     /* Push onto the stack, data for all columns of the new entry, beginning
   83355     ** with the first column.
   83356     */
   83357     nHidden = 0;
   83358     for(i=0; i<pTab->nCol; i++){
   83359       int iRegStore = regRowid+1+i;
   83360       if( i==pTab->iPKey ){
   83361         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   83362         ** Whenever this column is read, the record number will be substituted
   83363         ** in its place.  So will fill this column with a NULL to avoid
   83364         ** taking up data space with information that will never be used. */
   83365         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
   83366         continue;
   83367       }
   83368       if( pColumn==0 ){
   83369         if( IsHiddenColumn(&pTab->aCol[i]) ){
   83370           assert( IsVirtual(pTab) );
   83371           j = -1;
   83372           nHidden++;
   83373         }else{
   83374           j = i - nHidden;
   83375         }
   83376       }else{
   83377         for(j=0; j<pColumn->nId; j++){
   83378           if( pColumn->a[j].idx==i ) break;
   83379         }
   83380       }
   83381       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   83382         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
   83383       }else if( useTempTable ){
   83384         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
   83385       }else if( pSelect ){
   83386         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
   83387       }else{
   83388         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
   83389       }
   83390     }
   83391 
   83392     /* Generate code to check constraints and generate index keys and
   83393     ** do the insertion.
   83394     */
   83395 #ifndef SQLITE_OMIT_VIRTUALTABLE
   83396     if( IsVirtual(pTab) ){
   83397       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   83398       sqlite3VtabMakeWritable(pParse, pTab);
   83399       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
   83400       sqlite3MayAbort(pParse);
   83401     }else
   83402 #endif
   83403     {
   83404       int isReplace;    /* Set to true if constraints may cause a replace */
   83405       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
   83406           keyColumn>=0, 0, onError, endOfLoop, &isReplace
   83407       );
   83408       sqlite3FkCheck(pParse, pTab, 0, regIns);
   83409       sqlite3CompleteInsertion(
   83410           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
   83411       );
   83412     }
   83413   }
   83414 
   83415   /* Update the count of rows that are inserted
   83416   */
   83417   if( (db->flags & SQLITE_CountRows)!=0 ){
   83418     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   83419   }
   83420 
   83421   if( pTrigger ){
   83422     /* Code AFTER triggers */
   83423     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
   83424         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   83425   }
   83426 
   83427   /* The bottom of the main insertion loop, if the data source
   83428   ** is a SELECT statement.
   83429   */
   83430   sqlite3VdbeResolveLabel(v, endOfLoop);
   83431   if( useTempTable ){
   83432     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
   83433     sqlite3VdbeJumpHere(v, addrInsTop);
   83434     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   83435   }else if( pSelect ){
   83436     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
   83437     sqlite3VdbeJumpHere(v, addrInsTop);
   83438   }
   83439 
   83440   if( !IsVirtual(pTab) && !isView ){
   83441     /* Close all tables opened */
   83442     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
   83443     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
   83444       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
   83445     }
   83446   }
   83447 
   83448 insert_end:
   83449   /* Update the sqlite_sequence table by storing the content of the
   83450   ** maximum rowid counter values recorded while inserting into
   83451   ** autoincrement tables.
   83452   */
   83453   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   83454     sqlite3AutoincrementEnd(pParse);
   83455   }
   83456 
   83457   /*
   83458   ** Return the number of rows inserted. If this routine is
   83459   ** generating code because of a call to sqlite3NestedParse(), do not
   83460   ** invoke the callback function.
   83461   */
   83462   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
   83463     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   83464     sqlite3VdbeSetNumCols(v, 1);
   83465     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
   83466   }
   83467 
   83468 insert_cleanup:
   83469   sqlite3SrcListDelete(db, pTabList);
   83470   sqlite3ExprListDelete(db, pList);
   83471   sqlite3SelectDelete(db, pSelect);
   83472   sqlite3IdListDelete(db, pColumn);
   83473   sqlite3DbFree(db, aRegIdx);
   83474 }
   83475 
   83476 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   83477 ** thely may interfere with compilation of other functions in this file
   83478 ** (or in another file, if this file becomes part of the amalgamation).  */
   83479 #ifdef isView
   83480  #undef isView
   83481 #endif
   83482 #ifdef pTrigger
   83483  #undef pTrigger
   83484 #endif
   83485 #ifdef tmask
   83486  #undef tmask
   83487 #endif
   83488 
   83489 
   83490 /*
   83491 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
   83492 **
   83493 ** The input is a range of consecutive registers as follows:
   83494 **
   83495 **    1.  The rowid of the row after the update.
   83496 **
   83497 **    2.  The data in the first column of the entry after the update.
   83498 **
   83499 **    i.  Data from middle columns...
   83500 **
   83501 **    N.  The data in the last column of the entry after the update.
   83502 **
   83503 ** The regRowid parameter is the index of the register containing (1).
   83504 **
   83505 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
   83506 ** the address of a register containing the rowid before the update takes
   83507 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
   83508 ** is false, indicating an INSERT statement, then a non-zero rowidChng
   83509 ** indicates that the rowid was explicitly specified as part of the
   83510 ** INSERT statement. If rowidChng is false, it means that  the rowid is
   83511 ** computed automatically in an insert or that the rowid value is not
   83512 ** modified by an update.
   83513 **
   83514 ** The code generated by this routine store new index entries into
   83515 ** registers identified by aRegIdx[].  No index entry is created for
   83516 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
   83517 ** the same as the order of indices on the linked list of indices
   83518 ** attached to the table.
   83519 **
   83520 ** This routine also generates code to check constraints.  NOT NULL,
   83521 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
   83522 ** then the appropriate action is performed.  There are five possible
   83523 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
   83524 **
   83525 **  Constraint type  Action       What Happens
   83526 **  ---------------  ----------   ----------------------------------------
   83527 **  any              ROLLBACK     The current transaction is rolled back and
   83528 **                                sqlite3_exec() returns immediately with a
   83529 **                                return code of SQLITE_CONSTRAINT.
   83530 **
   83531 **  any              ABORT        Back out changes from the current command
   83532 **                                only (do not do a complete rollback) then
   83533 **                                cause sqlite3_exec() to return immediately
   83534 **                                with SQLITE_CONSTRAINT.
   83535 **
   83536 **  any              FAIL         Sqlite_exec() returns immediately with a
   83537 **                                return code of SQLITE_CONSTRAINT.  The
   83538 **                                transaction is not rolled back and any
   83539 **                                prior changes are retained.
   83540 **
   83541 **  any              IGNORE       The record number and data is popped from
   83542 **                                the stack and there is an immediate jump
   83543 **                                to label ignoreDest.
   83544 **
   83545 **  NOT NULL         REPLACE      The NULL value is replace by the default
   83546 **                                value for that column.  If the default value
   83547 **                                is NULL, the action is the same as ABORT.
   83548 **
   83549 **  UNIQUE           REPLACE      The other row that conflicts with the row
   83550 **                                being inserted is removed.
   83551 **
   83552 **  CHECK            REPLACE      Illegal.  The results in an exception.
   83553 **
   83554 ** Which action to take is determined by the overrideError parameter.
   83555 ** Or if overrideError==OE_Default, then the pParse->onError parameter
   83556 ** is used.  Or if pParse->onError==OE_Default then the onError value
   83557 ** for the constraint is used.
   83558 **
   83559 ** The calling routine must open a read/write cursor for pTab with
   83560 ** cursor number "baseCur".  All indices of pTab must also have open
   83561 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
   83562 ** Except, if there is no possibility of a REPLACE action then
   83563 ** cursors do not need to be open for indices where aRegIdx[i]==0.
   83564 */
   83565 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   83566   Parse *pParse,      /* The parser context */
   83567   Table *pTab,        /* the table into which we are inserting */
   83568   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   83569   int regRowid,       /* Index of the range of input registers */
   83570   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   83571   int rowidChng,      /* True if the rowid might collide with existing entry */
   83572   int isUpdate,       /* True for UPDATE, False for INSERT */
   83573   int overrideError,  /* Override onError to this if not OE_Default */
   83574   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
   83575   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
   83576 ){
   83577   int i;              /* loop counter */
   83578   Vdbe *v;            /* VDBE under constrution */
   83579   int nCol;           /* Number of columns */
   83580   int onError;        /* Conflict resolution strategy */
   83581   int j1;             /* Addresss of jump instruction */
   83582   int j2 = 0, j3;     /* Addresses of jump instructions */
   83583   int regData;        /* Register containing first data column */
   83584   int iCur;           /* Table cursor number */
   83585   Index *pIdx;         /* Pointer to one of the indices */
   83586   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   83587   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
   83588 
   83589   v = sqlite3GetVdbe(pParse);
   83590   assert( v!=0 );
   83591   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   83592   nCol = pTab->nCol;
   83593   regData = regRowid + 1;
   83594 
   83595   /* Test all NOT NULL constraints.
   83596   */
   83597   for(i=0; i<nCol; i++){
   83598     if( i==pTab->iPKey ){
   83599       continue;
   83600     }
   83601     onError = pTab->aCol[i].notNull;
   83602     if( onError==OE_None ) continue;
   83603     if( overrideError!=OE_Default ){
   83604       onError = overrideError;
   83605     }else if( onError==OE_Default ){
   83606       onError = OE_Abort;
   83607     }
   83608     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
   83609       onError = OE_Abort;
   83610     }
   83611     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   83612         || onError==OE_Ignore || onError==OE_Replace );
   83613     switch( onError ){
   83614       case OE_Abort:
   83615         sqlite3MayAbort(pParse);
   83616       case OE_Rollback:
   83617       case OE_Fail: {
   83618         char *zMsg;
   83619         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
   83620                                   SQLITE_CONSTRAINT, onError, regData+i);
   83621         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
   83622                               pTab->zName, pTab->aCol[i].zName);
   83623         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
   83624         break;
   83625       }
   83626       case OE_Ignore: {
   83627         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
   83628         break;
   83629       }
   83630       default: {
   83631         assert( onError==OE_Replace );
   83632         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
   83633         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
   83634         sqlite3VdbeJumpHere(v, j1);
   83635         break;
   83636       }
   83637     }
   83638   }
   83639 
   83640   /* Test all CHECK constraints
   83641   */
   83642 #ifndef SQLITE_OMIT_CHECK
   83643   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
   83644     int allOk = sqlite3VdbeMakeLabel(v);
   83645     pParse->ckBase = regData;
   83646     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
   83647     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
   83648     if( onError==OE_Ignore ){
   83649       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   83650     }else{
   83651       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
   83652       sqlite3HaltConstraint(pParse, onError, 0, 0);
   83653     }
   83654     sqlite3VdbeResolveLabel(v, allOk);
   83655   }
   83656 #endif /* !defined(SQLITE_OMIT_CHECK) */
   83657 
   83658   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
   83659   ** of the new record does not previously exist.  Except, if this
   83660   ** is an UPDATE and the primary key is not changing, that is OK.
   83661   */
   83662   if( rowidChng ){
   83663     onError = pTab->keyConf;
   83664     if( overrideError!=OE_Default ){
   83665       onError = overrideError;
   83666     }else if( onError==OE_Default ){
   83667       onError = OE_Abort;
   83668     }
   83669 
   83670     if( isUpdate ){
   83671       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
   83672     }
   83673     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
   83674     switch( onError ){
   83675       default: {
   83676         onError = OE_Abort;
   83677         /* Fall thru into the next case */
   83678       }
   83679       case OE_Rollback:
   83680       case OE_Abort:
   83681       case OE_Fail: {
   83682         sqlite3HaltConstraint(
   83683           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   83684         break;
   83685       }
   83686       case OE_Replace: {
   83687         /* If there are DELETE triggers on this table and the
   83688         ** recursive-triggers flag is set, call GenerateRowDelete() to
   83689         ** remove the conflicting row from the the table. This will fire
   83690         ** the triggers and remove both the table and index b-tree entries.
   83691         **
   83692         ** Otherwise, if there are no triggers or the recursive-triggers
   83693         ** flag is not set, but the table has one or more indexes, call
   83694         ** GenerateRowIndexDelete(). This removes the index b-tree entries
   83695         ** only. The table b-tree entry will be replaced by the new entry
   83696         ** when it is inserted.
   83697         **
   83698         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
   83699         ** also invoke MultiWrite() to indicate that this VDBE may require
   83700         ** statement rollback (if the statement is aborted after the delete
   83701         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
   83702         ** but being more selective here allows statements like:
   83703         **
   83704         **   REPLACE INTO t(rowid) VALUES($newrowid)
   83705         **
   83706         ** to run without a statement journal if there are no indexes on the
   83707         ** table.
   83708         */
   83709         Trigger *pTrigger = 0;
   83710         if( pParse->db->flags&SQLITE_RecTriggers ){
   83711           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   83712         }
   83713         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
   83714           sqlite3MultiWrite(pParse);
   83715           sqlite3GenerateRowDelete(
   83716               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
   83717           );
   83718         }else if( pTab->pIndex ){
   83719           sqlite3MultiWrite(pParse);
   83720           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
   83721         }
   83722         seenReplace = 1;
   83723         break;
   83724       }
   83725       case OE_Ignore: {
   83726         assert( seenReplace==0 );
   83727         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   83728         break;
   83729       }
   83730     }
   83731     sqlite3VdbeJumpHere(v, j3);
   83732     if( isUpdate ){
   83733       sqlite3VdbeJumpHere(v, j2);
   83734     }
   83735   }
   83736 
   83737   /* Test all UNIQUE constraints by creating entries for each UNIQUE
   83738   ** index and making sure that duplicate entries do not already exist.
   83739   ** Add the new records to the indices as we go.
   83740   */
   83741   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
   83742     int regIdx;
   83743     int regR;
   83744 
   83745     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
   83746 
   83747     /* Create a key for accessing the index entry */
   83748     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
   83749     for(i=0; i<pIdx->nColumn; i++){
   83750       int idx = pIdx->aiColumn[i];
   83751       if( idx==pTab->iPKey ){
   83752         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   83753       }else{
   83754         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
   83755       }
   83756     }
   83757     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
   83758     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
   83759     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
   83760     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
   83761 
   83762     /* Find out what action to take in case there is an indexing conflict */
   83763     onError = pIdx->onError;
   83764     if( onError==OE_None ){
   83765       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   83766       continue;  /* pIdx is not a UNIQUE index */
   83767     }
   83768     if( overrideError!=OE_Default ){
   83769       onError = overrideError;
   83770     }else if( onError==OE_Default ){
   83771       onError = OE_Abort;
   83772     }
   83773     if( seenReplace ){
   83774       if( onError==OE_Ignore ) onError = OE_Replace;
   83775       else if( onError==OE_Fail ) onError = OE_Abort;
   83776     }
   83777 
   83778     /* Check to see if the new index entry will be unique */
   83779     regR = sqlite3GetTempReg(pParse);
   83780     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
   83781     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
   83782                            regR, SQLITE_INT_TO_PTR(regIdx),
   83783                            P4_INT32);
   83784     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
   83785 
   83786     /* Generate code that executes if the new index entry is not unique */
   83787     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
   83788         || onError==OE_Ignore || onError==OE_Replace );
   83789     switch( onError ){
   83790       case OE_Rollback:
   83791       case OE_Abort:
   83792       case OE_Fail: {
   83793         int j;
   83794         StrAccum errMsg;
   83795         const char *zSep;
   83796         char *zErr;
   83797 
   83798         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
   83799         errMsg.db = pParse->db;
   83800         zSep = pIdx->nColumn>1 ? "columns " : "column ";
   83801         for(j=0; j<pIdx->nColumn; j++){
   83802           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
   83803           sqlite3StrAccumAppend(&errMsg, zSep, -1);
   83804           zSep = ", ";
   83805           sqlite3StrAccumAppend(&errMsg, zCol, -1);
   83806         }
   83807         sqlite3StrAccumAppend(&errMsg,
   83808             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
   83809         zErr = sqlite3StrAccumFinish(&errMsg);
   83810         sqlite3HaltConstraint(pParse, onError, zErr, 0);
   83811         sqlite3DbFree(errMsg.db, zErr);
   83812         break;
   83813       }
   83814       case OE_Ignore: {
   83815         assert( seenReplace==0 );
   83816         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
   83817         break;
   83818       }
   83819       default: {
   83820         Trigger *pTrigger = 0;
   83821         assert( onError==OE_Replace );
   83822         sqlite3MultiWrite(pParse);
   83823         if( pParse->db->flags&SQLITE_RecTriggers ){
   83824           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
   83825         }
   83826         sqlite3GenerateRowDelete(
   83827             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
   83828         );
   83829         seenReplace = 1;
   83830         break;
   83831       }
   83832     }
   83833     sqlite3VdbeJumpHere(v, j3);
   83834     sqlite3ReleaseTempReg(pParse, regR);
   83835   }
   83836 
   83837   if( pbMayReplace ){
   83838     *pbMayReplace = seenReplace;
   83839   }
   83840 }
   83841 
   83842 /*
   83843 ** This routine generates code to finish the INSERT or UPDATE operation
   83844 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
   83845 ** A consecutive range of registers starting at regRowid contains the
   83846 ** rowid and the content to be inserted.
   83847 **
   83848 ** The arguments to this routine should be the same as the first six
   83849 ** arguments to sqlite3GenerateConstraintChecks.
   83850 */
   83851 SQLITE_PRIVATE void sqlite3CompleteInsertion(
   83852   Parse *pParse,      /* The parser context */
   83853   Table *pTab,        /* the table into which we are inserting */
   83854   int baseCur,        /* Index of a read/write cursor pointing at pTab */
   83855   int regRowid,       /* Range of content */
   83856   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
   83857   int isUpdate,       /* True for UPDATE, False for INSERT */
   83858   int appendBias,     /* True if this is likely to be an append */
   83859   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
   83860 ){
   83861   int i;
   83862   Vdbe *v;
   83863   int nIdx;
   83864   Index *pIdx;
   83865   u8 pik_flags;
   83866   int regData;
   83867   int regRec;
   83868 
   83869   v = sqlite3GetVdbe(pParse);
   83870   assert( v!=0 );
   83871   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   83872   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   83873   for(i=nIdx-1; i>=0; i--){
   83874     if( aRegIdx[i]==0 ) continue;
   83875     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
   83876     if( useSeekResult ){
   83877       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   83878     }
   83879   }
   83880   regData = regRowid + 1;
   83881   regRec = sqlite3GetTempReg(pParse);
   83882   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
   83883   sqlite3TableAffinityStr(v, pTab);
   83884   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
   83885   if( pParse->nested ){
   83886     pik_flags = 0;
   83887   }else{
   83888     pik_flags = OPFLAG_NCHANGE;
   83889     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
   83890   }
   83891   if( appendBias ){
   83892     pik_flags |= OPFLAG_APPEND;
   83893   }
   83894   if( useSeekResult ){
   83895     pik_flags |= OPFLAG_USESEEKRESULT;
   83896   }
   83897   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
   83898   if( !pParse->nested ){
   83899     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
   83900   }
   83901   sqlite3VdbeChangeP5(v, pik_flags);
   83902 }
   83903 
   83904 /*
   83905 ** Generate code that will open cursors for a table and for all
   83906 ** indices of that table.  The "baseCur" parameter is the cursor number used
   83907 ** for the table.  Indices are opened on subsequent cursors.
   83908 **
   83909 ** Return the number of indices on the table.
   83910 */
   83911 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
   83912   Parse *pParse,   /* Parsing context */
   83913   Table *pTab,     /* Table to be opened */
   83914   int baseCur,     /* Cursor number assigned to the table */
   83915   int op           /* OP_OpenRead or OP_OpenWrite */
   83916 ){
   83917   int i;
   83918   int iDb;
   83919   Index *pIdx;
   83920   Vdbe *v;
   83921 
   83922   if( IsVirtual(pTab) ) return 0;
   83923   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   83924   v = sqlite3GetVdbe(pParse);
   83925   assert( v!=0 );
   83926   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
   83927   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   83928     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   83929     assert( pIdx->pSchema==pTab->pSchema );
   83930     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
   83931                       (char*)pKey, P4_KEYINFO_HANDOFF);
   83932     VdbeComment((v, "%s", pIdx->zName));
   83933   }
   83934   if( pParse->nTab<baseCur+i ){
   83935     pParse->nTab = baseCur+i;
   83936   }
   83937   return i-1;
   83938 }
   83939 
   83940 
   83941 #ifdef SQLITE_TEST
   83942 /*
   83943 ** The following global variable is incremented whenever the
   83944 ** transfer optimization is used.  This is used for testing
   83945 ** purposes only - to make sure the transfer optimization really
   83946 ** is happening when it is suppose to.
   83947 */
   83948 SQLITE_API int sqlite3_xferopt_count;
   83949 #endif /* SQLITE_TEST */
   83950 
   83951 
   83952 #ifndef SQLITE_OMIT_XFER_OPT
   83953 /*
   83954 ** Check to collation names to see if they are compatible.
   83955 */
   83956 static int xferCompatibleCollation(const char *z1, const char *z2){
   83957   if( z1==0 ){
   83958     return z2==0;
   83959   }
   83960   if( z2==0 ){
   83961     return 0;
   83962   }
   83963   return sqlite3StrICmp(z1, z2)==0;
   83964 }
   83965 
   83966 
   83967 /*
   83968 ** Check to see if index pSrc is compatible as a source of data
   83969 ** for index pDest in an insert transfer optimization.  The rules
   83970 ** for a compatible index:
   83971 **
   83972 **    *   The index is over the same set of columns
   83973 **    *   The same DESC and ASC markings occurs on all columns
   83974 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
   83975 **    *   The same collating sequence on each column
   83976 */
   83977 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   83978   int i;
   83979   assert( pDest && pSrc );
   83980   assert( pDest->pTable!=pSrc->pTable );
   83981   if( pDest->nColumn!=pSrc->nColumn ){
   83982     return 0;   /* Different number of columns */
   83983   }
   83984   if( pDest->onError!=pSrc->onError ){
   83985     return 0;   /* Different conflict resolution strategies */
   83986   }
   83987   for(i=0; i<pSrc->nColumn; i++){
   83988     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
   83989       return 0;   /* Different columns indexed */
   83990     }
   83991     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
   83992       return 0;   /* Different sort orders */
   83993     }
   83994     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
   83995       return 0;   /* Different collating sequences */
   83996     }
   83997   }
   83998 
   83999   /* If no test above fails then the indices must be compatible */
   84000   return 1;
   84001 }
   84002 
   84003 /*
   84004 ** Attempt the transfer optimization on INSERTs of the form
   84005 **
   84006 **     INSERT INTO tab1 SELECT * FROM tab2;
   84007 **
   84008 ** This optimization is only attempted if
   84009 **
   84010 **    (1)  tab1 and tab2 have identical schemas including all the
   84011 **         same indices and constraints
   84012 **
   84013 **    (2)  tab1 and tab2 are different tables
   84014 **
   84015 **    (3)  There must be no triggers on tab1
   84016 **
   84017 **    (4)  The result set of the SELECT statement is "*"
   84018 **
   84019 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
   84020 **         or LIMIT clause.
   84021 **
   84022 **    (6)  The SELECT statement is a simple (not a compound) select that
   84023 **         contains only tab2 in its FROM clause
   84024 **
   84025 ** This method for implementing the INSERT transfers raw records from
   84026 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
   84027 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
   84028 ** the resulting tab1 has much less fragmentation.
   84029 **
   84030 ** This routine returns TRUE if the optimization is attempted.  If any
   84031 ** of the conditions above fail so that the optimization should not
   84032 ** be attempted, then this routine returns FALSE.
   84033 */
   84034 static int xferOptimization(
   84035   Parse *pParse,        /* Parser context */
   84036   Table *pDest,         /* The table we are inserting into */
   84037   Select *pSelect,      /* A SELECT statement to use as the data source */
   84038   int onError,          /* How to handle constraint errors */
   84039   int iDbDest           /* The database of pDest */
   84040 ){
   84041   ExprList *pEList;                /* The result set of the SELECT */
   84042   Table *pSrc;                     /* The table in the FROM clause of SELECT */
   84043   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
   84044   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
   84045   int i;                           /* Loop counter */
   84046   int iDbSrc;                      /* The database of pSrc */
   84047   int iSrc, iDest;                 /* Cursors from source and destination */
   84048   int addr1, addr2;                /* Loop addresses */
   84049   int emptyDestTest;               /* Address of test for empty pDest */
   84050   int emptySrcTest;                /* Address of test for empty pSrc */
   84051   Vdbe *v;                         /* The VDBE we are building */
   84052   KeyInfo *pKey;                   /* Key information for an index */
   84053   int regAutoinc;                  /* Memory register used by AUTOINC */
   84054   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
   84055   int regData, regRowid;           /* Registers holding data and rowid */
   84056 
   84057   if( pSelect==0 ){
   84058     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
   84059   }
   84060   if( sqlite3TriggerList(pParse, pDest) ){
   84061     return 0;   /* tab1 must not have triggers */
   84062   }
   84063 #ifndef SQLITE_OMIT_VIRTUALTABLE
   84064   if( pDest->tabFlags & TF_Virtual ){
   84065     return 0;   /* tab1 must not be a virtual table */
   84066   }
   84067 #endif
   84068   if( onError==OE_Default ){
   84069     onError = OE_Abort;
   84070   }
   84071   if( onError!=OE_Abort && onError!=OE_Rollback ){
   84072     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
   84073   }
   84074   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
   84075   if( pSelect->pSrc->nSrc!=1 ){
   84076     return 0;   /* FROM clause must have exactly one term */
   84077   }
   84078   if( pSelect->pSrc->a[0].pSelect ){
   84079     return 0;   /* FROM clause cannot contain a subquery */
   84080   }
   84081   if( pSelect->pWhere ){
   84082     return 0;   /* SELECT may not have a WHERE clause */
   84083   }
   84084   if( pSelect->pOrderBy ){
   84085     return 0;   /* SELECT may not have an ORDER BY clause */
   84086   }
   84087   /* Do not need to test for a HAVING clause.  If HAVING is present but
   84088   ** there is no ORDER BY, we will get an error. */
   84089   if( pSelect->pGroupBy ){
   84090     return 0;   /* SELECT may not have a GROUP BY clause */
   84091   }
   84092   if( pSelect->pLimit ){
   84093     return 0;   /* SELECT may not have a LIMIT clause */
   84094   }
   84095   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
   84096   if( pSelect->pPrior ){
   84097     return 0;   /* SELECT may not be a compound query */
   84098   }
   84099   if( pSelect->selFlags & SF_Distinct ){
   84100     return 0;   /* SELECT may not be DISTINCT */
   84101   }
   84102   pEList = pSelect->pEList;
   84103   assert( pEList!=0 );
   84104   if( pEList->nExpr!=1 ){
   84105     return 0;   /* The result set must have exactly one column */
   84106   }
   84107   assert( pEList->a[0].pExpr );
   84108   if( pEList->a[0].pExpr->op!=TK_ALL ){
   84109     return 0;   /* The result set must be the special operator "*" */
   84110   }
   84111 
   84112   /* At this point we have established that the statement is of the
   84113   ** correct syntactic form to participate in this optimization.  Now
   84114   ** we have to check the semantics.
   84115   */
   84116   pItem = pSelect->pSrc->a;
   84117   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
   84118   if( pSrc==0 ){
   84119     return 0;   /* FROM clause does not contain a real table */
   84120   }
   84121   if( pSrc==pDest ){
   84122     return 0;   /* tab1 and tab2 may not be the same table */
   84123   }
   84124 #ifndef SQLITE_OMIT_VIRTUALTABLE
   84125   if( pSrc->tabFlags & TF_Virtual ){
   84126     return 0;   /* tab2 must not be a virtual table */
   84127   }
   84128 #endif
   84129   if( pSrc->pSelect ){
   84130     return 0;   /* tab2 may not be a view */
   84131   }
   84132   if( pDest->nCol!=pSrc->nCol ){
   84133     return 0;   /* Number of columns must be the same in tab1 and tab2 */
   84134   }
   84135   if( pDest->iPKey!=pSrc->iPKey ){
   84136     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
   84137   }
   84138   for(i=0; i<pDest->nCol; i++){
   84139     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
   84140       return 0;    /* Affinity must be the same on all columns */
   84141     }
   84142     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
   84143       return 0;    /* Collating sequence must be the same on all columns */
   84144     }
   84145     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
   84146       return 0;    /* tab2 must be NOT NULL if tab1 is */
   84147     }
   84148   }
   84149   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   84150     if( pDestIdx->onError!=OE_None ){
   84151       destHasUniqueIdx = 1;
   84152     }
   84153     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
   84154       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   84155     }
   84156     if( pSrcIdx==0 ){
   84157       return 0;    /* pDestIdx has no corresponding index in pSrc */
   84158     }
   84159   }
   84160 #ifndef SQLITE_OMIT_CHECK
   84161   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
   84162     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
   84163   }
   84164 #endif
   84165 
   84166   /* If we get this far, it means either:
   84167   **
   84168   **    *   We can always do the transfer if the table contains an
   84169   **        an integer primary key
   84170   **
   84171   **    *   We can conditionally do the transfer if the destination
   84172   **        table is empty.
   84173   */
   84174 #ifdef SQLITE_TEST
   84175   sqlite3_xferopt_count++;
   84176 #endif
   84177   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
   84178   v = sqlite3GetVdbe(pParse);
   84179   sqlite3CodeVerifySchema(pParse, iDbSrc);
   84180   iSrc = pParse->nTab++;
   84181   iDest = pParse->nTab++;
   84182   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
   84183   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
   84184   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
   84185     /* If tables do not have an INTEGER PRIMARY KEY and there
   84186     ** are indices to be copied and the destination is not empty,
   84187     ** we have to disallow the transfer optimization because the
   84188     ** the rowids might change which will mess up indexing.
   84189     **
   84190     ** Or if the destination has a UNIQUE index and is not empty,
   84191     ** we also disallow the transfer optimization because we cannot
   84192     ** insure that all entries in the union of DEST and SRC will be
   84193     ** unique.
   84194     */
   84195     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
   84196     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
   84197     sqlite3VdbeJumpHere(v, addr1);
   84198   }else{
   84199     emptyDestTest = 0;
   84200   }
   84201   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
   84202   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   84203   regData = sqlite3GetTempReg(pParse);
   84204   regRowid = sqlite3GetTempReg(pParse);
   84205   if( pDest->iPKey>=0 ){
   84206     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   84207     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
   84208     sqlite3HaltConstraint(
   84209         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
   84210     sqlite3VdbeJumpHere(v, addr2);
   84211     autoIncStep(pParse, regAutoinc, regRowid);
   84212   }else if( pDest->pIndex==0 ){
   84213     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
   84214   }else{
   84215     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
   84216     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
   84217   }
   84218   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
   84219   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
   84220   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
   84221   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
   84222   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
   84223   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
   84224     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
   84225       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
   84226     }
   84227     assert( pSrcIdx );
   84228     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   84229     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   84230     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
   84231     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
   84232                       (char*)pKey, P4_KEYINFO_HANDOFF);
   84233     VdbeComment((v, "%s", pSrcIdx->zName));
   84234     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
   84235     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
   84236                       (char*)pKey, P4_KEYINFO_HANDOFF);
   84237     VdbeComment((v, "%s", pDestIdx->zName));
   84238     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
   84239     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
   84240     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
   84241     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
   84242     sqlite3VdbeJumpHere(v, addr1);
   84243   }
   84244   sqlite3VdbeJumpHere(v, emptySrcTest);
   84245   sqlite3ReleaseTempReg(pParse, regRowid);
   84246   sqlite3ReleaseTempReg(pParse, regData);
   84247   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
   84248   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   84249   if( emptyDestTest ){
   84250     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
   84251     sqlite3VdbeJumpHere(v, emptyDestTest);
   84252     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
   84253     return 0;
   84254   }else{
   84255     return 1;
   84256   }
   84257 }
   84258 #endif /* SQLITE_OMIT_XFER_OPT */
   84259 
   84260 /************** End of insert.c **********************************************/
   84261 /************** Begin file legacy.c ******************************************/
   84262 /*
   84263 ** 2001 September 15
   84264 **
   84265 ** The author disclaims copyright to this source code.  In place of
   84266 ** a legal notice, here is a blessing:
   84267 **
   84268 **    May you do good and not evil.
   84269 **    May you find forgiveness for yourself and forgive others.
   84270 **    May you share freely, never taking more than you give.
   84271 **
   84272 *************************************************************************
   84273 ** Main file for the SQLite library.  The routines in this file
   84274 ** implement the programmer interface to the library.  Routines in
   84275 ** other files are for internal use by SQLite and should not be
   84276 ** accessed by users of the library.
   84277 */
   84278 
   84279 
   84280 /*
   84281 ** Execute SQL code.  Return one of the SQLITE_ success/failure
   84282 ** codes.  Also write an error message into memory obtained from
   84283 ** malloc() and make *pzErrMsg point to that message.
   84284 **
   84285 ** If the SQL is a query, then for each row in the query result
   84286 ** the xCallback() function is called.  pArg becomes the first
   84287 ** argument to xCallback().  If xCallback=NULL then no callback
   84288 ** is invoked, even for queries.
   84289 */
   84290 SQLITE_API int sqlite3_exec(
   84291   sqlite3 *db,                /* The database on which the SQL executes */
   84292   const char *zSql,           /* The SQL to be executed */
   84293   sqlite3_callback xCallback, /* Invoke this callback routine */
   84294   void *pArg,                 /* First argument to xCallback() */
   84295   char **pzErrMsg             /* Write error messages here */
   84296 ){
   84297   int rc = SQLITE_OK;         /* Return code */
   84298   const char *zLeftover;      /* Tail of unprocessed SQL */
   84299   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
   84300   char **azCols = 0;          /* Names of result columns */
   84301   int nRetry = 0;             /* Number of retry attempts */
   84302   int callbackIsInit;         /* True if callback data is initialized */
   84303 
   84304   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
   84305   if( zSql==0 ) zSql = "";
   84306 
   84307   sqlite3_mutex_enter(db->mutex);
   84308   sqlite3Error(db, SQLITE_OK, 0);
   84309   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
   84310     int nCol;
   84311     char **azVals = 0;
   84312 
   84313     pStmt = 0;
   84314     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
   84315     assert( rc==SQLITE_OK || pStmt==0 );
   84316     if( rc!=SQLITE_OK ){
   84317       continue;
   84318     }
   84319     if( !pStmt ){
   84320       /* this happens for a comment or white-space */
   84321       zSql = zLeftover;
   84322       continue;
   84323     }
   84324 
   84325     callbackIsInit = 0;
   84326     nCol = sqlite3_column_count(pStmt);
   84327 
   84328     while( 1 ){
   84329       int i;
   84330       rc = sqlite3_step(pStmt);
   84331 
   84332       /* Invoke the callback function if required */
   84333       if( xCallback && (SQLITE_ROW==rc ||
   84334           (SQLITE_DONE==rc && !callbackIsInit
   84335                            && db->flags&SQLITE_NullCallback)) ){
   84336         if( !callbackIsInit ){
   84337           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
   84338           if( azCols==0 ){
   84339             goto exec_out;
   84340           }
   84341           for(i=0; i<nCol; i++){
   84342             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
   84343             /* sqlite3VdbeSetColName() installs column names as UTF8
   84344             ** strings so there is no way for sqlite3_column_name() to fail. */
   84345             assert( azCols[i]!=0 );
   84346           }
   84347           callbackIsInit = 1;
   84348         }
   84349         if( rc==SQLITE_ROW ){
   84350           azVals = &azCols[nCol];
   84351           for(i=0; i<nCol; i++){
   84352             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
   84353             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
   84354               db->mallocFailed = 1;
   84355               goto exec_out;
   84356             }
   84357           }
   84358         }
   84359         if( xCallback(pArg, nCol, azVals, azCols) ){
   84360           rc = SQLITE_ABORT;
   84361           sqlite3VdbeFinalize((Vdbe *)pStmt);
   84362           pStmt = 0;
   84363           sqlite3Error(db, SQLITE_ABORT, 0);
   84364           goto exec_out;
   84365         }
   84366       }
   84367 
   84368       if( rc!=SQLITE_ROW ){
   84369         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
   84370         pStmt = 0;
   84371         if( rc!=SQLITE_SCHEMA ){
   84372           nRetry = 0;
   84373           zSql = zLeftover;
   84374           while( sqlite3Isspace(zSql[0]) ) zSql++;
   84375         }
   84376         break;
   84377       }
   84378     }
   84379 
   84380     sqlite3DbFree(db, azCols);
   84381     azCols = 0;
   84382   }
   84383 
   84384 exec_out:
   84385   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
   84386   sqlite3DbFree(db, azCols);
   84387 
   84388   rc = sqlite3ApiExit(db, rc);
   84389   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
   84390     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
   84391     *pzErrMsg = sqlite3Malloc(nErrMsg);
   84392     if( *pzErrMsg ){
   84393       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
   84394     }else{
   84395       rc = SQLITE_NOMEM;
   84396       sqlite3Error(db, SQLITE_NOMEM, 0);
   84397     }
   84398   }else if( pzErrMsg ){
   84399     *pzErrMsg = 0;
   84400   }
   84401 
   84402   assert( (rc&db->errMask)==rc );
   84403   sqlite3_mutex_leave(db->mutex);
   84404   return rc;
   84405 }
   84406 
   84407 /************** End of legacy.c **********************************************/
   84408 /************** Begin file loadext.c *****************************************/
   84409 /*
   84410 ** 2006 June 7
   84411 **
   84412 ** The author disclaims copyright to this source code.  In place of
   84413 ** a legal notice, here is a blessing:
   84414 **
   84415 **    May you do good and not evil.
   84416 **    May you find forgiveness for yourself and forgive others.
   84417 **    May you share freely, never taking more than you give.
   84418 **
   84419 *************************************************************************
   84420 ** This file contains code used to dynamically load extensions into
   84421 ** the SQLite library.
   84422 */
   84423 
   84424 #ifndef SQLITE_CORE
   84425   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
   84426 #endif
   84427 /************** Include sqlite3ext.h in the middle of loadext.c **************/
   84428 /************** Begin file sqlite3ext.h **************************************/
   84429 /*
   84430 ** 2006 June 7
   84431 **
   84432 ** The author disclaims copyright to this source code.  In place of
   84433 ** a legal notice, here is a blessing:
   84434 **
   84435 **    May you do good and not evil.
   84436 **    May you find forgiveness for yourself and forgive others.
   84437 **    May you share freely, never taking more than you give.
   84438 **
   84439 *************************************************************************
   84440 ** This header file defines the SQLite interface for use by
   84441 ** shared libraries that want to be imported as extensions into
   84442 ** an SQLite instance.  Shared libraries that intend to be loaded
   84443 ** as extensions by SQLite should #include this file instead of
   84444 ** sqlite3.h.
   84445 */
   84446 #ifndef _SQLITE3EXT_H_
   84447 #define _SQLITE3EXT_H_
   84448 
   84449 typedef struct sqlite3_api_routines sqlite3_api_routines;
   84450 
   84451 /*
   84452 ** The following structure holds pointers to all of the SQLite API
   84453 ** routines.
   84454 **
   84455 ** WARNING:  In order to maintain backwards compatibility, add new
   84456 ** interfaces to the end of this structure only.  If you insert new
   84457 ** interfaces in the middle of this structure, then older different
   84458 ** versions of SQLite will not be able to load each others' shared
   84459 ** libraries!
   84460 */
   84461 struct sqlite3_api_routines {
   84462   void * (*aggregate_context)(sqlite3_context*,int nBytes);
   84463   int  (*aggregate_count)(sqlite3_context*);
   84464   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
   84465   int  (*bind_double)(sqlite3_stmt*,int,double);
   84466   int  (*bind_int)(sqlite3_stmt*,int,int);
   84467   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
   84468   int  (*bind_null)(sqlite3_stmt*,int);
   84469   int  (*bind_parameter_count)(sqlite3_stmt*);
   84470   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
   84471   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
   84472   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
   84473   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
   84474   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
   84475   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
   84476   int  (*busy_timeout)(sqlite3*,int ms);
   84477   int  (*changes)(sqlite3*);
   84478   int  (*close)(sqlite3*);
   84479   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
   84480   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
   84481   const void * (*column_blob)(sqlite3_stmt*,int iCol);
   84482   int  (*column_bytes)(sqlite3_stmt*,int iCol);
   84483   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
   84484   int  (*column_count)(sqlite3_stmt*pStmt);
   84485   const char * (*column_database_name)(sqlite3_stmt*,int);
   84486   const void * (*column_database_name16)(sqlite3_stmt*,int);
   84487   const char * (*column_decltype)(sqlite3_stmt*,int i);
   84488   const void * (*column_decltype16)(sqlite3_stmt*,int);
   84489   double  (*column_double)(sqlite3_stmt*,int iCol);
   84490   int  (*column_int)(sqlite3_stmt*,int iCol);
   84491   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
   84492   const char * (*column_name)(sqlite3_stmt*,int);
   84493   const void * (*column_name16)(sqlite3_stmt*,int);
   84494   const char * (*column_origin_name)(sqlite3_stmt*,int);
   84495   const void * (*column_origin_name16)(sqlite3_stmt*,int);
   84496   const char * (*column_table_name)(sqlite3_stmt*,int);
   84497   const void * (*column_table_name16)(sqlite3_stmt*,int);
   84498   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
   84499   const void * (*column_text16)(sqlite3_stmt*,int iCol);
   84500   int  (*column_type)(sqlite3_stmt*,int iCol);
   84501   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
   84502   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
   84503   int  (*complete)(const char*sql);
   84504   int  (*complete16)(const void*sql);
   84505   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
   84506   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
   84507   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*));
   84508   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*));
   84509   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
   84510   int  (*data_count)(sqlite3_stmt*pStmt);
   84511   sqlite3 * (*db_handle)(sqlite3_stmt*);
   84512   int (*declare_vtab)(sqlite3*,const char*);
   84513   int  (*enable_shared_cache)(int);
   84514   int  (*errcode)(sqlite3*db);
   84515   const char * (*errmsg)(sqlite3*);
   84516   const void * (*errmsg16)(sqlite3*);
   84517   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
   84518   int  (*expired)(sqlite3_stmt*);
   84519   int  (*finalize)(sqlite3_stmt*pStmt);
   84520   void  (*free)(void*);
   84521   void  (*free_table)(char**result);
   84522   int  (*get_autocommit)(sqlite3*);
   84523   void * (*get_auxdata)(sqlite3_context*,int);
   84524   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   84525   int  (*global_recover)(void);
   84526   void  (*interruptx)(sqlite3*);
   84527   sqlite_int64  (*last_insert_rowid)(sqlite3*);
   84528   const char * (*libversion)(void);
   84529   int  (*libversion_number)(void);
   84530   void *(*malloc)(int);
   84531   char * (*mprintf)(const char*,...);
   84532   int  (*open)(const char*,sqlite3**);
   84533   int  (*open16)(const void*,sqlite3**);
   84534   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   84535   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   84536   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   84537   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   84538   void *(*realloc)(void*,int);
   84539   int  (*reset)(sqlite3_stmt*pStmt);
   84540   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   84541   void  (*result_double)(sqlite3_context*,double);
   84542   void  (*result_error)(sqlite3_context*,const char*,int);
   84543   void  (*result_error16)(sqlite3_context*,const void*,int);
   84544   void  (*result_int)(sqlite3_context*,int);
   84545   void  (*result_int64)(sqlite3_context*,sqlite_int64);
   84546   void  (*result_null)(sqlite3_context*);
   84547   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   84548   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   84549   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   84550   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   84551   void  (*result_value)(sqlite3_context*,sqlite3_value*);
   84552   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   84553   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
   84554   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   84555   char * (*snprintf)(int,char*,const char*,...);
   84556   int  (*step)(sqlite3_stmt*);
   84557   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
   84558   void  (*thread_cleanup)(void);
   84559   int  (*total_changes)(sqlite3*);
   84560   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   84561   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   84562   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
   84563   void * (*user_data)(sqlite3_context*);
   84564   const void * (*value_blob)(sqlite3_value*);
   84565   int  (*value_bytes)(sqlite3_value*);
   84566   int  (*value_bytes16)(sqlite3_value*);
   84567   double  (*value_double)(sqlite3_value*);
   84568   int  (*value_int)(sqlite3_value*);
   84569   sqlite_int64  (*value_int64)(sqlite3_value*);
   84570   int  (*value_numeric_type)(sqlite3_value*);
   84571   const unsigned char * (*value_text)(sqlite3_value*);
   84572   const void * (*value_text16)(sqlite3_value*);
   84573   const void * (*value_text16be)(sqlite3_value*);
   84574   const void * (*value_text16le)(sqlite3_value*);
   84575   int  (*value_type)(sqlite3_value*);
   84576   char *(*vmprintf)(const char*,va_list);
   84577   /* Added ??? */
   84578   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   84579   /* Added by 3.3.13 */
   84580   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   84581   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   84582   int (*clear_bindings)(sqlite3_stmt*);
   84583   /* Added by 3.4.1 */
   84584   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
   84585   /* Added by 3.5.0 */
   84586   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   84587   int (*blob_bytes)(sqlite3_blob*);
   84588   int (*blob_close)(sqlite3_blob*);
   84589   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
   84590   int (*blob_read)(sqlite3_blob*,void*,int,int);
   84591   int (*blob_write)(sqlite3_blob*,const void*,int,int);
   84592   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
   84593   int (*file_control)(sqlite3*,const char*,int,void*);
   84594   sqlite3_int64 (*memory_highwater)(int);
   84595   sqlite3_int64 (*memory_used)(void);
   84596   sqlite3_mutex *(*mutex_alloc)(int);
   84597   void (*mutex_enter)(sqlite3_mutex*);
   84598   void (*mutex_free)(sqlite3_mutex*);
   84599   void (*mutex_leave)(sqlite3_mutex*);
   84600   int (*mutex_try)(sqlite3_mutex*);
   84601   int (*open_v2)(const char*,sqlite3**,int,const char*);
   84602   int (*release_memory)(int);
   84603   void (*result_error_nomem)(sqlite3_context*);
   84604   void (*result_error_toobig)(sqlite3_context*);
   84605   int (*sleep)(int);
   84606   void (*soft_heap_limit)(int);
   84607   sqlite3_vfs *(*vfs_find)(const char*);
   84608   int (*vfs_register)(sqlite3_vfs*,int);
   84609   int (*vfs_unregister)(sqlite3_vfs*);
   84610   int (*xthreadsafe)(void);
   84611   void (*result_zeroblob)(sqlite3_context*,int);
   84612   void (*result_error_code)(sqlite3_context*,int);
   84613   int (*test_control)(int, ...);
   84614   void (*randomness)(int,void*);
   84615   sqlite3 *(*context_db_handle)(sqlite3_context*);
   84616   int (*extended_result_codes)(sqlite3*,int);
   84617   int (*limit)(sqlite3*,int,int);
   84618   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   84619   const char *(*sql)(sqlite3_stmt*);
   84620   int (*status)(int,int*,int*,int);
   84621   int (*backup_finish)(sqlite3_backup*);
   84622   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   84623   int (*backup_pagecount)(sqlite3_backup*);
   84624   int (*backup_remaining)(sqlite3_backup*);
   84625   int (*backup_step)(sqlite3_backup*,int);
   84626   const char *(*compileoption_get)(int);
   84627   int (*compileoption_used)(const char*);
   84628   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
   84629   int (*db_config)(sqlite3*,int,...);
   84630   sqlite3_mutex *(*db_mutex)(sqlite3*);
   84631   int (*db_status)(sqlite3*,int,int*,int*,int);
   84632   int (*extended_errcode)(sqlite3*);
   84633   void (*log)(int,const char*,...);
   84634   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   84635   const char *(*sourceid)(void);
   84636   int (*stmt_status)(sqlite3_stmt*,int,int);
   84637   int (*strnicmp)(const char*,const char*,int);
   84638   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   84639   int (*wal_autocheckpoint)(sqlite3*,int);
   84640   int (*wal_checkpoint)(sqlite3*,const char*);
   84641   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   84642 };
   84643 
   84644 /*
   84645 ** The following macros redefine the API routines so that they are
   84646 ** redirected throught the global sqlite3_api structure.
   84647 **
   84648 ** This header file is also used by the loadext.c source file
   84649 ** (part of the main SQLite library - not an extension) so that
   84650 ** it can get access to the sqlite3_api_routines structure
   84651 ** definition.  But the main library does not want to redefine
   84652 ** the API.  So the redefinition macros are only valid if the
   84653 ** SQLITE_CORE macros is undefined.
   84654 */
   84655 #ifndef SQLITE_CORE
   84656 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   84657 #ifndef SQLITE_OMIT_DEPRECATED
   84658 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
   84659 #endif
   84660 #define sqlite3_bind_blob              sqlite3_api->bind_blob
   84661 #define sqlite3_bind_double            sqlite3_api->bind_double
   84662 #define sqlite3_bind_int               sqlite3_api->bind_int
   84663 #define sqlite3_bind_int64             sqlite3_api->bind_int64
   84664 #define sqlite3_bind_null              sqlite3_api->bind_null
   84665 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   84666 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   84667 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   84668 #define sqlite3_bind_text              sqlite3_api->bind_text
   84669 #define sqlite3_bind_text16            sqlite3_api->bind_text16
   84670 #define sqlite3_bind_value             sqlite3_api->bind_value
   84671 #define sqlite3_busy_handler           sqlite3_api->busy_handler
   84672 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   84673 #define sqlite3_changes                sqlite3_api->changes
   84674 #define sqlite3_close                  sqlite3_api->close
   84675 #define sqlite3_collation_needed       sqlite3_api->collation_needed
   84676 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   84677 #define sqlite3_column_blob            sqlite3_api->column_blob
   84678 #define sqlite3_column_bytes           sqlite3_api->column_bytes
   84679 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   84680 #define sqlite3_column_count           sqlite3_api->column_count
   84681 #define sqlite3_column_database_name   sqlite3_api->column_database_name
   84682 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   84683 #define sqlite3_column_decltype        sqlite3_api->column_decltype
   84684 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   84685 #define sqlite3_column_double          sqlite3_api->column_double
   84686 #define sqlite3_column_int             sqlite3_api->column_int
   84687 #define sqlite3_column_int64           sqlite3_api->column_int64
   84688 #define sqlite3_column_name            sqlite3_api->column_name
   84689 #define sqlite3_column_name16          sqlite3_api->column_name16
   84690 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   84691 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   84692 #define sqlite3_column_table_name      sqlite3_api->column_table_name
   84693 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   84694 #define sqlite3_column_text            sqlite3_api->column_text
   84695 #define sqlite3_column_text16          sqlite3_api->column_text16
   84696 #define sqlite3_column_type            sqlite3_api->column_type
   84697 #define sqlite3_column_value           sqlite3_api->column_value
   84698 #define sqlite3_commit_hook            sqlite3_api->commit_hook
   84699 #define sqlite3_complete               sqlite3_api->complete
   84700 #define sqlite3_complete16             sqlite3_api->complete16
   84701 #define sqlite3_create_collation       sqlite3_api->create_collation
   84702 #define sqlite3_create_collation16     sqlite3_api->create_collation16
   84703 #define sqlite3_create_function        sqlite3_api->create_function
   84704 #define sqlite3_create_function16      sqlite3_api->create_function16
   84705 #define sqlite3_create_module          sqlite3_api->create_module
   84706 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   84707 #define sqlite3_data_count             sqlite3_api->data_count
   84708 #define sqlite3_db_handle              sqlite3_api->db_handle
   84709 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   84710 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   84711 #define sqlite3_errcode                sqlite3_api->errcode
   84712 #define sqlite3_errmsg                 sqlite3_api->errmsg
   84713 #define sqlite3_errmsg16               sqlite3_api->errmsg16
   84714 #define sqlite3_exec                   sqlite3_api->exec
   84715 #ifndef SQLITE_OMIT_DEPRECATED
   84716 #define sqlite3_expired                sqlite3_api->expired
   84717 #endif
   84718 #define sqlite3_finalize               sqlite3_api->finalize
   84719 #define sqlite3_free                   sqlite3_api->free
   84720 #define sqlite3_free_table             sqlite3_api->free_table
   84721 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   84722 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   84723 #define sqlite3_get_table              sqlite3_api->get_table
   84724 #ifndef SQLITE_OMIT_DEPRECATED
   84725 #define sqlite3_global_recover         sqlite3_api->global_recover
   84726 #endif
   84727 #define sqlite3_interrupt              sqlite3_api->interruptx
   84728 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   84729 #define sqlite3_libversion             sqlite3_api->libversion
   84730 #define sqlite3_libversion_number      sqlite3_api->libversion_number
   84731 #define sqlite3_malloc                 sqlite3_api->malloc
   84732 #define sqlite3_mprintf                sqlite3_api->mprintf
   84733 #define sqlite3_open                   sqlite3_api->open
   84734 #define sqlite3_open16                 sqlite3_api->open16
   84735 #define sqlite3_prepare                sqlite3_api->prepare
   84736 #define sqlite3_prepare16              sqlite3_api->prepare16
   84737 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   84738 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   84739 #define sqlite3_profile                sqlite3_api->profile
   84740 #define sqlite3_progress_handler       sqlite3_api->progress_handler
   84741 #define sqlite3_realloc                sqlite3_api->realloc
   84742 #define sqlite3_reset                  sqlite3_api->reset
   84743 #define sqlite3_result_blob            sqlite3_api->result_blob
   84744 #define sqlite3_result_double          sqlite3_api->result_double
   84745 #define sqlite3_result_error           sqlite3_api->result_error
   84746 #define sqlite3_result_error16         sqlite3_api->result_error16
   84747 #define sqlite3_result_int             sqlite3_api->result_int
   84748 #define sqlite3_result_int64           sqlite3_api->result_int64
   84749 #define sqlite3_result_null            sqlite3_api->result_null
   84750 #define sqlite3_result_text            sqlite3_api->result_text
   84751 #define sqlite3_result_text16          sqlite3_api->result_text16
   84752 #define sqlite3_result_text16be        sqlite3_api->result_text16be
   84753 #define sqlite3_result_text16le        sqlite3_api->result_text16le
   84754 #define sqlite3_result_value           sqlite3_api->result_value
   84755 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   84756 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   84757 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   84758 #define sqlite3_snprintf               sqlite3_api->snprintf
   84759 #define sqlite3_step                   sqlite3_api->step
   84760 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   84761 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
   84762 #define sqlite3_total_changes          sqlite3_api->total_changes
   84763 #define sqlite3_trace                  sqlite3_api->trace
   84764 #ifndef SQLITE_OMIT_DEPRECATED
   84765 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
   84766 #endif
   84767 #define sqlite3_update_hook            sqlite3_api->update_hook
   84768 #define sqlite3_user_data              sqlite3_api->user_data
   84769 #define sqlite3_value_blob             sqlite3_api->value_blob
   84770 #define sqlite3_value_bytes            sqlite3_api->value_bytes
   84771 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   84772 #define sqlite3_value_double           sqlite3_api->value_double
   84773 #define sqlite3_value_int              sqlite3_api->value_int
   84774 #define sqlite3_value_int64            sqlite3_api->value_int64
   84775 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   84776 #define sqlite3_value_text             sqlite3_api->value_text
   84777 #define sqlite3_value_text16           sqlite3_api->value_text16
   84778 #define sqlite3_value_text16be         sqlite3_api->value_text16be
   84779 #define sqlite3_value_text16le         sqlite3_api->value_text16le
   84780 #define sqlite3_value_type             sqlite3_api->value_type
   84781 #define sqlite3_vmprintf               sqlite3_api->vmprintf
   84782 #define sqlite3_overload_function      sqlite3_api->overload_function
   84783 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   84784 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   84785 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   84786 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   84787 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   84788 #define sqlite3_blob_close             sqlite3_api->blob_close
   84789 #define sqlite3_blob_open              sqlite3_api->blob_open
   84790 #define sqlite3_blob_read              sqlite3_api->blob_read
   84791 #define sqlite3_blob_write             sqlite3_api->blob_write
   84792 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   84793 #define sqlite3_file_control           sqlite3_api->file_control
   84794 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   84795 #define sqlite3_memory_used            sqlite3_api->memory_used
   84796 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   84797 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   84798 #define sqlite3_mutex_free             sqlite3_api->mutex_free
   84799 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   84800 #define sqlite3_mutex_try              sqlite3_api->mutex_try
   84801 #define sqlite3_open_v2                sqlite3_api->open_v2
   84802 #define sqlite3_release_memory         sqlite3_api->release_memory
   84803 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   84804 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   84805 #define sqlite3_sleep                  sqlite3_api->sleep
   84806 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
   84807 #define sqlite3_vfs_find               sqlite3_api->vfs_find
   84808 #define sqlite3_vfs_register           sqlite3_api->vfs_register
   84809 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   84810 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   84811 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   84812 #define sqlite3_result_error_code      sqlite3_api->result_error_code
   84813 #define sqlite3_test_control           sqlite3_api->test_control
   84814 #define sqlite3_randomness             sqlite3_api->randomness
   84815 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   84816 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   84817 #define sqlite3_limit                  sqlite3_api->limit
   84818 #define sqlite3_next_stmt              sqlite3_api->next_stmt
   84819 #define sqlite3_sql                    sqlite3_api->sql
   84820 #define sqlite3_status                 sqlite3_api->status
   84821 #define sqlite3_backup_finish          sqlite3_api->backup_finish
   84822 #define sqlite3_backup_init            sqlite3_api->backup_init
   84823 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   84824 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   84825 #define sqlite3_backup_step            sqlite3_api->backup_step
   84826 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   84827 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   84828 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   84829 #define sqlite3_db_config              sqlite3_api->db_config
   84830 #define sqlite3_db_mutex               sqlite3_api->db_mutex
   84831 #define sqlite3_db_status              sqlite3_api->db_status
   84832 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   84833 #define sqlite3_log                    sqlite3_api->log
   84834 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   84835 #define sqlite3_sourceid               sqlite3_api->sourceid
   84836 #define sqlite3_stmt_status            sqlite3_api->stmt_status
   84837 #define sqlite3_strnicmp               sqlite3_api->strnicmp
   84838 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   84839 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   84840 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
   84841 #define sqlite3_wal_hook               sqlite3_api->wal_hook
   84842 #endif /* SQLITE_CORE */
   84843 
   84844 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
   84845 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
   84846 
   84847 #endif /* _SQLITE3EXT_H_ */
   84848 
   84849 /************** End of sqlite3ext.h ******************************************/
   84850 /************** Continuing where we left off in loadext.c ********************/
   84851 
   84852 #ifndef SQLITE_OMIT_LOAD_EXTENSION
   84853 
   84854 /*
   84855 ** Some API routines are omitted when various features are
   84856 ** excluded from a build of SQLite.  Substitute a NULL pointer
   84857 ** for any missing APIs.
   84858 */
   84859 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   84860 # define sqlite3_column_database_name   0
   84861 # define sqlite3_column_database_name16 0
   84862 # define sqlite3_column_table_name      0
   84863 # define sqlite3_column_table_name16    0
   84864 # define sqlite3_column_origin_name     0
   84865 # define sqlite3_column_origin_name16   0
   84866 # define sqlite3_table_column_metadata  0
   84867 #endif
   84868 
   84869 #ifdef SQLITE_OMIT_AUTHORIZATION
   84870 # define sqlite3_set_authorizer         0
   84871 #endif
   84872 
   84873 #ifdef SQLITE_OMIT_UTF16
   84874 # define sqlite3_bind_text16            0
   84875 # define sqlite3_collation_needed16     0
   84876 # define sqlite3_column_decltype16      0
   84877 # define sqlite3_column_name16          0
   84878 # define sqlite3_column_text16          0
   84879 # define sqlite3_complete16             0
   84880 # define sqlite3_create_collation16     0
   84881 # define sqlite3_create_function16      0
   84882 # define sqlite3_errmsg16               0
   84883 # define sqlite3_open16                 0
   84884 # define sqlite3_prepare16              0
   84885 # define sqlite3_prepare16_v2           0
   84886 # define sqlite3_result_error16         0
   84887 # define sqlite3_result_text16          0
   84888 # define sqlite3_result_text16be        0
   84889 # define sqlite3_result_text16le        0
   84890 # define sqlite3_value_text16           0
   84891 # define sqlite3_value_text16be         0
   84892 # define sqlite3_value_text16le         0
   84893 # define sqlite3_column_database_name16 0
   84894 # define sqlite3_column_table_name16    0
   84895 # define sqlite3_column_origin_name16   0
   84896 #endif
   84897 
   84898 #ifdef SQLITE_OMIT_COMPLETE
   84899 # define sqlite3_complete 0
   84900 # define sqlite3_complete16 0
   84901 #endif
   84902 
   84903 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
   84904 # define sqlite3_progress_handler 0
   84905 #endif
   84906 
   84907 #ifdef SQLITE_OMIT_VIRTUALTABLE
   84908 # define sqlite3_create_module 0
   84909 # define sqlite3_create_module_v2 0
   84910 # define sqlite3_declare_vtab 0
   84911 #endif
   84912 
   84913 #ifdef SQLITE_OMIT_SHARED_CACHE
   84914 # define sqlite3_enable_shared_cache 0
   84915 #endif
   84916 
   84917 #ifdef SQLITE_OMIT_TRACE
   84918 # define sqlite3_profile       0
   84919 # define sqlite3_trace         0
   84920 #endif
   84921 
   84922 #ifdef SQLITE_OMIT_GET_TABLE
   84923 # define sqlite3_free_table    0
   84924 # define sqlite3_get_table     0
   84925 #endif
   84926 
   84927 #ifdef SQLITE_OMIT_INCRBLOB
   84928 #define sqlite3_bind_zeroblob  0
   84929 #define sqlite3_blob_bytes     0
   84930 #define sqlite3_blob_close     0
   84931 #define sqlite3_blob_open      0
   84932 #define sqlite3_blob_read      0
   84933 #define sqlite3_blob_write     0
   84934 #endif
   84935 
   84936 /*
   84937 ** The following structure contains pointers to all SQLite API routines.
   84938 ** A pointer to this structure is passed into extensions when they are
   84939 ** loaded so that the extension can make calls back into the SQLite
   84940 ** library.
   84941 **
   84942 ** When adding new APIs, add them to the bottom of this structure
   84943 ** in order to preserve backwards compatibility.
   84944 **
   84945 ** Extensions that use newer APIs should first call the
   84946 ** sqlite3_libversion_number() to make sure that the API they
   84947 ** intend to use is supported by the library.  Extensions should
   84948 ** also check to make sure that the pointer to the function is
   84949 ** not NULL before calling it.
   84950 */
   84951 static const sqlite3_api_routines sqlite3Apis = {
   84952   sqlite3_aggregate_context,
   84953 #ifndef SQLITE_OMIT_DEPRECATED
   84954   sqlite3_aggregate_count,
   84955 #else
   84956   0,
   84957 #endif
   84958   sqlite3_bind_blob,
   84959   sqlite3_bind_double,
   84960   sqlite3_bind_int,
   84961   sqlite3_bind_int64,
   84962   sqlite3_bind_null,
   84963   sqlite3_bind_parameter_count,
   84964   sqlite3_bind_parameter_index,
   84965   sqlite3_bind_parameter_name,
   84966   sqlite3_bind_text,
   84967   sqlite3_bind_text16,
   84968   sqlite3_bind_value,
   84969   sqlite3_busy_handler,
   84970   sqlite3_busy_timeout,
   84971   sqlite3_changes,
   84972   sqlite3_close,
   84973   sqlite3_collation_needed,
   84974   sqlite3_collation_needed16,
   84975   sqlite3_column_blob,
   84976   sqlite3_column_bytes,
   84977   sqlite3_column_bytes16,
   84978   sqlite3_column_count,
   84979   sqlite3_column_database_name,
   84980   sqlite3_column_database_name16,
   84981   sqlite3_column_decltype,
   84982   sqlite3_column_decltype16,
   84983   sqlite3_column_double,
   84984   sqlite3_column_int,
   84985   sqlite3_column_int64,
   84986   sqlite3_column_name,
   84987   sqlite3_column_name16,
   84988   sqlite3_column_origin_name,
   84989   sqlite3_column_origin_name16,
   84990   sqlite3_column_table_name,
   84991   sqlite3_column_table_name16,
   84992   sqlite3_column_text,
   84993   sqlite3_column_text16,
   84994   sqlite3_column_type,
   84995   sqlite3_column_value,
   84996   sqlite3_commit_hook,
   84997   sqlite3_complete,
   84998   sqlite3_complete16,
   84999   sqlite3_create_collation,
   85000   sqlite3_create_collation16,
   85001   sqlite3_create_function,
   85002   sqlite3_create_function16,
   85003   sqlite3_create_module,
   85004   sqlite3_data_count,
   85005   sqlite3_db_handle,
   85006   sqlite3_declare_vtab,
   85007   sqlite3_enable_shared_cache,
   85008   sqlite3_errcode,
   85009   sqlite3_errmsg,
   85010   sqlite3_errmsg16,
   85011   sqlite3_exec,
   85012 #ifndef SQLITE_OMIT_DEPRECATED
   85013   sqlite3_expired,
   85014 #else
   85015   0,
   85016 #endif
   85017   sqlite3_finalize,
   85018   sqlite3_free,
   85019   sqlite3_free_table,
   85020   sqlite3_get_autocommit,
   85021   sqlite3_get_auxdata,
   85022   sqlite3_get_table,
   85023   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
   85024   sqlite3_interrupt,
   85025   sqlite3_last_insert_rowid,
   85026   sqlite3_libversion,
   85027   sqlite3_libversion_number,
   85028   sqlite3_malloc,
   85029   sqlite3_mprintf,
   85030   sqlite3_open,
   85031   sqlite3_open16,
   85032   sqlite3_prepare,
   85033   sqlite3_prepare16,
   85034   sqlite3_profile,
   85035   sqlite3_progress_handler,
   85036   sqlite3_realloc,
   85037   sqlite3_reset,
   85038   sqlite3_result_blob,
   85039   sqlite3_result_double,
   85040   sqlite3_result_error,
   85041   sqlite3_result_error16,
   85042   sqlite3_result_int,
   85043   sqlite3_result_int64,
   85044   sqlite3_result_null,
   85045   sqlite3_result_text,
   85046   sqlite3_result_text16,
   85047   sqlite3_result_text16be,
   85048   sqlite3_result_text16le,
   85049   sqlite3_result_value,
   85050   sqlite3_rollback_hook,
   85051   sqlite3_set_authorizer,
   85052   sqlite3_set_auxdata,
   85053   sqlite3_snprintf,
   85054   sqlite3_step,
   85055   sqlite3_table_column_metadata,
   85056 #ifndef SQLITE_OMIT_DEPRECATED
   85057   sqlite3_thread_cleanup,
   85058 #else
   85059   0,
   85060 #endif
   85061   sqlite3_total_changes,
   85062   sqlite3_trace,
   85063 #ifndef SQLITE_OMIT_DEPRECATED
   85064   sqlite3_transfer_bindings,
   85065 #else
   85066   0,
   85067 #endif
   85068   sqlite3_update_hook,
   85069   sqlite3_user_data,
   85070   sqlite3_value_blob,
   85071   sqlite3_value_bytes,
   85072   sqlite3_value_bytes16,
   85073   sqlite3_value_double,
   85074   sqlite3_value_int,
   85075   sqlite3_value_int64,
   85076   sqlite3_value_numeric_type,
   85077   sqlite3_value_text,
   85078   sqlite3_value_text16,
   85079   sqlite3_value_text16be,
   85080   sqlite3_value_text16le,
   85081   sqlite3_value_type,
   85082   sqlite3_vmprintf,
   85083   /*
   85084   ** The original API set ends here.  All extensions can call any
   85085   ** of the APIs above provided that the pointer is not NULL.  But
   85086   ** before calling APIs that follow, extension should check the
   85087   ** sqlite3_libversion_number() to make sure they are dealing with
   85088   ** a library that is new enough to support that API.
   85089   *************************************************************************
   85090   */
   85091   sqlite3_overload_function,
   85092 
   85093   /*
   85094   ** Added after 3.3.13
   85095   */
   85096   sqlite3_prepare_v2,
   85097   sqlite3_prepare16_v2,
   85098   sqlite3_clear_bindings,
   85099 
   85100   /*
   85101   ** Added for 3.4.1
   85102   */
   85103   sqlite3_create_module_v2,
   85104 
   85105   /*
   85106   ** Added for 3.5.0
   85107   */
   85108   sqlite3_bind_zeroblob,
   85109   sqlite3_blob_bytes,
   85110   sqlite3_blob_close,
   85111   sqlite3_blob_open,
   85112   sqlite3_blob_read,
   85113   sqlite3_blob_write,
   85114   sqlite3_create_collation_v2,
   85115   sqlite3_file_control,
   85116   sqlite3_memory_highwater,
   85117   sqlite3_memory_used,
   85118 #ifdef SQLITE_MUTEX_OMIT
   85119   0,
   85120   0,
   85121   0,
   85122   0,
   85123   0,
   85124 #else
   85125   sqlite3_mutex_alloc,
   85126   sqlite3_mutex_enter,
   85127   sqlite3_mutex_free,
   85128   sqlite3_mutex_leave,
   85129   sqlite3_mutex_try,
   85130 #endif
   85131   sqlite3_open_v2,
   85132   sqlite3_release_memory,
   85133   sqlite3_result_error_nomem,
   85134   sqlite3_result_error_toobig,
   85135   sqlite3_sleep,
   85136   sqlite3_soft_heap_limit,
   85137   sqlite3_vfs_find,
   85138   sqlite3_vfs_register,
   85139   sqlite3_vfs_unregister,
   85140 
   85141   /*
   85142   ** Added for 3.5.8
   85143   */
   85144   sqlite3_threadsafe,
   85145   sqlite3_result_zeroblob,
   85146   sqlite3_result_error_code,
   85147   sqlite3_test_control,
   85148   sqlite3_randomness,
   85149   sqlite3_context_db_handle,
   85150 
   85151   /*
   85152   ** Added for 3.6.0
   85153   */
   85154   sqlite3_extended_result_codes,
   85155   sqlite3_limit,
   85156   sqlite3_next_stmt,
   85157   sqlite3_sql,
   85158   sqlite3_status,
   85159 
   85160   /*
   85161   ** Added for 3.7.4
   85162   */
   85163   sqlite3_backup_finish,
   85164   sqlite3_backup_init,
   85165   sqlite3_backup_pagecount,
   85166   sqlite3_backup_remaining,
   85167   sqlite3_backup_step,
   85168 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   85169   sqlite3_compileoption_get,
   85170   sqlite3_compileoption_used,
   85171 #else
   85172   0,
   85173   0,
   85174 #endif
   85175   sqlite3_create_function_v2,
   85176   sqlite3_db_config,
   85177   sqlite3_db_mutex,
   85178   sqlite3_db_status,
   85179   sqlite3_extended_errcode,
   85180   sqlite3_log,
   85181   sqlite3_soft_heap_limit64,
   85182   sqlite3_sourceid,
   85183   sqlite3_stmt_status,
   85184   sqlite3_strnicmp,
   85185 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   85186   sqlite3_unlock_notify,
   85187 #else
   85188   0,
   85189 #endif
   85190 #ifndef SQLITE_OMIT_WAL
   85191   sqlite3_wal_autocheckpoint,
   85192   sqlite3_wal_checkpoint,
   85193   sqlite3_wal_hook,
   85194 #else
   85195   0,
   85196   0,
   85197   0,
   85198 #endif
   85199 };
   85200 
   85201 /*
   85202 ** Attempt to load an SQLite extension library contained in the file
   85203 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
   85204 ** default entry point name (sqlite3_extension_init) is used.  Use
   85205 ** of the default name is recommended.
   85206 **
   85207 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
   85208 **
   85209 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
   85210 ** error message text.  The calling function should free this memory
   85211 ** by calling sqlite3DbFree(db, ).
   85212 */
   85213 static int sqlite3LoadExtension(
   85214   sqlite3 *db,          /* Load the extension into this database connection */
   85215   const char *zFile,    /* Name of the shared library containing extension */
   85216   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   85217   char **pzErrMsg       /* Put error message here if not 0 */
   85218 ){
   85219   sqlite3_vfs *pVfs = db->pVfs;
   85220   void *handle;
   85221   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   85222   char *zErrmsg = 0;
   85223   void **aHandle;
   85224   const int nMsg = 300;
   85225 
   85226   if( pzErrMsg ) *pzErrMsg = 0;
   85227 
   85228   /* Ticket #1863.  To avoid a creating security problems for older
   85229   ** applications that relink against newer versions of SQLite, the
   85230   ** ability to run load_extension is turned off by default.  One
   85231   ** must call sqlite3_enable_load_extension() to turn on extension
   85232   ** loading.  Otherwise you get the following error.
   85233   */
   85234   if( (db->flags & SQLITE_LoadExtension)==0 ){
   85235     if( pzErrMsg ){
   85236       *pzErrMsg = sqlite3_mprintf("not authorized");
   85237     }
   85238     return SQLITE_ERROR;
   85239   }
   85240 
   85241   if( zProc==0 ){
   85242     zProc = "sqlite3_extension_init";
   85243   }
   85244 
   85245   handle = sqlite3OsDlOpen(pVfs, zFile);
   85246   if( handle==0 ){
   85247     if( pzErrMsg ){
   85248       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   85249       if( zErrmsg ){
   85250         sqlite3_snprintf(nMsg, zErrmsg,
   85251             "unable to open shared library [%s]", zFile);
   85252         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   85253       }
   85254     }
   85255     return SQLITE_ERROR;
   85256   }
   85257   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   85258                    sqlite3OsDlSym(pVfs, handle, zProc);
   85259   if( xInit==0 ){
   85260     if( pzErrMsg ){
   85261       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
   85262       if( zErrmsg ){
   85263         sqlite3_snprintf(nMsg, zErrmsg,
   85264             "no entry point [%s] in shared library [%s]", zProc,zFile);
   85265         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
   85266       }
   85267       sqlite3OsDlClose(pVfs, handle);
   85268     }
   85269     return SQLITE_ERROR;
   85270   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
   85271     if( pzErrMsg ){
   85272       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
   85273     }
   85274     sqlite3_free(zErrmsg);
   85275     sqlite3OsDlClose(pVfs, handle);
   85276     return SQLITE_ERROR;
   85277   }
   85278 
   85279   /* Append the new shared library handle to the db->aExtension array. */
   85280   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
   85281   if( aHandle==0 ){
   85282     return SQLITE_NOMEM;
   85283   }
   85284   if( db->nExtension>0 ){
   85285     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
   85286   }
   85287   sqlite3DbFree(db, db->aExtension);
   85288   db->aExtension = aHandle;
   85289 
   85290   db->aExtension[db->nExtension++] = handle;
   85291   return SQLITE_OK;
   85292 }
   85293 SQLITE_API int sqlite3_load_extension(
   85294   sqlite3 *db,          /* Load the extension into this database connection */
   85295   const char *zFile,    /* Name of the shared library containing extension */
   85296   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
   85297   char **pzErrMsg       /* Put error message here if not 0 */
   85298 ){
   85299   int rc;
   85300   sqlite3_mutex_enter(db->mutex);
   85301   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
   85302   rc = sqlite3ApiExit(db, rc);
   85303   sqlite3_mutex_leave(db->mutex);
   85304   return rc;
   85305 }
   85306 
   85307 /*
   85308 ** Call this routine when the database connection is closing in order
   85309 ** to clean up loaded extensions
   85310 */
   85311 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
   85312   int i;
   85313   assert( sqlite3_mutex_held(db->mutex) );
   85314   for(i=0; i<db->nExtension; i++){
   85315     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
   85316   }
   85317   sqlite3DbFree(db, db->aExtension);
   85318 }
   85319 
   85320 /*
   85321 ** Enable or disable extension loading.  Extension loading is disabled by
   85322 ** default so as not to open security holes in older applications.
   85323 */
   85324 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
   85325   sqlite3_mutex_enter(db->mutex);
   85326   if( onoff ){
   85327     db->flags |= SQLITE_LoadExtension;
   85328   }else{
   85329     db->flags &= ~SQLITE_LoadExtension;
   85330   }
   85331   sqlite3_mutex_leave(db->mutex);
   85332   return SQLITE_OK;
   85333 }
   85334 
   85335 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
   85336 
   85337 /*
   85338 ** The auto-extension code added regardless of whether or not extension
   85339 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
   85340 ** code if regular extension loading is not available.  This is that
   85341 ** dummy pointer.
   85342 */
   85343 #ifdef SQLITE_OMIT_LOAD_EXTENSION
   85344 static const sqlite3_api_routines sqlite3Apis = { 0 };
   85345 #endif
   85346 
   85347 
   85348 /*
   85349 ** The following object holds the list of automatically loaded
   85350 ** extensions.
   85351 **
   85352 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
   85353 ** mutex must be held while accessing this list.
   85354 */
   85355 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
   85356 static SQLITE_WSD struct sqlite3AutoExtList {
   85357   int nExt;              /* Number of entries in aExt[] */
   85358   void (**aExt)(void);   /* Pointers to the extension init functions */
   85359 } sqlite3Autoext = { 0, 0 };
   85360 
   85361 /* The "wsdAutoext" macro will resolve to the autoextension
   85362 ** state vector.  If writable static data is unsupported on the target,
   85363 ** we have to locate the state vector at run-time.  In the more common
   85364 ** case where writable static data is supported, wsdStat can refer directly
   85365 ** to the "sqlite3Autoext" state vector declared above.
   85366 */
   85367 #ifdef SQLITE_OMIT_WSD
   85368 # define wsdAutoextInit \
   85369   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
   85370 # define wsdAutoext x[0]
   85371 #else
   85372 # define wsdAutoextInit
   85373 # define wsdAutoext sqlite3Autoext
   85374 #endif
   85375 
   85376 
   85377 /*
   85378 ** Register a statically linked extension that is automatically
   85379 ** loaded by every new database connection.
   85380 */
   85381 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
   85382   int rc = SQLITE_OK;
   85383 #ifndef SQLITE_OMIT_AUTOINIT
   85384   rc = sqlite3_initialize();
   85385   if( rc ){
   85386     return rc;
   85387   }else
   85388 #endif
   85389   {
   85390     int i;
   85391 #if SQLITE_THREADSAFE
   85392     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   85393 #endif
   85394     wsdAutoextInit;
   85395     sqlite3_mutex_enter(mutex);
   85396     for(i=0; i<wsdAutoext.nExt; i++){
   85397       if( wsdAutoext.aExt[i]==xInit ) break;
   85398     }
   85399     if( i==wsdAutoext.nExt ){
   85400       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
   85401       void (**aNew)(void);
   85402       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
   85403       if( aNew==0 ){
   85404         rc = SQLITE_NOMEM;
   85405       }else{
   85406         wsdAutoext.aExt = aNew;
   85407         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
   85408         wsdAutoext.nExt++;
   85409       }
   85410     }
   85411     sqlite3_mutex_leave(mutex);
   85412     assert( (rc&0xff)==rc );
   85413     return rc;
   85414   }
   85415 }
   85416 
   85417 /*
   85418 ** Reset the automatic extension loading mechanism.
   85419 */
   85420 SQLITE_API void sqlite3_reset_auto_extension(void){
   85421 #ifndef SQLITE_OMIT_AUTOINIT
   85422   if( sqlite3_initialize()==SQLITE_OK )
   85423 #endif
   85424   {
   85425 #if SQLITE_THREADSAFE
   85426     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   85427 #endif
   85428     wsdAutoextInit;
   85429     sqlite3_mutex_enter(mutex);
   85430     sqlite3_free(wsdAutoext.aExt);
   85431     wsdAutoext.aExt = 0;
   85432     wsdAutoext.nExt = 0;
   85433     sqlite3_mutex_leave(mutex);
   85434   }
   85435 }
   85436 
   85437 /*
   85438 ** Load all automatic extensions.
   85439 **
   85440 ** If anything goes wrong, set an error in the database connection.
   85441 */
   85442 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   85443   int i;
   85444   int go = 1;
   85445   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   85446 
   85447   wsdAutoextInit;
   85448   if( wsdAutoext.nExt==0 ){
   85449     /* Common case: early out without every having to acquire a mutex */
   85450     return;
   85451   }
   85452   for(i=0; go; i++){
   85453     char *zErrmsg;
   85454 #if SQLITE_THREADSAFE
   85455     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   85456 #endif
   85457     sqlite3_mutex_enter(mutex);
   85458     if( i>=wsdAutoext.nExt ){
   85459       xInit = 0;
   85460       go = 0;
   85461     }else{
   85462       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   85463               wsdAutoext.aExt[i];
   85464     }
   85465     sqlite3_mutex_leave(mutex);
   85466     zErrmsg = 0;
   85467     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
   85468       sqlite3Error(db, SQLITE_ERROR,
   85469             "automatic extension loading failed: %s", zErrmsg);
   85470       go = 0;
   85471     }
   85472     sqlite3_free(zErrmsg);
   85473   }
   85474 }
   85475 
   85476 /************** End of loadext.c *********************************************/
   85477 /************** Begin file pragma.c ******************************************/
   85478 /*
   85479 ** 2003 April 6
   85480 **
   85481 ** The author disclaims copyright to this source code.  In place of
   85482 ** a legal notice, here is a blessing:
   85483 **
   85484 **    May you do good and not evil.
   85485 **    May you find forgiveness for yourself and forgive others.
   85486 **    May you share freely, never taking more than you give.
   85487 **
   85488 *************************************************************************
   85489 ** This file contains code used to implement the PRAGMA command.
   85490 */
   85491 
   85492 /* Ignore this whole file if pragmas are disabled
   85493 */
   85494 #if !defined(SQLITE_OMIT_PRAGMA)
   85495 
   85496 /*
   85497 ** Interpret the given string as a safety level.  Return 0 for OFF,
   85498 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
   85499 ** unrecognized string argument.
   85500 **
   85501 ** Note that the values returned are one less that the values that
   85502 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
   85503 ** to support legacy SQL code.  The safety level used to be boolean
   85504 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
   85505 */
   85506 static u8 getSafetyLevel(const char *z){
   85507                              /* 123456789 123456789 */
   85508   static const char zText[] = "onoffalseyestruefull";
   85509   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
   85510   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
   85511   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
   85512   int i, n;
   85513   if( sqlite3Isdigit(*z) ){
   85514     return (u8)sqlite3Atoi(z);
   85515   }
   85516   n = sqlite3Strlen30(z);
   85517   for(i=0; i<ArraySize(iLength); i++){
   85518     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
   85519       return iValue[i];
   85520     }
   85521   }
   85522   return 1;
   85523 }
   85524 
   85525 /*
   85526 ** Interpret the given string as a boolean value.
   85527 */
   85528 static u8 getBoolean(const char *z){
   85529   return getSafetyLevel(z)&1;
   85530 }
   85531 
   85532 /*
   85533 ** Interpret the given string as a locking mode value.
   85534 */
   85535 static int getLockingMode(const char *z){
   85536   if( z ){
   85537     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
   85538     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
   85539   }
   85540   return PAGER_LOCKINGMODE_QUERY;
   85541 }
   85542 
   85543 #ifndef SQLITE_OMIT_AUTOVACUUM
   85544 /*
   85545 ** Interpret the given string as an auto-vacuum mode value.
   85546 **
   85547 ** The following strings, "none", "full" and "incremental" are
   85548 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
   85549 */
   85550 static int getAutoVacuum(const char *z){
   85551   int i;
   85552   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
   85553   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
   85554   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
   85555   i = sqlite3Atoi(z);
   85556   return (u8)((i>=0&&i<=2)?i:0);
   85557 }
   85558 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
   85559 
   85560 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85561 /*
   85562 ** Interpret the given string as a temp db location. Return 1 for file
   85563 ** backed temporary databases, 2 for the Red-Black tree in memory database
   85564 ** and 0 to use the compile-time default.
   85565 */
   85566 static int getTempStore(const char *z){
   85567   if( z[0]>='0' && z[0]<='2' ){
   85568     return z[0] - '0';
   85569   }else if( sqlite3StrICmp(z, "file")==0 ){
   85570     return 1;
   85571   }else if( sqlite3StrICmp(z, "memory")==0 ){
   85572     return 2;
   85573   }else{
   85574     return 0;
   85575   }
   85576 }
   85577 #endif /* SQLITE_PAGER_PRAGMAS */
   85578 
   85579 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85580 /*
   85581 ** Invalidate temp storage, either when the temp storage is changed
   85582 ** from default, or when 'file' and the temp_store_directory has changed
   85583 */
   85584 static int invalidateTempStorage(Parse *pParse){
   85585   sqlite3 *db = pParse->db;
   85586   if( db->aDb[1].pBt!=0 ){
   85587     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
   85588       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
   85589         "from within a transaction");
   85590       return SQLITE_ERROR;
   85591     }
   85592     sqlite3BtreeClose(db->aDb[1].pBt);
   85593     db->aDb[1].pBt = 0;
   85594     sqlite3ResetInternalSchema(db, 0);
   85595   }
   85596   return SQLITE_OK;
   85597 }
   85598 #endif /* SQLITE_PAGER_PRAGMAS */
   85599 
   85600 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85601 /*
   85602 ** If the TEMP database is open, close it and mark the database schema
   85603 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
   85604 ** or DEFAULT_TEMP_STORE pragmas.
   85605 */
   85606 static int changeTempStorage(Parse *pParse, const char *zStorageType){
   85607   int ts = getTempStore(zStorageType);
   85608   sqlite3 *db = pParse->db;
   85609   if( db->temp_store==ts ) return SQLITE_OK;
   85610   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
   85611     return SQLITE_ERROR;
   85612   }
   85613   db->temp_store = (u8)ts;
   85614   return SQLITE_OK;
   85615 }
   85616 #endif /* SQLITE_PAGER_PRAGMAS */
   85617 
   85618 /*
   85619 ** Generate code to return a single integer value.
   85620 */
   85621 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
   85622   Vdbe *v = sqlite3GetVdbe(pParse);
   85623   int mem = ++pParse->nMem;
   85624   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
   85625   if( pI64 ){
   85626     memcpy(pI64, &value, sizeof(value));
   85627   }
   85628   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
   85629   sqlite3VdbeSetNumCols(v, 1);
   85630   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
   85631   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
   85632 }
   85633 
   85634 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   85635 /*
   85636 ** Check to see if zRight and zLeft refer to a pragma that queries
   85637 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
   85638 ** Also, implement the pragma.
   85639 */
   85640 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
   85641   static const struct sPragmaType {
   85642     const char *zName;  /* Name of the pragma */
   85643     int mask;           /* Mask for the db->flags value */
   85644   } aPragma[] = {
   85645     { "full_column_names",        SQLITE_FullColNames  },
   85646     { "short_column_names",       SQLITE_ShortColNames },
   85647     { "count_changes",            SQLITE_CountRows     },
   85648     { "empty_result_callbacks",   SQLITE_NullCallback  },
   85649     { "legacy_file_format",       SQLITE_LegacyFileFmt },
   85650     { "fullfsync",                SQLITE_FullFSync     },
   85651     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
   85652     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
   85653 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   85654     { "automatic_index",          SQLITE_AutoIndex     },
   85655 #endif
   85656 #ifdef SQLITE_DEBUG
   85657     { "sql_trace",                SQLITE_SqlTrace      },
   85658     { "vdbe_listing",             SQLITE_VdbeListing   },
   85659     { "vdbe_trace",               SQLITE_VdbeTrace     },
   85660 #endif
   85661 #ifndef SQLITE_OMIT_CHECK
   85662     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
   85663 #endif
   85664     /* The following is VERY experimental */
   85665     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
   85666     { "omit_readlock",            SQLITE_NoReadlock    },
   85667 
   85668     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
   85669     ** flag if there are any active statements. */
   85670     { "read_uncommitted",         SQLITE_ReadUncommitted },
   85671     { "recursive_triggers",       SQLITE_RecTriggers },
   85672 
   85673     /* This flag may only be set if both foreign-key and trigger support
   85674     ** are present in the build.  */
   85675 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
   85676     { "foreign_keys",             SQLITE_ForeignKeys },
   85677 #endif
   85678   };
   85679   int i;
   85680   const struct sPragmaType *p;
   85681   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
   85682     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
   85683       sqlite3 *db = pParse->db;
   85684       Vdbe *v;
   85685       v = sqlite3GetVdbe(pParse);
   85686       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
   85687       if( ALWAYS(v) ){
   85688         if( zRight==0 ){
   85689           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
   85690         }else{
   85691           int mask = p->mask;          /* Mask of bits to set or clear. */
   85692           if( db->autoCommit==0 ){
   85693             /* Foreign key support may not be enabled or disabled while not
   85694             ** in auto-commit mode.  */
   85695             mask &= ~(SQLITE_ForeignKeys);
   85696           }
   85697 
   85698           if( getBoolean(zRight) ){
   85699             db->flags |= mask;
   85700           }else{
   85701             db->flags &= ~mask;
   85702           }
   85703 
   85704           /* Many of the flag-pragmas modify the code generated by the SQL
   85705           ** compiler (eg. count_changes). So add an opcode to expire all
   85706           ** compiled SQL statements after modifying a pragma value.
   85707           */
   85708           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   85709         }
   85710       }
   85711 
   85712       return 1;
   85713     }
   85714   }
   85715   return 0;
   85716 }
   85717 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   85718 
   85719 /*
   85720 ** Return a human-readable name for a constraint resolution action.
   85721 */
   85722 #ifndef SQLITE_OMIT_FOREIGN_KEY
   85723 static const char *actionName(u8 action){
   85724   const char *zName;
   85725   switch( action ){
   85726     case OE_SetNull:  zName = "SET NULL";        break;
   85727     case OE_SetDflt:  zName = "SET DEFAULT";     break;
   85728     case OE_Cascade:  zName = "CASCADE";         break;
   85729     case OE_Restrict: zName = "RESTRICT";        break;
   85730     default:          zName = "NO ACTION";
   85731                       assert( action==OE_None ); break;
   85732   }
   85733   return zName;
   85734 }
   85735 #endif
   85736 
   85737 
   85738 /*
   85739 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
   85740 ** defined in pager.h. This function returns the associated lowercase
   85741 ** journal-mode name.
   85742 */
   85743 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
   85744   static char * const azModeName[] = {
   85745     "delete", "persist", "off", "truncate", "memory"
   85746 #ifndef SQLITE_OMIT_WAL
   85747      , "wal"
   85748 #endif
   85749   };
   85750   assert( PAGER_JOURNALMODE_DELETE==0 );
   85751   assert( PAGER_JOURNALMODE_PERSIST==1 );
   85752   assert( PAGER_JOURNALMODE_OFF==2 );
   85753   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
   85754   assert( PAGER_JOURNALMODE_MEMORY==4 );
   85755   assert( PAGER_JOURNALMODE_WAL==5 );
   85756   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
   85757 
   85758   if( eMode==ArraySize(azModeName) ) return 0;
   85759   return azModeName[eMode];
   85760 }
   85761 
   85762 /*
   85763 ** Process a pragma statement.
   85764 **
   85765 ** Pragmas are of this form:
   85766 **
   85767 **      PRAGMA [database.]id [= value]
   85768 **
   85769 ** The identifier might also be a string.  The value is a string, and
   85770 ** identifier, or a number.  If minusFlag is true, then the value is
   85771 ** a number that was preceded by a minus sign.
   85772 **
   85773 ** If the left side is "database.id" then pId1 is the database name
   85774 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
   85775 ** id and pId2 is any empty string.
   85776 */
   85777 SQLITE_PRIVATE void sqlite3Pragma(
   85778   Parse *pParse,
   85779   Token *pId1,        /* First part of [database.]id field */
   85780   Token *pId2,        /* Second part of [database.]id field, or NULL */
   85781   Token *pValue,      /* Token for <value>, or NULL */
   85782   int minusFlag       /* True if a '-' sign preceded <value> */
   85783 ){
   85784   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
   85785   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
   85786   const char *zDb = 0;   /* The database name */
   85787   Token *pId;            /* Pointer to <id> token */
   85788   int iDb;               /* Database index for <database> */
   85789   sqlite3 *db = pParse->db;
   85790   Db *pDb;
   85791   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
   85792   if( v==0 ) return;
   85793   sqlite3VdbeRunOnlyOnce(v);
   85794   pParse->nMem = 2;
   85795 
   85796   /* Interpret the [database.] part of the pragma statement. iDb is the
   85797   ** index of the database this pragma is being applied to in db.aDb[]. */
   85798   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
   85799   if( iDb<0 ) return;
   85800   pDb = &db->aDb[iDb];
   85801 
   85802   /* If the temp database has been explicitly named as part of the
   85803   ** pragma, make sure it is open.
   85804   */
   85805   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
   85806     return;
   85807   }
   85808 
   85809   zLeft = sqlite3NameFromToken(db, pId);
   85810   if( !zLeft ) return;
   85811   if( minusFlag ){
   85812     zRight = sqlite3MPrintf(db, "-%T", pValue);
   85813   }else{
   85814     zRight = sqlite3NameFromToken(db, pValue);
   85815   }
   85816 
   85817   assert( pId2 );
   85818   zDb = pId2->n>0 ? pDb->zName : 0;
   85819   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   85820     goto pragma_out;
   85821   }
   85822 
   85823 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   85824   /*
   85825   **  PRAGMA [database.]default_cache_size
   85826   **  PRAGMA [database.]default_cache_size=N
   85827   **
   85828   ** The first form reports the current persistent setting for the
   85829   ** page cache size.  The value returned is the maximum number of
   85830   ** pages in the page cache.  The second form sets both the current
   85831   ** page cache size value and the persistent page cache size value
   85832   ** stored in the database file.
   85833   **
   85834   ** Older versions of SQLite would set the default cache size to a
   85835   ** negative number to indicate synchronous=OFF.  These days, synchronous
   85836   ** is always on by default regardless of the sign of the default cache
   85837   ** size.  But continue to take the absolute value of the default cache
   85838   ** size of historical compatibility.
   85839   */
   85840   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
   85841     static const VdbeOpList getCacheSize[] = {
   85842       { OP_Transaction, 0, 0,        0},                         /* 0 */
   85843       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   85844       { OP_IfPos,       1, 7,        0},
   85845       { OP_Integer,     0, 2,        0},
   85846       { OP_Subtract,    1, 2,        1},
   85847       { OP_IfPos,       1, 7,        0},
   85848       { OP_Integer,     0, 1,        0},                         /* 6 */
   85849       { OP_ResultRow,   1, 1,        0},
   85850     };
   85851     int addr;
   85852     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   85853     sqlite3VdbeUsesBtree(v, iDb);
   85854     if( !zRight ){
   85855       sqlite3VdbeSetNumCols(v, 1);
   85856       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   85857       pParse->nMem += 2;
   85858       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
   85859       sqlite3VdbeChangeP1(v, addr, iDb);
   85860       sqlite3VdbeChangeP1(v, addr+1, iDb);
   85861       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   85862     }else{
   85863       int size = sqlite3Atoi(zRight);
   85864       if( size<0 ) size = -size;
   85865       sqlite3BeginWriteOperation(pParse, 0, iDb);
   85866       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   85867       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   85868       pDb->pSchema->cache_size = size;
   85869       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   85870     }
   85871   }else
   85872 
   85873   /*
   85874   **  PRAGMA [database.]page_size
   85875   **  PRAGMA [database.]page_size=N
   85876   **
   85877   ** The first form reports the current setting for the
   85878   ** database page size in bytes.  The second form sets the
   85879   ** database page size value.  The value can only be set if
   85880   ** the database has not yet been created.
   85881   */
   85882   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
   85883     Btree *pBt = pDb->pBt;
   85884     assert( pBt!=0 );
   85885     if( !zRight ){
   85886       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   85887       returnSingleInt(pParse, "page_size", size);
   85888     }else{
   85889       /* Malloc may fail when setting the page-size, as there is an internal
   85890       ** buffer that the pager module resizes using sqlite3_realloc().
   85891       */
   85892       db->nextPagesize = sqlite3Atoi(zRight);
   85893       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
   85894         db->mallocFailed = 1;
   85895       }
   85896     }
   85897   }else
   85898 
   85899   /*
   85900   **  PRAGMA [database.]secure_delete
   85901   **  PRAGMA [database.]secure_delete=ON/OFF
   85902   **
   85903   ** The first form reports the current setting for the
   85904   ** secure_delete flag.  The second form changes the secure_delete
   85905   ** flag setting and reports thenew value.
   85906   */
   85907   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
   85908     Btree *pBt = pDb->pBt;
   85909     int b = -1;
   85910     assert( pBt!=0 );
   85911     if( zRight ){
   85912       b = getBoolean(zRight);
   85913     }
   85914     if( pId2->n==0 && b>=0 ){
   85915       int ii;
   85916       for(ii=0; ii<db->nDb; ii++){
   85917         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
   85918       }
   85919     }
   85920     b = sqlite3BtreeSecureDelete(pBt, b);
   85921     returnSingleInt(pParse, "secure_delete", b);
   85922   }else
   85923 
   85924   /*
   85925   **  PRAGMA [database.]max_page_count
   85926   **  PRAGMA [database.]max_page_count=N
   85927   **
   85928   ** The first form reports the current setting for the
   85929   ** maximum number of pages in the database file.  The
   85930   ** second form attempts to change this setting.  Both
   85931   ** forms return the current setting.
   85932   **
   85933   **  PRAGMA [database.]page_count
   85934   **
   85935   ** Return the number of pages in the specified database.
   85936   */
   85937   if( sqlite3StrICmp(zLeft,"page_count")==0
   85938    || sqlite3StrICmp(zLeft,"max_page_count")==0
   85939   ){
   85940     int iReg;
   85941     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   85942     sqlite3CodeVerifySchema(pParse, iDb);
   85943     iReg = ++pParse->nMem;
   85944     if( zLeft[0]=='p' ){
   85945       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   85946     }else{
   85947       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
   85948     }
   85949     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   85950     sqlite3VdbeSetNumCols(v, 1);
   85951     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   85952   }else
   85953 
   85954   /*
   85955   **  PRAGMA [database.]locking_mode
   85956   **  PRAGMA [database.]locking_mode = (normal|exclusive)
   85957   */
   85958   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
   85959     const char *zRet = "normal";
   85960     int eMode = getLockingMode(zRight);
   85961 
   85962     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
   85963       /* Simple "PRAGMA locking_mode;" statement. This is a query for
   85964       ** the current default locking mode (which may be different to
   85965       ** the locking-mode of the main database).
   85966       */
   85967       eMode = db->dfltLockMode;
   85968     }else{
   85969       Pager *pPager;
   85970       if( pId2->n==0 ){
   85971         /* This indicates that no database name was specified as part
   85972         ** of the PRAGMA command. In this case the locking-mode must be
   85973         ** set on all attached databases, as well as the main db file.
   85974         **
   85975         ** Also, the sqlite3.dfltLockMode variable is set so that
   85976         ** any subsequently attached databases also use the specified
   85977         ** locking mode.
   85978         */
   85979         int ii;
   85980         assert(pDb==&db->aDb[0]);
   85981         for(ii=2; ii<db->nDb; ii++){
   85982           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
   85983           sqlite3PagerLockingMode(pPager, eMode);
   85984         }
   85985         db->dfltLockMode = (u8)eMode;
   85986       }
   85987       pPager = sqlite3BtreePager(pDb->pBt);
   85988       eMode = sqlite3PagerLockingMode(pPager, eMode);
   85989     }
   85990 
   85991     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
   85992     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
   85993       zRet = "exclusive";
   85994     }
   85995     sqlite3VdbeSetNumCols(v, 1);
   85996     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
   85997     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
   85998     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   85999   }else
   86000 
   86001   /*
   86002   **  PRAGMA [database.]journal_mode
   86003   **  PRAGMA [database.]journal_mode =
   86004   **                      (delete|persist|off|truncate|memory|wal|off)
   86005   */
   86006   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
   86007     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
   86008     int ii;           /* Loop counter */
   86009 
   86010     /* Force the schema to be loaded on all databases.  This cases all
   86011     ** database files to be opened and the journal_modes set. */
   86012     if( sqlite3ReadSchema(pParse) ){
   86013       goto pragma_out;
   86014     }
   86015 
   86016     sqlite3VdbeSetNumCols(v, 1);
   86017     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
   86018 
   86019     if( zRight==0 ){
   86020       /* If there is no "=MODE" part of the pragma, do a query for the
   86021       ** current mode */
   86022       eMode = PAGER_JOURNALMODE_QUERY;
   86023     }else{
   86024       const char *zMode;
   86025       int n = sqlite3Strlen30(zRight);
   86026       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
   86027         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
   86028       }
   86029       if( !zMode ){
   86030         /* If the "=MODE" part does not match any known journal mode,
   86031         ** then do a query */
   86032         eMode = PAGER_JOURNALMODE_QUERY;
   86033       }
   86034     }
   86035     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
   86036       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
   86037       iDb = 0;
   86038       pId2->n = 1;
   86039     }
   86040     for(ii=db->nDb-1; ii>=0; ii--){
   86041       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
   86042         sqlite3VdbeUsesBtree(v, ii);
   86043         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
   86044       }
   86045     }
   86046     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   86047   }else
   86048 
   86049   /*
   86050   **  PRAGMA [database.]journal_size_limit
   86051   **  PRAGMA [database.]journal_size_limit=N
   86052   **
   86053   ** Get or set the size limit on rollback journal files.
   86054   */
   86055   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
   86056     Pager *pPager = sqlite3BtreePager(pDb->pBt);
   86057     i64 iLimit = -2;
   86058     if( zRight ){
   86059       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
   86060       if( iLimit<-1 ) iLimit = -1;
   86061     }
   86062     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
   86063     returnSingleInt(pParse, "journal_size_limit", iLimit);
   86064   }else
   86065 
   86066 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   86067 
   86068   /*
   86069   **  PRAGMA [database.]auto_vacuum
   86070   **  PRAGMA [database.]auto_vacuum=N
   86071   **
   86072   ** Get or set the value of the database 'auto-vacuum' parameter.
   86073   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
   86074   */
   86075 #ifndef SQLITE_OMIT_AUTOVACUUM
   86076   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
   86077     Btree *pBt = pDb->pBt;
   86078     assert( pBt!=0 );
   86079     if( sqlite3ReadSchema(pParse) ){
   86080       goto pragma_out;
   86081     }
   86082     if( !zRight ){
   86083       int auto_vacuum;
   86084       if( ALWAYS(pBt) ){
   86085          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
   86086       }else{
   86087          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
   86088       }
   86089       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
   86090     }else{
   86091       int eAuto = getAutoVacuum(zRight);
   86092       assert( eAuto>=0 && eAuto<=2 );
   86093       db->nextAutovac = (u8)eAuto;
   86094       if( ALWAYS(eAuto>=0) ){
   86095         /* Call SetAutoVacuum() to set initialize the internal auto and
   86096         ** incr-vacuum flags. This is required in case this connection
   86097         ** creates the database file. It is important that it is created
   86098         ** as an auto-vacuum capable db.
   86099         */
   86100         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
   86101         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
   86102           /* When setting the auto_vacuum mode to either "full" or
   86103           ** "incremental", write the value of meta[6] in the database
   86104           ** file. Before writing to meta[6], check that meta[3] indicates
   86105           ** that this really is an auto-vacuum capable database.
   86106           */
   86107           static const VdbeOpList setMeta6[] = {
   86108             { OP_Transaction,    0,         1,                 0},    /* 0 */
   86109             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
   86110             { OP_If,             1,         0,                 0},    /* 2 */
   86111             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
   86112             { OP_Integer,        0,         1,                 0},    /* 4 */
   86113             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
   86114           };
   86115           int iAddr;
   86116           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
   86117           sqlite3VdbeChangeP1(v, iAddr, iDb);
   86118           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
   86119           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
   86120           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
   86121           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
   86122           sqlite3VdbeUsesBtree(v, iDb);
   86123         }
   86124       }
   86125     }
   86126   }else
   86127 #endif
   86128 
   86129   /*
   86130   **  PRAGMA [database.]incremental_vacuum(N)
   86131   **
   86132   ** Do N steps of incremental vacuuming on a database.
   86133   */
   86134 #ifndef SQLITE_OMIT_AUTOVACUUM
   86135   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
   86136     int iLimit, addr;
   86137     if( sqlite3ReadSchema(pParse) ){
   86138       goto pragma_out;
   86139     }
   86140     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
   86141       iLimit = 0x7fffffff;
   86142     }
   86143     sqlite3BeginWriteOperation(pParse, 0, iDb);
   86144     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
   86145     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
   86146     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
   86147     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
   86148     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
   86149     sqlite3VdbeJumpHere(v, addr);
   86150   }else
   86151 #endif
   86152 
   86153 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   86154   /*
   86155   **  PRAGMA [database.]cache_size
   86156   **  PRAGMA [database.]cache_size=N
   86157   **
   86158   ** The first form reports the current local setting for the
   86159   ** page cache size.  The local setting can be different from
   86160   ** the persistent cache size value that is stored in the database
   86161   ** file itself.  The value returned is the maximum number of
   86162   ** pages in the page cache.  The second form sets the local
   86163   ** page cache size value.  It does not change the persistent
   86164   ** cache size stored on the disk so the cache size will revert
   86165   ** to its default value when the database is closed and reopened.
   86166   ** N should be a positive integer.
   86167   */
   86168   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
   86169     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86170     if( !zRight ){
   86171       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   86172     }else{
   86173       int size = sqlite3Atoi(zRight);
   86174       if( size<0 ) size = -size;
   86175       pDb->pSchema->cache_size = size;
   86176       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   86177     }
   86178   }else
   86179 
   86180   /*
   86181   **   PRAGMA temp_store
   86182   **   PRAGMA temp_store = "default"|"memory"|"file"
   86183   **
   86184   ** Return or set the local value of the temp_store flag.  Changing
   86185   ** the local value does not make changes to the disk file and the default
   86186   ** value will be restored the next time the database is opened.
   86187   **
   86188   ** Note that it is possible for the library compile-time options to
   86189   ** override this setting
   86190   */
   86191   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
   86192     if( !zRight ){
   86193       returnSingleInt(pParse, "temp_store", db->temp_store);
   86194     }else{
   86195       changeTempStorage(pParse, zRight);
   86196     }
   86197   }else
   86198 
   86199   /*
   86200   **   PRAGMA temp_store_directory
   86201   **   PRAGMA temp_store_directory = ""|"directory_name"
   86202   **
   86203   ** Return or set the local value of the temp_store_directory flag.  Changing
   86204   ** the value sets a specific directory to be used for temporary files.
   86205   ** Setting to a null string reverts to the default temporary directory search.
   86206   ** If temporary directory is changed, then invalidateTempStorage.
   86207   **
   86208   */
   86209   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
   86210     if( !zRight ){
   86211       if( sqlite3_temp_directory ){
   86212         sqlite3VdbeSetNumCols(v, 1);
   86213         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   86214             "temp_store_directory", SQLITE_STATIC);
   86215         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
   86216         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   86217       }
   86218     }else{
   86219 #ifndef SQLITE_OMIT_WSD
   86220       if( zRight[0] ){
   86221         int rc;
   86222         int res;
   86223         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
   86224         if( rc!=SQLITE_OK || res==0 ){
   86225           sqlite3ErrorMsg(pParse, "not a writable directory");
   86226           goto pragma_out;
   86227         }
   86228       }
   86229       if( SQLITE_TEMP_STORE==0
   86230        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
   86231        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
   86232       ){
   86233         invalidateTempStorage(pParse);
   86234       }
   86235       sqlite3_free(sqlite3_temp_directory);
   86236       if( zRight[0] ){
   86237         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
   86238       }else{
   86239         sqlite3_temp_directory = 0;
   86240       }
   86241 #endif /* SQLITE_OMIT_WSD */
   86242     }
   86243   }else
   86244 
   86245 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
   86246 #  if defined(__APPLE__)
   86247 #    define SQLITE_ENABLE_LOCKING_STYLE 1
   86248 #  else
   86249 #    define SQLITE_ENABLE_LOCKING_STYLE 0
   86250 #  endif
   86251 #endif
   86252 #if SQLITE_ENABLE_LOCKING_STYLE
   86253   /*
   86254    **   PRAGMA [database.]lock_proxy_file
   86255    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
   86256    **
   86257    ** Return or set the value of the lock_proxy_file flag.  Changing
   86258    ** the value sets a specific file to be used for database access locks.
   86259    **
   86260    */
   86261   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
   86262     if( !zRight ){
   86263       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   86264       char *proxy_file_path = NULL;
   86265       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   86266       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
   86267                            &proxy_file_path);
   86268 
   86269       if( proxy_file_path ){
   86270         sqlite3VdbeSetNumCols(v, 1);
   86271         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
   86272                               "lock_proxy_file", SQLITE_STATIC);
   86273         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
   86274         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   86275       }
   86276     }else{
   86277       Pager *pPager = sqlite3BtreePager(pDb->pBt);
   86278       sqlite3_file *pFile = sqlite3PagerFile(pPager);
   86279       int res;
   86280       if( zRight[0] ){
   86281         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   86282                                      zRight);
   86283       } else {
   86284         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
   86285                                      NULL);
   86286       }
   86287       if( res!=SQLITE_OK ){
   86288         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
   86289         goto pragma_out;
   86290       }
   86291     }
   86292   }else
   86293 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
   86294 
   86295   /*
   86296   **   PRAGMA [database.]synchronous
   86297   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
   86298   **
   86299   ** Return or set the local value of the synchronous flag.  Changing
   86300   ** the local value does not make changes to the disk file and the
   86301   ** default value will be restored the next time the database is
   86302   ** opened.
   86303   */
   86304   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
   86305     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86306     if( !zRight ){
   86307       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
   86308     }else{
   86309       if( !db->autoCommit ){
   86310         sqlite3ErrorMsg(pParse,
   86311             "Safety level may not be changed inside a transaction");
   86312       }else{
   86313         pDb->safety_level = getSafetyLevel(zRight)+1;
   86314       }
   86315     }
   86316   }else
   86317 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
   86318 
   86319 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
   86320   if( flagPragma(pParse, zLeft, zRight) ){
   86321     /* The flagPragma() subroutine also generates any necessary code
   86322     ** there is nothing more to do here */
   86323   }else
   86324 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
   86325 
   86326 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
   86327   /*
   86328   **   PRAGMA table_info(<table>)
   86329   **
   86330   ** Return a single row for each column of the named table. The columns of
   86331   ** the returned data set are:
   86332   **
   86333   ** cid:        Column id (numbered from left to right, starting at 0)
   86334   ** name:       Column name
   86335   ** type:       Column declaration type.
   86336   ** notnull:    True if 'NOT NULL' is part of column declaration
   86337   ** dflt_value: The default value for the column, if any.
   86338   */
   86339   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
   86340     Table *pTab;
   86341     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86342     pTab = sqlite3FindTable(db, zRight, zDb);
   86343     if( pTab ){
   86344       int i;
   86345       int nHidden = 0;
   86346       Column *pCol;
   86347       sqlite3VdbeSetNumCols(v, 6);
   86348       pParse->nMem = 6;
   86349       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
   86350       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   86351       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
   86352       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
   86353       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
   86354       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
   86355       sqlite3ViewGetColumnNames(pParse, pTab);
   86356       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
   86357         if( IsHiddenColumn(pCol) ){
   86358           nHidden++;
   86359           continue;
   86360         }
   86361         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
   86362         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
   86363         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   86364            pCol->zType ? pCol->zType : "", 0);
   86365         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
   86366         if( pCol->zDflt ){
   86367           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
   86368         }else{
   86369           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
   86370         }
   86371         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
   86372         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
   86373       }
   86374     }
   86375   }else
   86376 
   86377   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
   86378     Index *pIdx;
   86379     Table *pTab;
   86380     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86381     pIdx = sqlite3FindIndex(db, zRight, zDb);
   86382     if( pIdx ){
   86383       int i;
   86384       pTab = pIdx->pTable;
   86385       sqlite3VdbeSetNumCols(v, 3);
   86386       pParse->nMem = 3;
   86387       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
   86388       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
   86389       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
   86390       for(i=0; i<pIdx->nColumn; i++){
   86391         int cnum = pIdx->aiColumn[i];
   86392         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   86393         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
   86394         assert( pTab->nCol>cnum );
   86395         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
   86396         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   86397       }
   86398     }
   86399   }else
   86400 
   86401   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
   86402     Index *pIdx;
   86403     Table *pTab;
   86404     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86405     pTab = sqlite3FindTable(db, zRight, zDb);
   86406     if( pTab ){
   86407       v = sqlite3GetVdbe(pParse);
   86408       pIdx = pTab->pIndex;
   86409       if( pIdx ){
   86410         int i = 0;
   86411         sqlite3VdbeSetNumCols(v, 3);
   86412         pParse->nMem = 3;
   86413         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   86414         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   86415         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
   86416         while(pIdx){
   86417           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   86418           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
   86419           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
   86420           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   86421           ++i;
   86422           pIdx = pIdx->pNext;
   86423         }
   86424       }
   86425     }
   86426   }else
   86427 
   86428   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
   86429     int i;
   86430     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86431     sqlite3VdbeSetNumCols(v, 3);
   86432     pParse->nMem = 3;
   86433     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   86434     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   86435     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
   86436     for(i=0; i<db->nDb; i++){
   86437       if( db->aDb[i].pBt==0 ) continue;
   86438       assert( db->aDb[i].zName!=0 );
   86439       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   86440       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
   86441       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   86442            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
   86443       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
   86444     }
   86445   }else
   86446 
   86447   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
   86448     int i = 0;
   86449     HashElem *p;
   86450     sqlite3VdbeSetNumCols(v, 2);
   86451     pParse->nMem = 2;
   86452     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
   86453     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
   86454     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
   86455       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
   86456       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
   86457       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
   86458       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   86459     }
   86460   }else
   86461 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
   86462 
   86463 #ifndef SQLITE_OMIT_FOREIGN_KEY
   86464   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
   86465     FKey *pFK;
   86466     Table *pTab;
   86467     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86468     pTab = sqlite3FindTable(db, zRight, zDb);
   86469     if( pTab ){
   86470       v = sqlite3GetVdbe(pParse);
   86471       pFK = pTab->pFKey;
   86472       if( pFK ){
   86473         int i = 0;
   86474         sqlite3VdbeSetNumCols(v, 8);
   86475         pParse->nMem = 8;
   86476         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
   86477         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
   86478         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
   86479         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
   86480         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
   86481         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
   86482         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
   86483         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
   86484         while(pFK){
   86485           int j;
   86486           for(j=0; j<pFK->nCol; j++){
   86487             char *zCol = pFK->aCol[j].zCol;
   86488             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
   86489             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
   86490             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
   86491             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
   86492             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
   86493             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
   86494                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
   86495             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
   86496             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
   86497             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
   86498             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
   86499             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
   86500           }
   86501           ++i;
   86502           pFK = pFK->pNextFrom;
   86503         }
   86504       }
   86505     }
   86506   }else
   86507 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
   86508 
   86509 #ifndef NDEBUG
   86510   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
   86511     if( zRight ){
   86512       if( getBoolean(zRight) ){
   86513         sqlite3ParserTrace(stderr, "parser: ");
   86514       }else{
   86515         sqlite3ParserTrace(0, 0);
   86516       }
   86517     }
   86518   }else
   86519 #endif
   86520 
   86521   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
   86522   ** used will be case sensitive or not depending on the RHS.
   86523   */
   86524   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
   86525     if( zRight ){
   86526       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
   86527     }
   86528   }else
   86529 
   86530 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
   86531 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
   86532 #endif
   86533 
   86534 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
   86535   /* Pragma "quick_check" is an experimental reduced version of
   86536   ** integrity_check designed to detect most database corruption
   86537   ** without most of the overhead of a full integrity-check.
   86538   */
   86539   if( sqlite3StrICmp(zLeft, "integrity_check")==0
   86540    || sqlite3StrICmp(zLeft, "quick_check")==0
   86541   ){
   86542     int i, j, addr, mxErr;
   86543 
   86544     /* Code that appears at the end of the integrity check.  If no error
   86545     ** messages have been generated, output OK.  Otherwise output the
   86546     ** error message
   86547     */
   86548     static const VdbeOpList endCode[] = {
   86549       { OP_AddImm,      1, 0,        0},    /* 0 */
   86550       { OP_IfNeg,       1, 0,        0},    /* 1 */
   86551       { OP_String8,     0, 3,        0},    /* 2 */
   86552       { OP_ResultRow,   3, 1,        0},
   86553     };
   86554 
   86555     int isQuick = (zLeft[0]=='q');
   86556 
   86557     /* Initialize the VDBE program */
   86558     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86559     pParse->nMem = 6;
   86560     sqlite3VdbeSetNumCols(v, 1);
   86561     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
   86562 
   86563     /* Set the maximum error count */
   86564     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   86565     if( zRight ){
   86566       sqlite3GetInt32(zRight, &mxErr);
   86567       if( mxErr<=0 ){
   86568         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
   86569       }
   86570     }
   86571     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
   86572 
   86573     /* Do an integrity check on each database file */
   86574     for(i=0; i<db->nDb; i++){
   86575       HashElem *x;
   86576       Hash *pTbls;
   86577       int cnt = 0;
   86578 
   86579       if( OMIT_TEMPDB && i==1 ) continue;
   86580 
   86581       sqlite3CodeVerifySchema(pParse, i);
   86582       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
   86583       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   86584       sqlite3VdbeJumpHere(v, addr);
   86585 
   86586       /* Do an integrity check of the B-Tree
   86587       **
   86588       ** Begin by filling registers 2, 3, ... with the root pages numbers
   86589       ** for all tables and indices in the database.
   86590       */
   86591       pTbls = &db->aDb[i].pSchema->tblHash;
   86592       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
   86593         Table *pTab = sqliteHashData(x);
   86594         Index *pIdx;
   86595         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
   86596         cnt++;
   86597         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   86598           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
   86599           cnt++;
   86600         }
   86601       }
   86602 
   86603       /* Make sure sufficient number of registers have been allocated */
   86604       if( pParse->nMem < cnt+4 ){
   86605         pParse->nMem = cnt+4;
   86606       }
   86607 
   86608       /* Do the b-tree integrity checks */
   86609       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
   86610       sqlite3VdbeChangeP5(v, (u8)i);
   86611       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
   86612       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
   86613          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
   86614          P4_DYNAMIC);
   86615       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
   86616       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
   86617       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
   86618       sqlite3VdbeJumpHere(v, addr);
   86619 
   86620       /* Make sure all the indices are constructed correctly.
   86621       */
   86622       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
   86623         Table *pTab = sqliteHashData(x);
   86624         Index *pIdx;
   86625         int loopTop;
   86626 
   86627         if( pTab->pIndex==0 ) continue;
   86628         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
   86629         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   86630         sqlite3VdbeJumpHere(v, addr);
   86631         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
   86632         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
   86633         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
   86634         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
   86635         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   86636           int jmp2;
   86637           int r1;
   86638           static const VdbeOpList idxErr[] = {
   86639             { OP_AddImm,      1, -1,  0},
   86640             { OP_String8,     0,  3,  0},    /* 1 */
   86641             { OP_Rowid,       1,  4,  0},
   86642             { OP_String8,     0,  5,  0},    /* 3 */
   86643             { OP_String8,     0,  6,  0},    /* 4 */
   86644             { OP_Concat,      4,  3,  3},
   86645             { OP_Concat,      5,  3,  3},
   86646             { OP_Concat,      6,  3,  3},
   86647             { OP_ResultRow,   3,  1,  0},
   86648             { OP_IfPos,       1,  0,  0},    /* 9 */
   86649             { OP_Halt,        0,  0,  0},
   86650           };
   86651           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
   86652           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
   86653           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
   86654           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
   86655           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
   86656           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
   86657           sqlite3VdbeJumpHere(v, addr+9);
   86658           sqlite3VdbeJumpHere(v, jmp2);
   86659         }
   86660         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
   86661         sqlite3VdbeJumpHere(v, loopTop);
   86662         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   86663           static const VdbeOpList cntIdx[] = {
   86664              { OP_Integer,      0,  3,  0},
   86665              { OP_Rewind,       0,  0,  0},  /* 1 */
   86666              { OP_AddImm,       3,  1,  0},
   86667              { OP_Next,         0,  0,  0},  /* 3 */
   86668              { OP_Eq,           2,  0,  3},  /* 4 */
   86669              { OP_AddImm,       1, -1,  0},
   86670              { OP_String8,      0,  2,  0},  /* 6 */
   86671              { OP_String8,      0,  3,  0},  /* 7 */
   86672              { OP_Concat,       3,  2,  2},
   86673              { OP_ResultRow,    2,  1,  0},
   86674           };
   86675           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
   86676           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
   86677           sqlite3VdbeJumpHere(v, addr);
   86678           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
   86679           sqlite3VdbeChangeP1(v, addr+1, j+2);
   86680           sqlite3VdbeChangeP2(v, addr+1, addr+4);
   86681           sqlite3VdbeChangeP1(v, addr+3, j+2);
   86682           sqlite3VdbeChangeP2(v, addr+3, addr+2);
   86683           sqlite3VdbeJumpHere(v, addr+4);
   86684           sqlite3VdbeChangeP4(v, addr+6,
   86685                      "wrong # of entries in index ", P4_STATIC);
   86686           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
   86687         }
   86688       }
   86689     }
   86690     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
   86691     sqlite3VdbeChangeP2(v, addr, -mxErr);
   86692     sqlite3VdbeJumpHere(v, addr+1);
   86693     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
   86694   }else
   86695 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
   86696 
   86697 #ifndef SQLITE_OMIT_UTF16
   86698   /*
   86699   **   PRAGMA encoding
   86700   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
   86701   **
   86702   ** In its first form, this pragma returns the encoding of the main
   86703   ** database. If the database is not initialized, it is initialized now.
   86704   **
   86705   ** The second form of this pragma is a no-op if the main database file
   86706   ** has not already been initialized. In this case it sets the default
   86707   ** encoding that will be used for the main database file if a new file
   86708   ** is created. If an existing main database file is opened, then the
   86709   ** default text encoding for the existing database is used.
   86710   **
   86711   ** In all cases new databases created using the ATTACH command are
   86712   ** created to use the same default text encoding as the main database. If
   86713   ** the main database has not been initialized and/or created when ATTACH
   86714   ** is executed, this is done before the ATTACH operation.
   86715   **
   86716   ** In the second form this pragma sets the text encoding to be used in
   86717   ** new database files created using this database handle. It is only
   86718   ** useful if invoked immediately after the main database i
   86719   */
   86720   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
   86721     static const struct EncName {
   86722       char *zName;
   86723       u8 enc;
   86724     } encnames[] = {
   86725       { "UTF8",     SQLITE_UTF8        },
   86726       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
   86727       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
   86728       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
   86729       { "UTF16le",  SQLITE_UTF16LE     },
   86730       { "UTF16be",  SQLITE_UTF16BE     },
   86731       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
   86732       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
   86733       { 0, 0 }
   86734     };
   86735     const struct EncName *pEnc;
   86736     if( !zRight ){    /* "PRAGMA encoding" */
   86737       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86738       sqlite3VdbeSetNumCols(v, 1);
   86739       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
   86740       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
   86741       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
   86742       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
   86743       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
   86744       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
   86745       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   86746     }else{                        /* "PRAGMA encoding = XXX" */
   86747       /* Only change the value of sqlite.enc if the database handle is not
   86748       ** initialized. If the main database exists, the new sqlite.enc value
   86749       ** will be overwritten when the schema is next loaded. If it does not
   86750       ** already exists, it will be created to use the new encoding value.
   86751       */
   86752       if(
   86753         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
   86754         DbHasProperty(db, 0, DB_Empty)
   86755       ){
   86756         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
   86757           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
   86758             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
   86759             break;
   86760           }
   86761         }
   86762         if( !pEnc->zName ){
   86763           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
   86764         }
   86765       }
   86766     }
   86767   }else
   86768 #endif /* SQLITE_OMIT_UTF16 */
   86769 
   86770 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
   86771   /*
   86772   **   PRAGMA [database.]schema_version
   86773   **   PRAGMA [database.]schema_version = <integer>
   86774   **
   86775   **   PRAGMA [database.]user_version
   86776   **   PRAGMA [database.]user_version = <integer>
   86777   **
   86778   ** The pragma's schema_version and user_version are used to set or get
   86779   ** the value of the schema-version and user-version, respectively. Both
   86780   ** the schema-version and the user-version are 32-bit signed integers
   86781   ** stored in the database header.
   86782   **
   86783   ** The schema-cookie is usually only manipulated internally by SQLite. It
   86784   ** is incremented by SQLite whenever the database schema is modified (by
   86785   ** creating or dropping a table or index). The schema version is used by
   86786   ** SQLite each time a query is executed to ensure that the internal cache
   86787   ** of the schema used when compiling the SQL query matches the schema of
   86788   ** the database against which the compiled query is actually executed.
   86789   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
   86790   ** the schema-version is potentially dangerous and may lead to program
   86791   ** crashes or database corruption. Use with caution!
   86792   **
   86793   ** The user-version is not used internally by SQLite. It may be used by
   86794   ** applications for any purpose.
   86795   */
   86796   if( sqlite3StrICmp(zLeft, "schema_version")==0
   86797    || sqlite3StrICmp(zLeft, "user_version")==0
   86798    || sqlite3StrICmp(zLeft, "freelist_count")==0
   86799   ){
   86800     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
   86801     sqlite3VdbeUsesBtree(v, iDb);
   86802     switch( zLeft[0] ){
   86803       case 'f': case 'F':
   86804         iCookie = BTREE_FREE_PAGE_COUNT;
   86805         break;
   86806       case 's': case 'S':
   86807         iCookie = BTREE_SCHEMA_VERSION;
   86808         break;
   86809       default:
   86810         iCookie = BTREE_USER_VERSION;
   86811         break;
   86812     }
   86813 
   86814     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
   86815       /* Write the specified cookie value */
   86816       static const VdbeOpList setCookie[] = {
   86817         { OP_Transaction,    0,  1,  0},    /* 0 */
   86818         { OP_Integer,        0,  1,  0},    /* 1 */
   86819         { OP_SetCookie,      0,  0,  1},    /* 2 */
   86820       };
   86821       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
   86822       sqlite3VdbeChangeP1(v, addr, iDb);
   86823       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
   86824       sqlite3VdbeChangeP1(v, addr+2, iDb);
   86825       sqlite3VdbeChangeP2(v, addr+2, iCookie);
   86826     }else{
   86827       /* Read the specified cookie value */
   86828       static const VdbeOpList readCookie[] = {
   86829         { OP_Transaction,     0,  0,  0},    /* 0 */
   86830         { OP_ReadCookie,      0,  1,  0},    /* 1 */
   86831         { OP_ResultRow,       1,  1,  0}
   86832       };
   86833       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
   86834       sqlite3VdbeChangeP1(v, addr, iDb);
   86835       sqlite3VdbeChangeP1(v, addr+1, iDb);
   86836       sqlite3VdbeChangeP3(v, addr+1, iCookie);
   86837       sqlite3VdbeSetNumCols(v, 1);
   86838       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   86839     }
   86840   }else
   86841 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
   86842 
   86843 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
   86844   /*
   86845   **   PRAGMA compile_options
   86846   **
   86847   ** Return the names of all compile-time options used in this build,
   86848   ** one option per row.
   86849   */
   86850   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
   86851     int i = 0;
   86852     const char *zOpt;
   86853     sqlite3VdbeSetNumCols(v, 1);
   86854     pParse->nMem = 1;
   86855     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
   86856     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
   86857       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
   86858       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
   86859     }
   86860   }else
   86861 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
   86862 
   86863 #ifndef SQLITE_OMIT_WAL
   86864   /*
   86865   **   PRAGMA [database.]wal_checkpoint
   86866   **
   86867   ** Checkpoint the database.
   86868   */
   86869   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
   86870     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   86871     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
   86872   }else
   86873 
   86874   /*
   86875   **   PRAGMA wal_autocheckpoint
   86876   **   PRAGMA wal_autocheckpoint = N
   86877   **
   86878   ** Configure a database connection to automatically checkpoint a database
   86879   ** after accumulating N frames in the log. Or query for the current value
   86880   ** of N.
   86881   */
   86882   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
   86883     if( zRight ){
   86884       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
   86885     }
   86886     returnSingleInt(pParse, "wal_autocheckpoint",
   86887        db->xWalCallback==sqlite3WalDefaultHook ?
   86888            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   86889   }else
   86890 #endif
   86891 
   86892 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   86893   /*
   86894   ** Report the current state of file logs for all databases
   86895   */
   86896   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
   86897     static const char *const azLockName[] = {
   86898       "unlocked", "shared", "reserved", "pending", "exclusive"
   86899     };
   86900     int i;
   86901     sqlite3VdbeSetNumCols(v, 2);
   86902     pParse->nMem = 2;
   86903     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
   86904     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
   86905     for(i=0; i<db->nDb; i++){
   86906       Btree *pBt;
   86907       Pager *pPager;
   86908       const char *zState = "unknown";
   86909       int j;
   86910       if( db->aDb[i].zName==0 ) continue;
   86911       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
   86912       pBt = db->aDb[i].pBt;
   86913       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
   86914         zState = "closed";
   86915       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
   86916                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
   86917          zState = azLockName[j];
   86918       }
   86919       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
   86920       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
   86921     }
   86922 
   86923   }else
   86924 #endif
   86925 
   86926 #ifdef SQLITE_HAS_CODEC
   86927   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
   86928     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
   86929   }else
   86930   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
   86931     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
   86932   }else
   86933   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
   86934                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
   86935     int i, h1, h2;
   86936     char zKey[40];
   86937     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
   86938       h1 += 9*(1&(h1>>6));
   86939       h2 += 9*(1&(h2>>6));
   86940       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
   86941     }
   86942     if( (zLeft[3] & 0xf)==0xb ){
   86943       sqlite3_key(db, zKey, i/2);
   86944     }else{
   86945       sqlite3_rekey(db, zKey, i/2);
   86946     }
   86947   }else
   86948 #endif
   86949 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
   86950   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
   86951 #ifdef SQLITE_HAS_CODEC
   86952     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
   86953       sqlite3_activate_see(&zRight[4]);
   86954     }
   86955 #endif
   86956 #ifdef SQLITE_ENABLE_CEROD
   86957     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
   86958       sqlite3_activate_cerod(&zRight[6]);
   86959     }
   86960 #endif
   86961   }else
   86962 #endif
   86963 
   86964 
   86965   {/* Empty ELSE clause */}
   86966 
   86967   /*
   86968   ** Reset the safety level, in case the fullfsync flag or synchronous
   86969   ** setting changed.
   86970   */
   86971 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   86972   if( db->autoCommit ){
   86973     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
   86974                (db->flags&SQLITE_FullFSync)!=0,
   86975                (db->flags&SQLITE_CkptFullFSync)!=0);
   86976   }
   86977 #endif
   86978 pragma_out:
   86979   sqlite3DbFree(db, zLeft);
   86980   sqlite3DbFree(db, zRight);
   86981 }
   86982 
   86983 #endif /* SQLITE_OMIT_PRAGMA */
   86984 
   86985 /************** End of pragma.c **********************************************/
   86986 /************** Begin file prepare.c *****************************************/
   86987 /*
   86988 ** 2005 May 25
   86989 **
   86990 ** The author disclaims copyright to this source code.  In place of
   86991 ** a legal notice, here is a blessing:
   86992 **
   86993 **    May you do good and not evil.
   86994 **    May you find forgiveness for yourself and forgive others.
   86995 **    May you share freely, never taking more than you give.
   86996 **
   86997 *************************************************************************
   86998 ** This file contains the implementation of the sqlite3_prepare()
   86999 ** interface, and routines that contribute to loading the database schema
   87000 ** from disk.
   87001 */
   87002 
   87003 /*
   87004 ** Fill the InitData structure with an error message that indicates
   87005 ** that the database is corrupt.
   87006 */
   87007 static void corruptSchema(
   87008   InitData *pData,     /* Initialization context */
   87009   const char *zObj,    /* Object being parsed at the point of error */
   87010   const char *zExtra   /* Error information */
   87011 ){
   87012   sqlite3 *db = pData->db;
   87013   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
   87014     if( zObj==0 ) zObj = "?";
   87015     sqlite3SetString(pData->pzErrMsg, db,
   87016       "malformed database schema (%s)", zObj);
   87017     if( zExtra ){
   87018       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
   87019                                  "%s - %s", *pData->pzErrMsg, zExtra);
   87020     }
   87021   }
   87022   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
   87023 }
   87024 
   87025 /*
   87026 ** This is the callback routine for the code that initializes the
   87027 ** database.  See sqlite3Init() below for additional information.
   87028 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
   87029 **
   87030 ** Each callback contains the following information:
   87031 **
   87032 **     argv[0] = name of thing being created
   87033 **     argv[1] = root page number for table or index. 0 for trigger or view.
   87034 **     argv[2] = SQL text for the CREATE statement.
   87035 **
   87036 */
   87037 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
   87038   InitData *pData = (InitData*)pInit;
   87039   sqlite3 *db = pData->db;
   87040   int iDb = pData->iDb;
   87041 
   87042   assert( argc==3 );
   87043   UNUSED_PARAMETER2(NotUsed, argc);
   87044   assert( sqlite3_mutex_held(db->mutex) );
   87045   DbClearProperty(db, iDb, DB_Empty);
   87046   if( db->mallocFailed ){
   87047     corruptSchema(pData, argv[0], 0);
   87048     return 1;
   87049   }
   87050 
   87051   assert( iDb>=0 && iDb<db->nDb );
   87052   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
   87053   if( argv[1]==0 ){
   87054     corruptSchema(pData, argv[0], 0);
   87055   }else if( argv[2] && argv[2][0] ){
   87056     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
   87057     ** But because db->init.busy is set to 1, no VDBE code is generated
   87058     ** or executed.  All the parser does is build the internal data
   87059     ** structures that describe the table, index, or view.
   87060     */
   87061     int rc;
   87062     sqlite3_stmt *pStmt;
   87063     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
   87064 
   87065     assert( db->init.busy );
   87066     db->init.iDb = iDb;
   87067     db->init.newTnum = sqlite3Atoi(argv[1]);
   87068     db->init.orphanTrigger = 0;
   87069     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
   87070     rc = db->errCode;
   87071     assert( (rc&0xFF)==(rcp&0xFF) );
   87072     db->init.iDb = 0;
   87073     if( SQLITE_OK!=rc ){
   87074       if( db->init.orphanTrigger ){
   87075         assert( iDb==1 );
   87076       }else{
   87077         pData->rc = rc;
   87078         if( rc==SQLITE_NOMEM ){
   87079           db->mallocFailed = 1;
   87080         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
   87081           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
   87082         }
   87083       }
   87084     }
   87085     sqlite3_finalize(pStmt);
   87086   }else if( argv[0]==0 ){
   87087     corruptSchema(pData, 0, 0);
   87088   }else{
   87089     /* If the SQL column is blank it means this is an index that
   87090     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
   87091     ** constraint for a CREATE TABLE.  The index should have already
   87092     ** been created when we processed the CREATE TABLE.  All we have
   87093     ** to do here is record the root page number for that index.
   87094     */
   87095     Index *pIndex;
   87096     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
   87097     if( pIndex==0 ){
   87098       /* This can occur if there exists an index on a TEMP table which
   87099       ** has the same name as another index on a permanent index.  Since
   87100       ** the permanent table is hidden by the TEMP table, we can also
   87101       ** safely ignore the index on the permanent table.
   87102       */
   87103       /* Do Nothing */;
   87104     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
   87105       corruptSchema(pData, argv[0], "invalid rootpage");
   87106     }
   87107   }
   87108   return 0;
   87109 }
   87110 
   87111 /*
   87112 ** Attempt to read the database schema and initialize internal
   87113 ** data structures for a single database file.  The index of the
   87114 ** database file is given by iDb.  iDb==0 is used for the main
   87115 ** database.  iDb==1 should never be used.  iDb>=2 is used for
   87116 ** auxiliary databases.  Return one of the SQLITE_ error codes to
   87117 ** indicate success or failure.
   87118 */
   87119 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
   87120   int rc;
   87121   int i;
   87122   int size;
   87123   Table *pTab;
   87124   Db *pDb;
   87125   char const *azArg[4];
   87126   int meta[5];
   87127   InitData initData;
   87128   char const *zMasterSchema;
   87129   char const *zMasterName = SCHEMA_TABLE(iDb);
   87130   int openedTransaction = 0;
   87131 
   87132   /*
   87133   ** The master database table has a structure like this
   87134   */
   87135   static const char master_schema[] =
   87136      "CREATE TABLE sqlite_master(\n"
   87137      "  type text,\n"
   87138      "  name text,\n"
   87139      "  tbl_name text,\n"
   87140      "  rootpage integer,\n"
   87141      "  sql text\n"
   87142      ")"
   87143   ;
   87144 #ifndef SQLITE_OMIT_TEMPDB
   87145   static const char temp_master_schema[] =
   87146      "CREATE TEMP TABLE sqlite_temp_master(\n"
   87147      "  type text,\n"
   87148      "  name text,\n"
   87149      "  tbl_name text,\n"
   87150      "  rootpage integer,\n"
   87151      "  sql text\n"
   87152      ")"
   87153   ;
   87154 #else
   87155   #define temp_master_schema 0
   87156 #endif
   87157 
   87158   assert( iDb>=0 && iDb<db->nDb );
   87159   assert( db->aDb[iDb].pSchema );
   87160   assert( sqlite3_mutex_held(db->mutex) );
   87161   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
   87162 
   87163   /* zMasterSchema and zInitScript are set to point at the master schema
   87164   ** and initialisation script appropriate for the database being
   87165   ** initialised. zMasterName is the name of the master table.
   87166   */
   87167   if( !OMIT_TEMPDB && iDb==1 ){
   87168     zMasterSchema = temp_master_schema;
   87169   }else{
   87170     zMasterSchema = master_schema;
   87171   }
   87172   zMasterName = SCHEMA_TABLE(iDb);
   87173 
   87174   /* Construct the schema tables.  */
   87175   azArg[0] = zMasterName;
   87176   azArg[1] = "1";
   87177   azArg[2] = zMasterSchema;
   87178   azArg[3] = 0;
   87179   initData.db = db;
   87180   initData.iDb = iDb;
   87181   initData.rc = SQLITE_OK;
   87182   initData.pzErrMsg = pzErrMsg;
   87183   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
   87184   if( initData.rc ){
   87185     rc = initData.rc;
   87186     goto error_out;
   87187   }
   87188   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
   87189   if( ALWAYS(pTab) ){
   87190     pTab->tabFlags |= TF_Readonly;
   87191   }
   87192 
   87193   /* Create a cursor to hold the database open
   87194   */
   87195   pDb = &db->aDb[iDb];
   87196   if( pDb->pBt==0 ){
   87197     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
   87198       DbSetProperty(db, 1, DB_SchemaLoaded);
   87199     }
   87200     return SQLITE_OK;
   87201   }
   87202 
   87203   /* If there is not already a read-only (or read-write) transaction opened
   87204   ** on the b-tree database, open one now. If a transaction is opened, it
   87205   ** will be closed before this function returns.  */
   87206   sqlite3BtreeEnter(pDb->pBt);
   87207   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
   87208     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
   87209     if( rc!=SQLITE_OK ){
   87210       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
   87211       goto initone_error_out;
   87212     }
   87213     openedTransaction = 1;
   87214   }
   87215 
   87216   /* Get the database meta information.
   87217   **
   87218   ** Meta values are as follows:
   87219   **    meta[0]   Schema cookie.  Changes with each schema change.
   87220   **    meta[1]   File format of schema layer.
   87221   **    meta[2]   Size of the page cache.
   87222   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
   87223   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
   87224   **    meta[5]   User version
   87225   **    meta[6]   Incremental vacuum mode
   87226   **    meta[7]   unused
   87227   **    meta[8]   unused
   87228   **    meta[9]   unused
   87229   **
   87230   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
   87231   ** the possible values of meta[4].
   87232   */
   87233   for(i=0; i<ArraySize(meta); i++){
   87234     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
   87235   }
   87236   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
   87237 
   87238   /* If opening a non-empty database, check the text encoding. For the
   87239   ** main database, set sqlite3.enc to the encoding of the main database.
   87240   ** For an attached db, it is an error if the encoding is not the same
   87241   ** as sqlite3.enc.
   87242   */
   87243   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
   87244     if( iDb==0 ){
   87245       u8 encoding;
   87246       /* If opening the main database, set ENC(db). */
   87247       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
   87248       if( encoding==0 ) encoding = SQLITE_UTF8;
   87249       ENC(db) = encoding;
   87250       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   87251     }else{
   87252       /* If opening an attached database, the encoding much match ENC(db) */
   87253       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
   87254         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
   87255             " text encoding as main database");
   87256         rc = SQLITE_ERROR;
   87257         goto initone_error_out;
   87258       }
   87259     }
   87260   }else{
   87261     DbSetProperty(db, iDb, DB_Empty);
   87262   }
   87263   pDb->pSchema->enc = ENC(db);
   87264 
   87265   if( pDb->pSchema->cache_size==0 ){
   87266     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
   87267     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   87268     if( size<0 ) size = -size;
   87269     pDb->pSchema->cache_size = size;
   87270     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   87271   }
   87272 
   87273   /*
   87274   ** file_format==1    Version 3.0.0.
   87275   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   87276   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
   87277   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
   87278   */
   87279   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
   87280   if( pDb->pSchema->file_format==0 ){
   87281     pDb->pSchema->file_format = 1;
   87282   }
   87283   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
   87284     sqlite3SetString(pzErrMsg, db, "unsupported file format");
   87285     rc = SQLITE_CORRUPT_BKPT; // Android Change from "rc = SQLITE_ERROR;"
   87286     goto initone_error_out;
   87287   }
   87288 
   87289   /* Ticket #2804:  When we open a database in the newer file format,
   87290   ** clear the legacy_file_format pragma flag so that a VACUUM will
   87291   ** not downgrade the database and thus invalidate any descending
   87292   ** indices that the user might have created.
   87293   */
   87294   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
   87295     db->flags &= ~SQLITE_LegacyFileFmt;
   87296   }
   87297 
   87298   /* Read the schema information out of the schema tables
   87299   */
   87300   assert( db->init.busy );
   87301   {
   87302     char *zSql;
   87303     zSql = sqlite3MPrintf(db,
   87304         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
   87305         db->aDb[iDb].zName, zMasterName);
   87306 #ifndef SQLITE_OMIT_AUTHORIZATION
   87307     {
   87308       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
   87309       xAuth = db->xAuth;
   87310       db->xAuth = 0;
   87311 #endif
   87312       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
   87313 #ifndef SQLITE_OMIT_AUTHORIZATION
   87314       db->xAuth = xAuth;
   87315     }
   87316 #endif
   87317     if( rc==SQLITE_OK ) rc = initData.rc;
   87318     sqlite3DbFree(db, zSql);
   87319 #ifndef SQLITE_OMIT_ANALYZE
   87320     if( rc==SQLITE_OK ){
   87321       sqlite3AnalysisLoad(db, iDb);
   87322     }
   87323 #endif
   87324   }
   87325   if( db->mallocFailed ){
   87326     rc = SQLITE_NOMEM;
   87327     sqlite3ResetInternalSchema(db, 0);
   87328   }
   87329   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
   87330     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
   87331     ** the schema loaded, even if errors occurred. In this situation the
   87332     ** current sqlite3_prepare() operation will fail, but the following one
   87333     ** will attempt to compile the supplied statement against whatever subset
   87334     ** of the schema was loaded before the error occurred. The primary
   87335     ** purpose of this is to allow access to the sqlite_master table
   87336     ** even when its contents have been corrupted.
   87337     */
   87338     DbSetProperty(db, iDb, DB_SchemaLoaded);
   87339     rc = SQLITE_OK;
   87340   }
   87341 
   87342   /* Jump here for an error that occurs after successfully allocating
   87343   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
   87344   ** before that point, jump to error_out.
   87345   */
   87346 initone_error_out:
   87347   if( openedTransaction ){
   87348     sqlite3BtreeCommit(pDb->pBt);
   87349   }
   87350   sqlite3BtreeLeave(pDb->pBt);
   87351 
   87352 error_out:
   87353   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   87354     db->mallocFailed = 1;
   87355   }
   87356   return rc;
   87357 }
   87358 
   87359 /*
   87360 ** Initialize all database files - the main database file, the file
   87361 ** used to store temporary tables, and any additional database files
   87362 ** created using ATTACH statements.  Return a success code.  If an
   87363 ** error occurs, write an error message into *pzErrMsg.
   87364 **
   87365 ** After a database is initialized, the DB_SchemaLoaded bit is set
   87366 ** bit is set in the flags field of the Db structure. If the database
   87367 ** file was of zero-length, then the DB_Empty flag is also set.
   87368 */
   87369 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   87370   int i, rc;
   87371   int commit_internal = !(db->flags&SQLITE_InternChanges);
   87372 
   87373   assert( sqlite3_mutex_held(db->mutex) );
   87374   rc = SQLITE_OK;
   87375   db->init.busy = 1;
   87376   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
   87377     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
   87378     rc = sqlite3InitOne(db, i, pzErrMsg);
   87379     if( rc ){
   87380       sqlite3ResetInternalSchema(db, i);
   87381     }
   87382   }
   87383 
   87384   /* Once all the other databases have been initialised, load the schema
   87385   ** for the TEMP database. This is loaded last, as the TEMP database
   87386   ** schema may contain references to objects in other databases.
   87387   */
   87388 #ifndef SQLITE_OMIT_TEMPDB
   87389   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
   87390                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
   87391     rc = sqlite3InitOne(db, 1, pzErrMsg);
   87392     if( rc ){
   87393       sqlite3ResetInternalSchema(db, 1);
   87394     }
   87395   }
   87396 #endif
   87397 
   87398   db->init.busy = 0;
   87399   if( rc==SQLITE_OK && commit_internal ){
   87400     sqlite3CommitInternalChanges(db);
   87401   }
   87402 
   87403   return rc;
   87404 }
   87405 
   87406 /*
   87407 ** This routine is a no-op if the database schema is already initialised.
   87408 ** Otherwise, the schema is loaded. An error code is returned.
   87409 */
   87410 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
   87411   int rc = SQLITE_OK;
   87412   sqlite3 *db = pParse->db;
   87413   assert( sqlite3_mutex_held(db->mutex) );
   87414   if( !db->init.busy ){
   87415     rc = sqlite3Init(db, &pParse->zErrMsg);
   87416   }
   87417   if( rc!=SQLITE_OK ){
   87418     pParse->rc = rc;
   87419     pParse->nErr++;
   87420   }
   87421   return rc;
   87422 }
   87423 
   87424 
   87425 /*
   87426 ** Check schema cookies in all databases.  If any cookie is out
   87427 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
   87428 ** make no changes to pParse->rc.
   87429 */
   87430 static void schemaIsValid(Parse *pParse){
   87431   sqlite3 *db = pParse->db;
   87432   int iDb;
   87433   int rc;
   87434   int cookie;
   87435 
   87436   assert( pParse->checkSchema );
   87437   assert( sqlite3_mutex_held(db->mutex) );
   87438   for(iDb=0; iDb<db->nDb; iDb++){
   87439     int openedTransaction = 0;         /* True if a transaction is opened */
   87440     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
   87441     if( pBt==0 ) continue;
   87442 
   87443     /* If there is not already a read-only (or read-write) transaction opened
   87444     ** on the b-tree database, open one now. If a transaction is opened, it
   87445     ** will be closed immediately after reading the meta-value. */
   87446     if( !sqlite3BtreeIsInReadTrans(pBt) ){
   87447       rc = sqlite3BtreeBeginTrans(pBt, 0);
   87448       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   87449         db->mallocFailed = 1;
   87450       }
   87451       if( rc!=SQLITE_OK ) return;
   87452       openedTransaction = 1;
   87453     }
   87454 
   87455     /* Read the schema cookie from the database. If it does not match the
   87456     ** value stored as part of the in-memory schema representation,
   87457     ** set Parse.rc to SQLITE_SCHEMA. */
   87458     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
   87459     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
   87460       pParse->rc = SQLITE_SCHEMA;
   87461     }
   87462 
   87463     /* Close the transaction, if one was opened. */
   87464     if( openedTransaction ){
   87465       sqlite3BtreeCommit(pBt);
   87466     }
   87467   }
   87468 }
   87469 
   87470 /*
   87471 ** Convert a schema pointer into the iDb index that indicates
   87472 ** which database file in db->aDb[] the schema refers to.
   87473 **
   87474 ** If the same database is attached more than once, the first
   87475 ** attached database is returned.
   87476 */
   87477 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
   87478   int i = -1000000;
   87479 
   87480   /* If pSchema is NULL, then return -1000000. This happens when code in
   87481   ** expr.c is trying to resolve a reference to a transient table (i.e. one
   87482   ** created by a sub-select). In this case the return value of this
   87483   ** function should never be used.
   87484   **
   87485   ** We return -1000000 instead of the more usual -1 simply because using
   87486   ** -1000000 as the incorrect index into db->aDb[] is much
   87487   ** more likely to cause a segfault than -1 (of course there are assert()
   87488   ** statements too, but it never hurts to play the odds).
   87489   */
   87490   assert( sqlite3_mutex_held(db->mutex) );
   87491   if( pSchema ){
   87492     for(i=0; ALWAYS(i<db->nDb); i++){
   87493       if( db->aDb[i].pSchema==pSchema ){
   87494         break;
   87495       }
   87496     }
   87497     assert( i>=0 && i<db->nDb );
   87498   }
   87499   return i;
   87500 }
   87501 
   87502 /*
   87503 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   87504 */
   87505 static int sqlite3Prepare(
   87506   sqlite3 *db,              /* Database handle. */
   87507   const char *zSql,         /* UTF-8 encoded SQL statement. */
   87508   int nBytes,               /* Length of zSql in bytes. */
   87509   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   87510   Vdbe *pReprepare,         /* VM being reprepared */
   87511   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87512   const char **pzTail       /* OUT: End of parsed string */
   87513 ){
   87514   Parse *pParse;            /* Parsing context */
   87515   char *zErrMsg = 0;        /* Error message */
   87516   int rc = SQLITE_OK;       /* Result code */
   87517   int i;                    /* Loop counter */
   87518 
   87519   /* Allocate the parsing context */
   87520   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   87521   if( pParse==0 ){
   87522     rc = SQLITE_NOMEM;
   87523     goto end_prepare;
   87524   }
   87525   pParse->pReprepare = pReprepare;
   87526   assert( ppStmt && *ppStmt==0 );
   87527   assert( !db->mallocFailed );
   87528   assert( sqlite3_mutex_held(db->mutex) );
   87529 
   87530   /* Check to verify that it is possible to get a read lock on all
   87531   ** database schemas.  The inability to get a read lock indicates that
   87532   ** some other database connection is holding a write-lock, which in
   87533   ** turn means that the other connection has made uncommitted changes
   87534   ** to the schema.
   87535   **
   87536   ** Were we to proceed and prepare the statement against the uncommitted
   87537   ** schema changes and if those schema changes are subsequently rolled
   87538   ** back and different changes are made in their place, then when this
   87539   ** prepared statement goes to run the schema cookie would fail to detect
   87540   ** the schema change.  Disaster would follow.
   87541   **
   87542   ** This thread is currently holding mutexes on all Btrees (because
   87543   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   87544   ** is not possible for another thread to start a new schema change
   87545   ** while this routine is running.  Hence, we do not need to hold
   87546   ** locks on the schema, we just need to make sure nobody else is
   87547   ** holding them.
   87548   **
   87549   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   87550   ** but it does *not* override schema lock detection, so this all still
   87551   ** works even if READ_UNCOMMITTED is set.
   87552   */
   87553   for(i=0; i<db->nDb; i++) {
   87554     Btree *pBt = db->aDb[i].pBt;
   87555     if( pBt ){
   87556       assert( sqlite3BtreeHoldsMutex(pBt) );
   87557       rc = sqlite3BtreeSchemaLocked(pBt);
   87558       if( rc ){
   87559         const char *zDb = db->aDb[i].zName;
   87560         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
   87561         testcase( db->flags & SQLITE_ReadUncommitted );
   87562         goto end_prepare;
   87563       }
   87564     }
   87565   }
   87566 
   87567   sqlite3VtabUnlockList(db);
   87568 
   87569   pParse->db = db;
   87570   pParse->nQueryLoop = (double)1;
   87571   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
   87572     char *zSqlCopy;
   87573     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   87574     testcase( nBytes==mxLen );
   87575     testcase( nBytes==mxLen+1 );
   87576     if( nBytes>mxLen ){
   87577       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
   87578       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
   87579       goto end_prepare;
   87580     }
   87581     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
   87582     if( zSqlCopy ){
   87583       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
   87584       sqlite3DbFree(db, zSqlCopy);
   87585       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
   87586     }else{
   87587       pParse->zTail = &zSql[nBytes];
   87588     }
   87589   }else{
   87590     sqlite3RunParser(pParse, zSql, &zErrMsg);
   87591   }
   87592   assert( 1==(int)pParse->nQueryLoop );
   87593 
   87594   if( db->mallocFailed ){
   87595     pParse->rc = SQLITE_NOMEM;
   87596   }
   87597   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   87598   if( pParse->checkSchema ){
   87599     schemaIsValid(pParse);
   87600   }
   87601   if( pParse->rc==SQLITE_SCHEMA ){
   87602     sqlite3ResetInternalSchema(db, 0);
   87603   }
   87604   if( db->mallocFailed ){
   87605     pParse->rc = SQLITE_NOMEM;
   87606   }
   87607   if( pzTail ){
   87608     *pzTail = pParse->zTail;
   87609   }
   87610   rc = pParse->rc;
   87611 
   87612 #ifndef SQLITE_OMIT_EXPLAIN
   87613   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
   87614     static const char * const azColName[] = {
   87615        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
   87616        "selectid", "order", "from", "detail"
   87617     };
   87618     int iFirst, mx;
   87619     if( pParse->explain==2 ){
   87620       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
   87621       iFirst = 8;
   87622       mx = 12;
   87623     }else{
   87624       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
   87625       iFirst = 0;
   87626       mx = 8;
   87627     }
   87628     for(i=iFirst; i<mx; i++){
   87629       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
   87630                             azColName[i], SQLITE_STATIC);
   87631     }
   87632   }
   87633 #endif
   87634 
   87635   assert( db->init.busy==0 || saveSqlFlag==0 );
   87636   if( db->init.busy==0 ){
   87637     Vdbe *pVdbe = pParse->pVdbe;
   87638     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
   87639   }
   87640   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
   87641     sqlite3VdbeFinalize(pParse->pVdbe);
   87642     assert(!(*ppStmt));
   87643   }else{
   87644     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
   87645   }
   87646 
   87647   if( zErrMsg ){
   87648     sqlite3Error(db, rc, "%s", zErrMsg);
   87649     sqlite3DbFree(db, zErrMsg);
   87650   }else{
   87651     sqlite3Error(db, rc, 0);
   87652   }
   87653 
   87654   /* Delete any TriggerPrg structures allocated while parsing this statement. */
   87655   while( pParse->pTriggerPrg ){
   87656     TriggerPrg *pT = pParse->pTriggerPrg;
   87657     pParse->pTriggerPrg = pT->pNext;
   87658     sqlite3DbFree(db, pT);
   87659   }
   87660 
   87661 end_prepare:
   87662 
   87663   sqlite3StackFree(db, pParse);
   87664   rc = sqlite3ApiExit(db, rc);
   87665   assert( (rc&db->errMask)==rc );
   87666   return rc;
   87667 }
   87668 static int sqlite3LockAndPrepare(
   87669   sqlite3 *db,              /* Database handle. */
   87670   const char *zSql,         /* UTF-8 encoded SQL statement. */
   87671   int nBytes,               /* Length of zSql in bytes. */
   87672   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
   87673   Vdbe *pOld,               /* VM being reprepared */
   87674   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87675   const char **pzTail       /* OUT: End of parsed string */
   87676 ){
   87677   int rc;
   87678   assert( ppStmt!=0 );
   87679   *ppStmt = 0;
   87680   if( !sqlite3SafetyCheckOk(db) ){
   87681     return SQLITE_MISUSE_BKPT;
   87682   }
   87683   sqlite3_mutex_enter(db->mutex);
   87684   sqlite3BtreeEnterAll(db);
   87685   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   87686   if( rc==SQLITE_SCHEMA ){
   87687     sqlite3_finalize(*ppStmt);
   87688     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
   87689   }
   87690   sqlite3BtreeLeaveAll(db);
   87691   sqlite3_mutex_leave(db->mutex);
   87692   return rc;
   87693 }
   87694 
   87695 /*
   87696 ** Rerun the compilation of a statement after a schema change.
   87697 **
   87698 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
   87699 ** if the statement cannot be recompiled because another connection has
   87700 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
   87701 ** occurs, return SQLITE_SCHEMA.
   87702 */
   87703 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
   87704   int rc;
   87705   sqlite3_stmt *pNew;
   87706   const char *zSql;
   87707   sqlite3 *db;
   87708 
   87709   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
   87710   zSql = sqlite3_sql((sqlite3_stmt *)p);
   87711   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   87712   db = sqlite3VdbeDb(p);
   87713   assert( sqlite3_mutex_held(db->mutex) );
   87714   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   87715   if( rc ){
   87716     if( rc==SQLITE_NOMEM ){
   87717       db->mallocFailed = 1;
   87718     }
   87719     assert( pNew==0 );
   87720     return rc;
   87721   }else{
   87722     assert( pNew!=0 );
   87723   }
   87724   sqlite3VdbeSwap((Vdbe*)pNew, p);
   87725   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
   87726   sqlite3VdbeResetStepResult((Vdbe*)pNew);
   87727   sqlite3VdbeFinalize((Vdbe*)pNew);
   87728   return SQLITE_OK;
   87729 }
   87730 
   87731 
   87732 /*
   87733 ** Two versions of the official API.  Legacy and new use.  In the legacy
   87734 ** version, the original SQL text is not saved in the prepared statement
   87735 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   87736 ** sqlite3_step().  In the new version, the original SQL text is retained
   87737 ** and the statement is automatically recompiled if an schema change
   87738 ** occurs.
   87739 */
   87740 SQLITE_API int sqlite3_prepare(
   87741   sqlite3 *db,              /* Database handle. */
   87742   const char *zSql,         /* UTF-8 encoded SQL statement. */
   87743   int nBytes,               /* Length of zSql in bytes. */
   87744   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87745   const char **pzTail       /* OUT: End of parsed string */
   87746 ){
   87747   int rc;
   87748   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
   87749   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   87750   return rc;
   87751 }
   87752 SQLITE_API int sqlite3_prepare_v2(
   87753   sqlite3 *db,              /* Database handle. */
   87754   const char *zSql,         /* UTF-8 encoded SQL statement. */
   87755   int nBytes,               /* Length of zSql in bytes. */
   87756   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87757   const char **pzTail       /* OUT: End of parsed string */
   87758 ){
   87759   int rc;
   87760   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
   87761   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   87762   return rc;
   87763 }
   87764 
   87765 
   87766 #ifndef SQLITE_OMIT_UTF16
   87767 /*
   87768 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
   87769 */
   87770 static int sqlite3Prepare16(
   87771   sqlite3 *db,              /* Database handle. */
   87772   const void *zSql,         /* UTF-8 encoded SQL statement. */
   87773   int nBytes,               /* Length of zSql in bytes. */
   87774   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
   87775   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87776   const void **pzTail       /* OUT: End of parsed string */
   87777 ){
   87778   /* This function currently works by first transforming the UTF-16
   87779   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
   87780   ** tricky bit is figuring out the pointer to return in *pzTail.
   87781   */
   87782   char *zSql8;
   87783   const char *zTail8 = 0;
   87784   int rc = SQLITE_OK;
   87785 
   87786   assert( ppStmt );
   87787   *ppStmt = 0;
   87788   if( !sqlite3SafetyCheckOk(db) ){
   87789     return SQLITE_MISUSE_BKPT;
   87790   }
   87791   sqlite3_mutex_enter(db->mutex);
   87792   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
   87793   if( zSql8 ){
   87794     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
   87795   }
   87796 
   87797   if( zTail8 && pzTail ){
   87798     /* If sqlite3_prepare returns a tail pointer, we calculate the
   87799     ** equivalent pointer into the UTF-16 string by counting the unicode
   87800     ** characters between zSql8 and zTail8, and then returning a pointer
   87801     ** the same number of characters into the UTF-16 string.
   87802     */
   87803     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
   87804     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   87805   }
   87806   sqlite3DbFree(db, zSql8);
   87807   rc = sqlite3ApiExit(db, rc);
   87808   sqlite3_mutex_leave(db->mutex);
   87809   return rc;
   87810 }
   87811 
   87812 /*
   87813 ** Two versions of the official API.  Legacy and new use.  In the legacy
   87814 ** version, the original SQL text is not saved in the prepared statement
   87815 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
   87816 ** sqlite3_step().  In the new version, the original SQL text is retained
   87817 ** and the statement is automatically recompiled if an schema change
   87818 ** occurs.
   87819 */
   87820 SQLITE_API int sqlite3_prepare16(
   87821   sqlite3 *db,              /* Database handle. */
   87822   const void *zSql,         /* UTF-8 encoded SQL statement. */
   87823   int nBytes,               /* Length of zSql in bytes. */
   87824   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87825   const void **pzTail       /* OUT: End of parsed string */
   87826 ){
   87827   int rc;
   87828   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
   87829   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   87830   return rc;
   87831 }
   87832 SQLITE_API int sqlite3_prepare16_v2(
   87833   sqlite3 *db,              /* Database handle. */
   87834   const void *zSql,         /* UTF-8 encoded SQL statement. */
   87835   int nBytes,               /* Length of zSql in bytes. */
   87836   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
   87837   const void **pzTail       /* OUT: End of parsed string */
   87838 ){
   87839   int rc;
   87840   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
   87841   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
   87842   return rc;
   87843 }
   87844 
   87845 #endif /* SQLITE_OMIT_UTF16 */
   87846 
   87847 /************** End of prepare.c *********************************************/
   87848 /************** Begin file select.c ******************************************/
   87849 /*
   87850 ** 2001 September 15
   87851 **
   87852 ** The author disclaims copyright to this source code.  In place of
   87853 ** a legal notice, here is a blessing:
   87854 **
   87855 **    May you do good and not evil.
   87856 **    May you find forgiveness for yourself and forgive others.
   87857 **    May you share freely, never taking more than you give.
   87858 **
   87859 *************************************************************************
   87860 ** This file contains C code routines that are called by the parser
   87861 ** to handle SELECT statements in SQLite.
   87862 */
   87863 
   87864 
   87865 /*
   87866 ** Delete all the content of a Select structure but do not deallocate
   87867 ** the select structure itself.
   87868 */
   87869 static void clearSelect(sqlite3 *db, Select *p){
   87870   sqlite3ExprListDelete(db, p->pEList);
   87871   sqlite3SrcListDelete(db, p->pSrc);
   87872   sqlite3ExprDelete(db, p->pWhere);
   87873   sqlite3ExprListDelete(db, p->pGroupBy);
   87874   sqlite3ExprDelete(db, p->pHaving);
   87875   sqlite3ExprListDelete(db, p->pOrderBy);
   87876   sqlite3SelectDelete(db, p->pPrior);
   87877   sqlite3ExprDelete(db, p->pLimit);
   87878   sqlite3ExprDelete(db, p->pOffset);
   87879 }
   87880 
   87881 /*
   87882 ** Initialize a SelectDest structure.
   87883 */
   87884 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   87885   pDest->eDest = (u8)eDest;
   87886   pDest->iParm = iParm;
   87887   pDest->affinity = 0;
   87888   pDest->iMem = 0;
   87889   pDest->nMem = 0;
   87890 }
   87891 
   87892 
   87893 /*
   87894 ** Allocate a new Select structure and return a pointer to that
   87895 ** structure.
   87896 */
   87897 SQLITE_PRIVATE Select *sqlite3SelectNew(
   87898   Parse *pParse,        /* Parsing context */
   87899   ExprList *pEList,     /* which columns to include in the result */
   87900   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
   87901   Expr *pWhere,         /* the WHERE clause */
   87902   ExprList *pGroupBy,   /* the GROUP BY clause */
   87903   Expr *pHaving,        /* the HAVING clause */
   87904   ExprList *pOrderBy,   /* the ORDER BY clause */
   87905   int isDistinct,       /* true if the DISTINCT keyword is present */
   87906   Expr *pLimit,         /* LIMIT value.  NULL means not used */
   87907   Expr *pOffset         /* OFFSET value.  NULL means no offset */
   87908 ){
   87909   Select *pNew;
   87910   Select standin;
   87911   sqlite3 *db = pParse->db;
   87912   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
   87913   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
   87914   if( pNew==0 ){
   87915     pNew = &standin;
   87916     memset(pNew, 0, sizeof(*pNew));
   87917   }
   87918   if( pEList==0 ){
   87919     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
   87920   }
   87921   pNew->pEList = pEList;
   87922   pNew->pSrc = pSrc;
   87923   pNew->pWhere = pWhere;
   87924   pNew->pGroupBy = pGroupBy;
   87925   pNew->pHaving = pHaving;
   87926   pNew->pOrderBy = pOrderBy;
   87927   pNew->selFlags = isDistinct ? SF_Distinct : 0;
   87928   pNew->op = TK_SELECT;
   87929   pNew->pLimit = pLimit;
   87930   pNew->pOffset = pOffset;
   87931   assert( pOffset==0 || pLimit!=0 );
   87932   pNew->addrOpenEphm[0] = -1;
   87933   pNew->addrOpenEphm[1] = -1;
   87934   pNew->addrOpenEphm[2] = -1;
   87935   if( db->mallocFailed ) {
   87936     clearSelect(db, pNew);
   87937     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
   87938     pNew = 0;
   87939   }
   87940   return pNew;
   87941 }
   87942 
   87943 /*
   87944 ** Delete the given Select structure and all of its substructures.
   87945 */
   87946 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
   87947   if( p ){
   87948     clearSelect(db, p);
   87949     sqlite3DbFree(db, p);
   87950   }
   87951 }
   87952 
   87953 /*
   87954 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   87955 ** type of join.  Return an integer constant that expresses that type
   87956 ** in terms of the following bit values:
   87957 **
   87958 **     JT_INNER
   87959 **     JT_CROSS
   87960 **     JT_OUTER
   87961 **     JT_NATURAL
   87962 **     JT_LEFT
   87963 **     JT_RIGHT
   87964 **
   87965 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   87966 **
   87967 ** If an illegal or unsupported join type is seen, then still return
   87968 ** a join type, but put an error in the pParse structure.
   87969 */
   87970 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   87971   int jointype = 0;
   87972   Token *apAll[3];
   87973   Token *p;
   87974                              /*   0123456789 123456789 123456789 123 */
   87975   static const char zKeyText[] = "naturaleftouterightfullinnercross";
   87976   static const struct {
   87977     u8 i;        /* Beginning of keyword text in zKeyText[] */
   87978     u8 nChar;    /* Length of the keyword in characters */
   87979     u8 code;     /* Join type mask */
   87980   } aKeyword[] = {
   87981     /* natural */ { 0,  7, JT_NATURAL                },
   87982     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
   87983     /* outer   */ { 10, 5, JT_OUTER                  },
   87984     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
   87985     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
   87986     /* inner   */ { 23, 5, JT_INNER                  },
   87987     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
   87988   };
   87989   int i, j;
   87990   apAll[0] = pA;
   87991   apAll[1] = pB;
   87992   apAll[2] = pC;
   87993   for(i=0; i<3 && apAll[i]; i++){
   87994     p = apAll[i];
   87995     for(j=0; j<ArraySize(aKeyword); j++){
   87996       if( p->n==aKeyword[j].nChar
   87997           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
   87998         jointype |= aKeyword[j].code;
   87999         break;
   88000       }
   88001     }
   88002     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
   88003     if( j>=ArraySize(aKeyword) ){
   88004       jointype |= JT_ERROR;
   88005       break;
   88006     }
   88007   }
   88008   if(
   88009      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   88010      (jointype & JT_ERROR)!=0
   88011   ){
   88012     const char *zSp = " ";
   88013     assert( pB!=0 );
   88014     if( pC==0 ){ zSp++; }
   88015     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   88016        "%T %T%s%T", pA, pB, zSp, pC);
   88017     jointype = JT_INNER;
   88018   }else if( (jointype & JT_OUTER)!=0
   88019          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
   88020     sqlite3ErrorMsg(pParse,
   88021       "RIGHT and FULL OUTER JOINs are not currently supported");
   88022     jointype = JT_INNER;
   88023   }
   88024   return jointype;
   88025 }
   88026 
   88027 /*
   88028 ** Return the index of a column in a table.  Return -1 if the column
   88029 ** is not contained in the table.
   88030 */
   88031 static int columnIndex(Table *pTab, const char *zCol){
   88032   int i;
   88033   for(i=0; i<pTab->nCol; i++){
   88034     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   88035   }
   88036   return -1;
   88037 }
   88038 
   88039 /*
   88040 ** Search the first N tables in pSrc, from left to right, looking for a
   88041 ** table that has a column named zCol.
   88042 **
   88043 ** When found, set *piTab and *piCol to the table index and column index
   88044 ** of the matching column and return TRUE.
   88045 **
   88046 ** If not found, return FALSE.
   88047 */
   88048 static int tableAndColumnIndex(
   88049   SrcList *pSrc,       /* Array of tables to search */
   88050   int N,               /* Number of tables in pSrc->a[] to search */
   88051   const char *zCol,    /* Name of the column we are looking for */
   88052   int *piTab,          /* Write index of pSrc->a[] here */
   88053   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
   88054 ){
   88055   int i;               /* For looping over tables in pSrc */
   88056   int iCol;            /* Index of column matching zCol */
   88057 
   88058   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   88059   for(i=0; i<N; i++){
   88060     iCol = columnIndex(pSrc->a[i].pTab, zCol);
   88061     if( iCol>=0 ){
   88062       if( piTab ){
   88063         *piTab = i;
   88064         *piCol = iCol;
   88065       }
   88066       return 1;
   88067     }
   88068   }
   88069   return 0;
   88070 }
   88071 
   88072 /*
   88073 ** This function is used to add terms implied by JOIN syntax to the
   88074 ** WHERE clause expression of a SELECT statement. The new term, which
   88075 ** is ANDed with the existing WHERE clause, is of the form:
   88076 **
   88077 **    (tab1.col1 = tab2.col2)
   88078 **
   88079 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
   88080 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
   88081 ** column iColRight of tab2.
   88082 */
   88083 static void addWhereTerm(
   88084   Parse *pParse,                  /* Parsing context */
   88085   SrcList *pSrc,                  /* List of tables in FROM clause */
   88086   int iLeft,                      /* Index of first table to join in pSrc */
   88087   int iColLeft,                   /* Index of column in first table */
   88088   int iRight,                     /* Index of second table in pSrc */
   88089   int iColRight,                  /* Index of column in second table */
   88090   int isOuterJoin,                /* True if this is an OUTER join */
   88091   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
   88092 ){
   88093   sqlite3 *db = pParse->db;
   88094   Expr *pE1;
   88095   Expr *pE2;
   88096   Expr *pEq;
   88097 
   88098   assert( iLeft<iRight );
   88099   assert( pSrc->nSrc>iRight );
   88100   assert( pSrc->a[iLeft].pTab );
   88101   assert( pSrc->a[iRight].pTab );
   88102 
   88103   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
   88104   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
   88105 
   88106   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
   88107   if( pEq && isOuterJoin ){
   88108     ExprSetProperty(pEq, EP_FromJoin);
   88109     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
   88110     ExprSetIrreducible(pEq);
   88111     pEq->iRightJoinTable = (i16)pE2->iTable;
   88112   }
   88113   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
   88114 }
   88115 
   88116 /*
   88117 ** Set the EP_FromJoin property on all terms of the given expression.
   88118 ** And set the Expr.iRightJoinTable to iTable for every term in the
   88119 ** expression.
   88120 **
   88121 ** The EP_FromJoin property is used on terms of an expression to tell
   88122 ** the LEFT OUTER JOIN processing logic that this term is part of the
   88123 ** join restriction specified in the ON or USING clause and not a part
   88124 ** of the more general WHERE clause.  These terms are moved over to the
   88125 ** WHERE clause during join processing but we need to remember that they
   88126 ** originated in the ON or USING clause.
   88127 **
   88128 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
   88129 ** expression depends on table iRightJoinTable even if that table is not
   88130 ** explicitly mentioned in the expression.  That information is needed
   88131 ** for cases like this:
   88132 **
   88133 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   88134 **
   88135 ** The where clause needs to defer the handling of the t1.x=5
   88136 ** term until after the t2 loop of the join.  In that way, a
   88137 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   88138 ** defer the handling of t1.x=5, it will be processed immediately
   88139 ** after the t1 loop and rows with t1.x!=5 will never appear in
   88140 ** the output, which is incorrect.
   88141 */
   88142 static void setJoinExpr(Expr *p, int iTable){
   88143   while( p ){
   88144     ExprSetProperty(p, EP_FromJoin);
   88145     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
   88146     ExprSetIrreducible(p);
   88147     p->iRightJoinTable = (i16)iTable;
   88148     setJoinExpr(p->pLeft, iTable);
   88149     p = p->pRight;
   88150   }
   88151 }
   88152 
   88153 /*
   88154 ** This routine processes the join information for a SELECT statement.
   88155 ** ON and USING clauses are converted into extra terms of the WHERE clause.
   88156 ** NATURAL joins also create extra WHERE clause terms.
   88157 **
   88158 ** The terms of a FROM clause are contained in the Select.pSrc structure.
   88159 ** The left most table is the first entry in Select.pSrc.  The right-most
   88160 ** table is the last entry.  The join operator is held in the entry to
   88161 ** the left.  Thus entry 0 contains the join operator for the join between
   88162 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
   88163 ** also attached to the left entry.
   88164 **
   88165 ** This routine returns the number of errors encountered.
   88166 */
   88167 static int sqliteProcessJoin(Parse *pParse, Select *p){
   88168   SrcList *pSrc;                  /* All tables in the FROM clause */
   88169   int i, j;                       /* Loop counters */
   88170   struct SrcList_item *pLeft;     /* Left table being joined */
   88171   struct SrcList_item *pRight;    /* Right table being joined */
   88172 
   88173   pSrc = p->pSrc;
   88174   pLeft = &pSrc->a[0];
   88175   pRight = &pLeft[1];
   88176   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   88177     Table *pLeftTab = pLeft->pTab;
   88178     Table *pRightTab = pRight->pTab;
   88179     int isOuter;
   88180 
   88181     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
   88182     isOuter = (pRight->jointype & JT_OUTER)!=0;
   88183 
   88184     /* When the NATURAL keyword is present, add WHERE clause terms for
   88185     ** every column that the two tables have in common.
   88186     */
   88187     if( pRight->jointype & JT_NATURAL ){
   88188       if( pRight->pOn || pRight->pUsing ){
   88189         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   88190            "an ON or USING clause", 0);
   88191         return 1;
   88192       }
   88193       for(j=0; j<pRightTab->nCol; j++){
   88194         char *zName;   /* Name of column in the right table */
   88195         int iLeft;     /* Matching left table */
   88196         int iLeftCol;  /* Matching column in the left table */
   88197 
   88198         zName = pRightTab->aCol[j].zName;
   88199         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
   88200           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
   88201                        isOuter, &p->pWhere);
   88202         }
   88203       }
   88204     }
   88205 
   88206     /* Disallow both ON and USING clauses in the same join
   88207     */
   88208     if( pRight->pOn && pRight->pUsing ){
   88209       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   88210         "clauses in the same join");
   88211       return 1;
   88212     }
   88213 
   88214     /* Add the ON clause to the end of the WHERE clause, connected by
   88215     ** an AND operator.
   88216     */
   88217     if( pRight->pOn ){
   88218       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   88219       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   88220       pRight->pOn = 0;
   88221     }
   88222 
   88223     /* Create extra terms on the WHERE clause for each column named
   88224     ** in the USING clause.  Example: If the two tables to be joined are
   88225     ** A and B and the USING clause names X, Y, and Z, then add this
   88226     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   88227     ** Report an error if any column mentioned in the USING clause is
   88228     ** not contained in both tables to be joined.
   88229     */
   88230     if( pRight->pUsing ){
   88231       IdList *pList = pRight->pUsing;
   88232       for(j=0; j<pList->nId; j++){
   88233         char *zName;     /* Name of the term in the USING clause */
   88234         int iLeft;       /* Table on the left with matching column name */
   88235         int iLeftCol;    /* Column number of matching column on the left */
   88236         int iRightCol;   /* Column number of matching column on the right */
   88237 
   88238         zName = pList->a[j].zName;
   88239         iRightCol = columnIndex(pRightTab, zName);
   88240         if( iRightCol<0
   88241          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
   88242         ){
   88243           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   88244             "not present in both tables", zName);
   88245           return 1;
   88246         }
   88247         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
   88248                      isOuter, &p->pWhere);
   88249       }
   88250     }
   88251   }
   88252   return 0;
   88253 }
   88254 
   88255 /*
   88256 ** Insert code into "v" that will push the record on the top of the
   88257 ** stack into the sorter.
   88258 */
   88259 static void pushOntoSorter(
   88260   Parse *pParse,         /* Parser context */
   88261   ExprList *pOrderBy,    /* The ORDER BY clause */
   88262   Select *pSelect,       /* The whole SELECT statement */
   88263   int regData            /* Register holding data to be sorted */
   88264 ){
   88265   Vdbe *v = pParse->pVdbe;
   88266   int nExpr = pOrderBy->nExpr;
   88267   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
   88268   int regRecord = sqlite3GetTempReg(pParse);
   88269   sqlite3ExprCacheClear(pParse);
   88270   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
   88271   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
   88272   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   88273   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
   88274   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
   88275   sqlite3ReleaseTempReg(pParse, regRecord);
   88276   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
   88277   if( pSelect->iLimit ){
   88278     int addr1, addr2;
   88279     int iLimit;
   88280     if( pSelect->iOffset ){
   88281       iLimit = pSelect->iOffset+1;
   88282     }else{
   88283       iLimit = pSelect->iLimit;
   88284     }
   88285     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
   88286     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   88287     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   88288     sqlite3VdbeJumpHere(v, addr1);
   88289     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   88290     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   88291     sqlite3VdbeJumpHere(v, addr2);
   88292   }
   88293 }
   88294 
   88295 /*
   88296 ** Add code to implement the OFFSET
   88297 */
   88298 static void codeOffset(
   88299   Vdbe *v,          /* Generate code into this VM */
   88300   Select *p,        /* The SELECT statement being coded */
   88301   int iContinue     /* Jump here to skip the current record */
   88302 ){
   88303   if( p->iOffset && iContinue!=0 ){
   88304     int addr;
   88305     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
   88306     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
   88307     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   88308     VdbeComment((v, "skip OFFSET records"));
   88309     sqlite3VdbeJumpHere(v, addr);
   88310   }
   88311 }
   88312 
   88313 /*
   88314 ** Add code that will check to make sure the N registers starting at iMem
   88315 ** form a distinct entry.  iTab is a sorting index that holds previously
   88316 ** seen combinations of the N values.  A new entry is made in iTab
   88317 ** if the current N values are new.
   88318 **
   88319 ** A jump to addrRepeat is made and the N+1 values are popped from the
   88320 ** stack if the top N elements are not distinct.
   88321 */
   88322 static void codeDistinct(
   88323   Parse *pParse,     /* Parsing and code generating context */
   88324   int iTab,          /* A sorting index used to test for distinctness */
   88325   int addrRepeat,    /* Jump to here if not distinct */
   88326   int N,             /* Number of elements */
   88327   int iMem           /* First element */
   88328 ){
   88329   Vdbe *v;
   88330   int r1;
   88331 
   88332   v = pParse->pVdbe;
   88333   r1 = sqlite3GetTempReg(pParse);
   88334   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
   88335   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   88336   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   88337   sqlite3ReleaseTempReg(pParse, r1);
   88338 }
   88339 
   88340 #ifndef SQLITE_OMIT_SUBQUERY
   88341 /*
   88342 ** Generate an error message when a SELECT is used within a subexpression
   88343 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   88344 ** column.  We do this in a subroutine because the error used to occur
   88345 ** in multiple places.  (The error only occurs in one place now, but we
   88346 ** retain the subroutine to minimize code disruption.)
   88347 */
   88348 static int checkForMultiColumnSelectError(
   88349   Parse *pParse,       /* Parse context. */
   88350   SelectDest *pDest,   /* Destination of SELECT results */
   88351   int nExpr            /* Number of result columns returned by SELECT */
   88352 ){
   88353   int eDest = pDest->eDest;
   88354   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   88355     sqlite3ErrorMsg(pParse, "only a single result allowed for "
   88356        "a SELECT that is part of an expression");
   88357     return 1;
   88358   }else{
   88359     return 0;
   88360   }
   88361 }
   88362 #endif
   88363 
   88364 /*
   88365 ** This routine generates the code for the inside of the inner loop
   88366 ** of a SELECT.
   88367 **
   88368 ** If srcTab and nColumn are both zero, then the pEList expressions
   88369 ** are evaluated in order to get the data for this row.  If nColumn>0
   88370 ** then data is pulled from srcTab and pEList is used only to get the
   88371 ** datatypes for each column.
   88372 */
   88373 static void selectInnerLoop(
   88374   Parse *pParse,          /* The parser context */
   88375   Select *p,              /* The complete select statement being coded */
   88376   ExprList *pEList,       /* List of values being extracted */
   88377   int srcTab,             /* Pull data from this table */
   88378   int nColumn,            /* Number of columns in the source table */
   88379   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   88380   int distinct,           /* If >=0, make sure results are distinct */
   88381   SelectDest *pDest,      /* How to dispose of the results */
   88382   int iContinue,          /* Jump here to continue with next row */
   88383   int iBreak              /* Jump here to break out of the inner loop */
   88384 ){
   88385   Vdbe *v = pParse->pVdbe;
   88386   int i;
   88387   int hasDistinct;        /* True if the DISTINCT keyword is present */
   88388   int regResult;              /* Start of memory holding result set */
   88389   int eDest = pDest->eDest;   /* How to dispose of results */
   88390   int iParm = pDest->iParm;   /* First argument to disposal method */
   88391   int nResultCol;             /* Number of result columns */
   88392 
   88393   assert( v );
   88394   if( NEVER(v==0) ) return;
   88395   assert( pEList!=0 );
   88396   hasDistinct = distinct>=0;
   88397   if( pOrderBy==0 && !hasDistinct ){
   88398     codeOffset(v, p, iContinue);
   88399   }
   88400 
   88401   /* Pull the requested columns.
   88402   */
   88403   if( nColumn>0 ){
   88404     nResultCol = nColumn;
   88405   }else{
   88406     nResultCol = pEList->nExpr;
   88407   }
   88408   if( pDest->iMem==0 ){
   88409     pDest->iMem = pParse->nMem+1;
   88410     pDest->nMem = nResultCol;
   88411     pParse->nMem += nResultCol;
   88412   }else{
   88413     assert( pDest->nMem==nResultCol );
   88414   }
   88415   regResult = pDest->iMem;
   88416   if( nColumn>0 ){
   88417     for(i=0; i<nColumn; i++){
   88418       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   88419     }
   88420   }else if( eDest!=SRT_Exists ){
   88421     /* If the destination is an EXISTS(...) expression, the actual
   88422     ** values returned by the SELECT are not required.
   88423     */
   88424     sqlite3ExprCacheClear(pParse);
   88425     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
   88426   }
   88427   nColumn = nResultCol;
   88428 
   88429   /* If the DISTINCT keyword was present on the SELECT statement
   88430   ** and this row has been seen before, then do not make this row
   88431   ** part of the result.
   88432   */
   88433   if( hasDistinct ){
   88434     assert( pEList!=0 );
   88435     assert( pEList->nExpr==nColumn );
   88436     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
   88437     if( pOrderBy==0 ){
   88438       codeOffset(v, p, iContinue);
   88439     }
   88440   }
   88441 
   88442   switch( eDest ){
   88443     /* In this mode, write each query result to the key of the temporary
   88444     ** table iParm.
   88445     */
   88446 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   88447     case SRT_Union: {
   88448       int r1;
   88449       r1 = sqlite3GetTempReg(pParse);
   88450       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   88451       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   88452       sqlite3ReleaseTempReg(pParse, r1);
   88453       break;
   88454     }
   88455 
   88456     /* Construct a record from the query result, but instead of
   88457     ** saving that record, use it as a key to delete elements from
   88458     ** the temporary table iParm.
   88459     */
   88460     case SRT_Except: {
   88461       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
   88462       break;
   88463     }
   88464 #endif
   88465 
   88466     /* Store the result as data using a unique key.
   88467     */
   88468     case SRT_Table:
   88469     case SRT_EphemTab: {
   88470       int r1 = sqlite3GetTempReg(pParse);
   88471       testcase( eDest==SRT_Table );
   88472       testcase( eDest==SRT_EphemTab );
   88473       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   88474       if( pOrderBy ){
   88475         pushOntoSorter(pParse, pOrderBy, p, r1);
   88476       }else{
   88477         int r2 = sqlite3GetTempReg(pParse);
   88478         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   88479         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   88480         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   88481         sqlite3ReleaseTempReg(pParse, r2);
   88482       }
   88483       sqlite3ReleaseTempReg(pParse, r1);
   88484       break;
   88485     }
   88486 
   88487 #ifndef SQLITE_OMIT_SUBQUERY
   88488     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   88489     ** then there should be a single item on the stack.  Write this
   88490     ** item into the set table with bogus data.
   88491     */
   88492     case SRT_Set: {
   88493       assert( nColumn==1 );
   88494       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
   88495       if( pOrderBy ){
   88496         /* At first glance you would think we could optimize out the
   88497         ** ORDER BY in this case since the order of entries in the set
   88498         ** does not matter.  But there might be a LIMIT clause, in which
   88499         ** case the order does matter */
   88500         pushOntoSorter(pParse, pOrderBy, p, regResult);
   88501       }else{
   88502         int r1 = sqlite3GetTempReg(pParse);
   88503         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
   88504         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   88505         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   88506         sqlite3ReleaseTempReg(pParse, r1);
   88507       }
   88508       break;
   88509     }
   88510 
   88511     /* If any row exist in the result set, record that fact and abort.
   88512     */
   88513     case SRT_Exists: {
   88514       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   88515       /* The LIMIT clause will terminate the loop for us */
   88516       break;
   88517     }
   88518 
   88519     /* If this is a scalar select that is part of an expression, then
   88520     ** store the results in the appropriate memory cell and break out
   88521     ** of the scan loop.
   88522     */
   88523     case SRT_Mem: {
   88524       assert( nColumn==1 );
   88525       if( pOrderBy ){
   88526         pushOntoSorter(pParse, pOrderBy, p, regResult);
   88527       }else{
   88528         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   88529         /* The LIMIT clause will jump out of the loop for us */
   88530       }
   88531       break;
   88532     }
   88533 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   88534 
   88535     /* Send the data to the callback function or to a subroutine.  In the
   88536     ** case of a subroutine, the subroutine itself is responsible for
   88537     ** popping the data from the stack.
   88538     */
   88539     case SRT_Coroutine:
   88540     case SRT_Output: {
   88541       testcase( eDest==SRT_Coroutine );
   88542       testcase( eDest==SRT_Output );
   88543       if( pOrderBy ){
   88544         int r1 = sqlite3GetTempReg(pParse);
   88545         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   88546         pushOntoSorter(pParse, pOrderBy, p, r1);
   88547         sqlite3ReleaseTempReg(pParse, r1);
   88548       }else if( eDest==SRT_Coroutine ){
   88549         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   88550       }else{
   88551         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
   88552         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
   88553       }
   88554       break;
   88555     }
   88556 
   88557 #if !defined(SQLITE_OMIT_TRIGGER)
   88558     /* Discard the results.  This is used for SELECT statements inside
   88559     ** the body of a TRIGGER.  The purpose of such selects is to call
   88560     ** user-defined functions that have side effects.  We do not care
   88561     ** about the actual results of the select.
   88562     */
   88563     default: {
   88564       assert( eDest==SRT_Discard );
   88565       break;
   88566     }
   88567 #endif
   88568   }
   88569 
   88570   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   88571   ** there is a sorter, in which case the sorter has already limited
   88572   ** the output for us.
   88573   */
   88574   if( pOrderBy==0 && p->iLimit ){
   88575     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   88576   }
   88577 }
   88578 
   88579 /*
   88580 ** Given an expression list, generate a KeyInfo structure that records
   88581 ** the collating sequence for each expression in that expression list.
   88582 **
   88583 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   88584 ** KeyInfo structure is appropriate for initializing a virtual index to
   88585 ** implement that clause.  If the ExprList is the result set of a SELECT
   88586 ** then the KeyInfo structure is appropriate for initializing a virtual
   88587 ** index to implement a DISTINCT test.
   88588 **
   88589 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   88590 ** function is responsible for seeing that this structure is eventually
   88591 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   88592 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   88593 */
   88594 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   88595   sqlite3 *db = pParse->db;
   88596   int nExpr;
   88597   KeyInfo *pInfo;
   88598   struct ExprList_item *pItem;
   88599   int i;
   88600 
   88601   nExpr = pList->nExpr;
   88602   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   88603   if( pInfo ){
   88604     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   88605     pInfo->nField = (u16)nExpr;
   88606     pInfo->enc = ENC(db);
   88607     pInfo->db = db;
   88608     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   88609       CollSeq *pColl;
   88610       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   88611       if( !pColl ){
   88612         pColl = db->pDfltColl;
   88613       }
   88614       pInfo->aColl[i] = pColl;
   88615       pInfo->aSortOrder[i] = pItem->sortOrder;
   88616     }
   88617   }
   88618   return pInfo;
   88619 }
   88620 
   88621 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   88622 /*
   88623 ** Name of the connection operator, used for error messages.
   88624 */
   88625 static const char *selectOpName(int id){
   88626   char *z;
   88627   switch( id ){
   88628     case TK_ALL:       z = "UNION ALL";   break;
   88629     case TK_INTERSECT: z = "INTERSECT";   break;
   88630     case TK_EXCEPT:    z = "EXCEPT";      break;
   88631     default:           z = "UNION";       break;
   88632   }
   88633   return z;
   88634 }
   88635 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   88636 
   88637 #ifndef SQLITE_OMIT_EXPLAIN
   88638 /*
   88639 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   88640 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   88641 ** where the caption is of the form:
   88642 **
   88643 **   "USE TEMP B-TREE FOR xxx"
   88644 **
   88645 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
   88646 ** is determined by the zUsage argument.
   88647 */
   88648 static void explainTempTable(Parse *pParse, const char *zUsage){
   88649   if( pParse->explain==2 ){
   88650     Vdbe *v = pParse->pVdbe;
   88651     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
   88652     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   88653   }
   88654 }
   88655 
   88656 /*
   88657 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
   88658 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
   88659 ** where the caption is of one of the two forms:
   88660 **
   88661 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
   88662 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
   88663 **
   88664 ** where iSub1 and iSub2 are the integers passed as the corresponding
   88665 ** function parameters, and op is the text representation of the parameter
   88666 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
   88667 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
   88668 ** false, or the second form if it is true.
   88669 */
   88670 static void explainComposite(
   88671   Parse *pParse,                  /* Parse context */
   88672   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
   88673   int iSub1,                      /* Subquery id 1 */
   88674   int iSub2,                      /* Subquery id 2 */
   88675   int bUseTmp                     /* True if a temp table was used */
   88676 ){
   88677   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
   88678   if( pParse->explain==2 ){
   88679     Vdbe *v = pParse->pVdbe;
   88680     char *zMsg = sqlite3MPrintf(
   88681         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
   88682         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
   88683     );
   88684     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
   88685   }
   88686 }
   88687 
   88688 /*
   88689 ** Assign expression b to lvalue a. A second, no-op, version of this macro
   88690 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
   88691 ** in sqlite3Select() to assign values to structure member variables that
   88692 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
   88693 ** code with #ifndef directives.
   88694 */
   88695 # define explainSetInteger(a, b) a = b
   88696 
   88697 #else
   88698 /* No-op versions of the explainXXX() functions and macros. */
   88699 # define explainTempTable(y,z)
   88700 # define explainComposite(v,w,x,y,z)
   88701 # define explainSetInteger(y,z)
   88702 #endif
   88703 
   88704 /*
   88705 ** If the inner loop was generated using a non-null pOrderBy argument,
   88706 ** then the results were placed in a sorter.  After the loop is terminated
   88707 ** we need to run the sorter and output the results.  The following
   88708 ** routine generates the code needed to do that.
   88709 */
   88710 static void generateSortTail(
   88711   Parse *pParse,    /* Parsing context */
   88712   Select *p,        /* The SELECT statement */
   88713   Vdbe *v,          /* Generate code into this VDBE */
   88714   int nColumn,      /* Number of columns of data */
   88715   SelectDest *pDest /* Write the sorted results here */
   88716 ){
   88717   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
   88718   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
   88719   int addr;
   88720   int iTab;
   88721   int pseudoTab = 0;
   88722   ExprList *pOrderBy = p->pOrderBy;
   88723 
   88724   int eDest = pDest->eDest;
   88725   int iParm = pDest->iParm;
   88726 
   88727   int regRow;
   88728   int regRowid;
   88729 
   88730   iTab = pOrderBy->iECursor;
   88731   regRow = sqlite3GetTempReg(pParse);
   88732   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   88733     pseudoTab = pParse->nTab++;
   88734     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
   88735     regRowid = 0;
   88736   }else{
   88737     regRowid = sqlite3GetTempReg(pParse);
   88738   }
   88739   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
   88740   codeOffset(v, p, addrContinue);
   88741   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
   88742   switch( eDest ){
   88743     case SRT_Table:
   88744     case SRT_EphemTab: {
   88745       testcase( eDest==SRT_Table );
   88746       testcase( eDest==SRT_EphemTab );
   88747       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   88748       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   88749       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   88750       break;
   88751     }
   88752 #ifndef SQLITE_OMIT_SUBQUERY
   88753     case SRT_Set: {
   88754       assert( nColumn==1 );
   88755       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
   88756       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   88757       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   88758       break;
   88759     }
   88760     case SRT_Mem: {
   88761       assert( nColumn==1 );
   88762       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   88763       /* The LIMIT clause will terminate the loop for us */
   88764       break;
   88765     }
   88766 #endif
   88767     default: {
   88768       int i;
   88769       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
   88770       testcase( eDest==SRT_Output );
   88771       testcase( eDest==SRT_Coroutine );
   88772       for(i=0; i<nColumn; i++){
   88773         assert( regRow!=pDest->iMem+i );
   88774         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
   88775         if( i==0 ){
   88776           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
   88777         }
   88778       }
   88779       if( eDest==SRT_Output ){
   88780         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
   88781         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
   88782       }else{
   88783         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   88784       }
   88785       break;
   88786     }
   88787   }
   88788   sqlite3ReleaseTempReg(pParse, regRow);
   88789   sqlite3ReleaseTempReg(pParse, regRowid);
   88790 
   88791   /* The bottom of the loop
   88792   */
   88793   sqlite3VdbeResolveLabel(v, addrContinue);
   88794   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
   88795   sqlite3VdbeResolveLabel(v, addrBreak);
   88796   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   88797     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
   88798   }
   88799 }
   88800 
   88801 /*
   88802 ** Return a pointer to a string containing the 'declaration type' of the
   88803 ** expression pExpr. The string may be treated as static by the caller.
   88804 **
   88805 ** The declaration type is the exact datatype definition extracted from the
   88806 ** original CREATE TABLE statement if the expression is a column. The
   88807 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
   88808 ** is considered a column can be complex in the presence of subqueries. The
   88809 ** result-set expression in all of the following SELECT statements is
   88810 ** considered a column by this function.
   88811 **
   88812 **   SELECT col FROM tbl;
   88813 **   SELECT (SELECT col FROM tbl;
   88814 **   SELECT (SELECT col FROM tbl);
   88815 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
   88816 **
   88817 ** The declaration type for any expression other than a column is NULL.
   88818 */
   88819 static const char *columnType(
   88820   NameContext *pNC,
   88821   Expr *pExpr,
   88822   const char **pzOriginDb,
   88823   const char **pzOriginTab,
   88824   const char **pzOriginCol
   88825 ){
   88826   char const *zType = 0;
   88827   char const *zOriginDb = 0;
   88828   char const *zOriginTab = 0;
   88829   char const *zOriginCol = 0;
   88830   int j;
   88831   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
   88832 
   88833   switch( pExpr->op ){
   88834     case TK_AGG_COLUMN:
   88835     case TK_COLUMN: {
   88836       /* The expression is a column. Locate the table the column is being
   88837       ** extracted from in NameContext.pSrcList. This table may be real
   88838       ** database table or a subquery.
   88839       */
   88840       Table *pTab = 0;            /* Table structure column is extracted from */
   88841       Select *pS = 0;             /* Select the column is extracted from */
   88842       int iCol = pExpr->iColumn;  /* Index of column in pTab */
   88843       testcase( pExpr->op==TK_AGG_COLUMN );
   88844       testcase( pExpr->op==TK_COLUMN );
   88845       while( pNC && !pTab ){
   88846         SrcList *pTabList = pNC->pSrcList;
   88847         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   88848         if( j<pTabList->nSrc ){
   88849           pTab = pTabList->a[j].pTab;
   88850           pS = pTabList->a[j].pSelect;
   88851         }else{
   88852           pNC = pNC->pNext;
   88853         }
   88854       }
   88855 
   88856       if( pTab==0 ){
   88857         /* At one time, code such as "SELECT new.x" within a trigger would
   88858         ** cause this condition to run.  Since then, we have restructured how
   88859         ** trigger code is generated and so this condition is no longer
   88860         ** possible. However, it can still be true for statements like
   88861         ** the following:
   88862         **
   88863         **   CREATE TABLE t1(col INTEGER);
   88864         **   SELECT (SELECT t1.col) FROM FROM t1;
   88865         **
   88866         ** when columnType() is called on the expression "t1.col" in the
   88867         ** sub-select. In this case, set the column type to NULL, even
   88868         ** though it should really be "INTEGER".
   88869         **
   88870         ** This is not a problem, as the column type of "t1.col" is never
   88871         ** used. When columnType() is called on the expression
   88872         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
   88873         ** branch below.  */
   88874         break;
   88875       }
   88876 
   88877       assert( pTab && pExpr->pTab==pTab );
   88878       if( pS ){
   88879         /* The "table" is actually a sub-select or a view in the FROM clause
   88880         ** of the SELECT statement. Return the declaration type and origin
   88881         ** data for the result-set column of the sub-select.
   88882         */
   88883         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
   88884           /* If iCol is less than zero, then the expression requests the
   88885           ** rowid of the sub-select or view. This expression is legal (see
   88886           ** test case misc2.2.2) - it always evaluates to NULL.
   88887           */
   88888           NameContext sNC;
   88889           Expr *p = pS->pEList->a[iCol].pExpr;
   88890           sNC.pSrcList = pS->pSrc;
   88891           sNC.pNext = pNC;
   88892           sNC.pParse = pNC->pParse;
   88893           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   88894         }
   88895       }else if( ALWAYS(pTab->pSchema) ){
   88896         /* A real table */
   88897         assert( !pS );
   88898         if( iCol<0 ) iCol = pTab->iPKey;
   88899         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   88900         if( iCol<0 ){
   88901           zType = "INTEGER";
   88902           zOriginCol = "rowid";
   88903         }else{
   88904           zType = pTab->aCol[iCol].zType;
   88905           zOriginCol = pTab->aCol[iCol].zName;
   88906         }
   88907         zOriginTab = pTab->zName;
   88908         if( pNC->pParse ){
   88909           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   88910           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   88911         }
   88912       }
   88913       break;
   88914     }
   88915 #ifndef SQLITE_OMIT_SUBQUERY
   88916     case TK_SELECT: {
   88917       /* The expression is a sub-select. Return the declaration type and
   88918       ** origin info for the single column in the result set of the SELECT
   88919       ** statement.
   88920       */
   88921       NameContext sNC;
   88922       Select *pS = pExpr->x.pSelect;
   88923       Expr *p = pS->pEList->a[0].pExpr;
   88924       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
   88925       sNC.pSrcList = pS->pSrc;
   88926       sNC.pNext = pNC;
   88927       sNC.pParse = pNC->pParse;
   88928       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
   88929       break;
   88930     }
   88931 #endif
   88932   }
   88933 
   88934   if( pzOriginDb ){
   88935     assert( pzOriginTab && pzOriginCol );
   88936     *pzOriginDb = zOriginDb;
   88937     *pzOriginTab = zOriginTab;
   88938     *pzOriginCol = zOriginCol;
   88939   }
   88940   return zType;
   88941 }
   88942 
   88943 /*
   88944 ** Generate code that will tell the VDBE the declaration types of columns
   88945 ** in the result set.
   88946 */
   88947 static void generateColumnTypes(
   88948   Parse *pParse,      /* Parser context */
   88949   SrcList *pTabList,  /* List of tables */
   88950   ExprList *pEList    /* Expressions defining the result set */
   88951 ){
   88952 #ifndef SQLITE_OMIT_DECLTYPE
   88953   Vdbe *v = pParse->pVdbe;
   88954   int i;
   88955   NameContext sNC;
   88956   sNC.pSrcList = pTabList;
   88957   sNC.pParse = pParse;
   88958   for(i=0; i<pEList->nExpr; i++){
   88959     Expr *p = pEList->a[i].pExpr;
   88960     const char *zType;
   88961 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   88962     const char *zOrigDb = 0;
   88963     const char *zOrigTab = 0;
   88964     const char *zOrigCol = 0;
   88965     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   88966 
   88967     /* The vdbe must make its own copy of the column-type and other
   88968     ** column specific strings, in case the schema is reset before this
   88969     ** virtual machine is deleted.
   88970     */
   88971     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
   88972     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
   88973     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
   88974 #else
   88975     zType = columnType(&sNC, p, 0, 0, 0);
   88976 #endif
   88977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
   88978   }
   88979 #endif /* SQLITE_OMIT_DECLTYPE */
   88980 }
   88981 
   88982 /*
   88983 ** Generate code that will tell the VDBE the names of columns
   88984 ** in the result set.  This information is used to provide the
   88985 ** azCol[] values in the callback.
   88986 */
   88987 static void generateColumnNames(
   88988   Parse *pParse,      /* Parser context */
   88989   SrcList *pTabList,  /* List of tables */
   88990   ExprList *pEList    /* Expressions defining the result set */
   88991 ){
   88992   Vdbe *v = pParse->pVdbe;
   88993   int i, j;
   88994   sqlite3 *db = pParse->db;
   88995   int fullNames, shortNames;
   88996 
   88997 #ifndef SQLITE_OMIT_EXPLAIN
   88998   /* If this is an EXPLAIN, skip this step */
   88999   if( pParse->explain ){
   89000     return;
   89001   }
   89002 #endif
   89003 
   89004   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
   89005   pParse->colNamesSet = 1;
   89006   fullNames = (db->flags & SQLITE_FullColNames)!=0;
   89007   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
   89008   sqlite3VdbeSetNumCols(v, pEList->nExpr);
   89009   for(i=0; i<pEList->nExpr; i++){
   89010     Expr *p;
   89011     p = pEList->a[i].pExpr;
   89012     if( NEVER(p==0) ) continue;
   89013     if( pEList->a[i].zName ){
   89014       char *zName = pEList->a[i].zName;
   89015       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
   89016     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
   89017       Table *pTab;
   89018       char *zCol;
   89019       int iCol = p->iColumn;
   89020       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
   89021         if( pTabList->a[j].iCursor==p->iTable ) break;
   89022       }
   89023       assert( j<pTabList->nSrc );
   89024       pTab = pTabList->a[j].pTab;
   89025       if( iCol<0 ) iCol = pTab->iPKey;
   89026       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   89027       if( iCol<0 ){
   89028         zCol = "rowid";
   89029       }else{
   89030         zCol = pTab->aCol[iCol].zName;
   89031       }
   89032       if( !shortNames && !fullNames ){
   89033         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   89034             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   89035       }else if( fullNames ){
   89036         char *zName = 0;
   89037         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
   89038         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
   89039       }else{
   89040         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
   89041       }
   89042     }else{
   89043       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
   89044           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
   89045     }
   89046   }
   89047   generateColumnTypes(pParse, pTabList, pEList);
   89048 }
   89049 
   89050 /*
   89051 ** Given a an expression list (which is really the list of expressions
   89052 ** that form the result set of a SELECT statement) compute appropriate
   89053 ** column names for a table that would hold the expression list.
   89054 **
   89055 ** All column names will be unique.
   89056 **
   89057 ** Only the column names are computed.  Column.zType, Column.zColl,
   89058 ** and other fields of Column are zeroed.
   89059 **
   89060 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
   89061 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
   89062 */
   89063 static int selectColumnsFromExprList(
   89064   Parse *pParse,          /* Parsing context */
   89065   ExprList *pEList,       /* Expr list from which to derive column names */
   89066   int *pnCol,             /* Write the number of columns here */
   89067   Column **paCol          /* Write the new column list here */
   89068 ){
   89069   sqlite3 *db = pParse->db;   /* Database connection */
   89070   int i, j;                   /* Loop counters */
   89071   int cnt;                    /* Index added to make the name unique */
   89072   Column *aCol, *pCol;        /* For looping over result columns */
   89073   int nCol;                   /* Number of columns in the result set */
   89074   Expr *p;                    /* Expression for a single result column */
   89075   char *zName;                /* Column name */
   89076   int nName;                  /* Size of name in zName[] */
   89077 
   89078   *pnCol = nCol = pEList->nExpr;
   89079   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
   89080   if( aCol==0 ) return SQLITE_NOMEM;
   89081   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   89082     /* Get an appropriate name for the column
   89083     */
   89084     p = pEList->a[i].pExpr;
   89085     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
   89086                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
   89087     if( (zName = pEList->a[i].zName)!=0 ){
   89088       /* If the column contains an "AS <name>" phrase, use <name> as the name */
   89089       zName = sqlite3DbStrDup(db, zName);
   89090     }else{
   89091       Expr *pColExpr = p;  /* The expression that is the result column name */
   89092       Table *pTab;         /* Table associated with this expression */
   89093       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
   89094       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
   89095         /* For columns use the column name name */
   89096         int iCol = pColExpr->iColumn;
   89097         pTab = pColExpr->pTab;
   89098         if( iCol<0 ) iCol = pTab->iPKey;
   89099         zName = sqlite3MPrintf(db, "%s",
   89100                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
   89101       }else if( pColExpr->op==TK_ID ){
   89102         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
   89103         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
   89104       }else{
   89105         /* Use the original text of the column expression as its name */
   89106         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
   89107       }
   89108     }
   89109     if( db->mallocFailed ){
   89110       sqlite3DbFree(db, zName);
   89111       break;
   89112     }
   89113 
   89114     /* Make sure the column name is unique.  If the name is not unique,
   89115     ** append a integer to the name so that it becomes unique.
   89116     */
   89117     nName = sqlite3Strlen30(zName);
   89118     for(j=cnt=0; j<i; j++){
   89119       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
   89120         char *zNewName;
   89121         zName[nName] = 0;
   89122         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
   89123         sqlite3DbFree(db, zName);
   89124         zName = zNewName;
   89125         j = -1;
   89126         if( zName==0 ) break;
   89127       }
   89128     }
   89129     pCol->zName = zName;
   89130   }
   89131   if( db->mallocFailed ){
   89132     for(j=0; j<i; j++){
   89133       sqlite3DbFree(db, aCol[j].zName);
   89134     }
   89135     sqlite3DbFree(db, aCol);
   89136     *paCol = 0;
   89137     *pnCol = 0;
   89138     return SQLITE_NOMEM;
   89139   }
   89140   return SQLITE_OK;
   89141 }
   89142 
   89143 /*
   89144 ** Add type and collation information to a column list based on
   89145 ** a SELECT statement.
   89146 **
   89147 ** The column list presumably came from selectColumnNamesFromExprList().
   89148 ** The column list has only names, not types or collations.  This
   89149 ** routine goes through and adds the types and collations.
   89150 **
   89151 ** This routine requires that all identifiers in the SELECT
   89152 ** statement be resolved.
   89153 */
   89154 static void selectAddColumnTypeAndCollation(
   89155   Parse *pParse,        /* Parsing contexts */
   89156   int nCol,             /* Number of columns */
   89157   Column *aCol,         /* List of columns */
   89158   Select *pSelect       /* SELECT used to determine types and collations */
   89159 ){
   89160   sqlite3 *db = pParse->db;
   89161   NameContext sNC;
   89162   Column *pCol;
   89163   CollSeq *pColl;
   89164   int i;
   89165   Expr *p;
   89166   struct ExprList_item *a;
   89167 
   89168   assert( pSelect!=0 );
   89169   assert( (pSelect->selFlags & SF_Resolved)!=0 );
   89170   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
   89171   if( db->mallocFailed ) return;
   89172   memset(&sNC, 0, sizeof(sNC));
   89173   sNC.pSrcList = pSelect->pSrc;
   89174   a = pSelect->pEList->a;
   89175   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
   89176     p = a[i].pExpr;
   89177     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
   89178     pCol->affinity = sqlite3ExprAffinity(p);
   89179     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
   89180     pColl = sqlite3ExprCollSeq(pParse, p);
   89181     if( pColl ){
   89182       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
   89183     }
   89184   }
   89185 }
   89186 
   89187 /*
   89188 ** Given a SELECT statement, generate a Table structure that describes
   89189 ** the result set of that SELECT.
   89190 */
   89191 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
   89192   Table *pTab;
   89193   sqlite3 *db = pParse->db;
   89194   int savedFlags;
   89195 
   89196   savedFlags = db->flags;
   89197   db->flags &= ~SQLITE_FullColNames;
   89198   db->flags |= SQLITE_ShortColNames;
   89199   sqlite3SelectPrep(pParse, pSelect, 0);
   89200   if( pParse->nErr ) return 0;
   89201   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
   89202   db->flags = savedFlags;
   89203   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
   89204   if( pTab==0 ){
   89205     return 0;
   89206   }
   89207   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
   89208   ** is disabled */
   89209   assert( db->lookaside.bEnabled==0 );
   89210   pTab->nRef = 1;
   89211   pTab->zName = 0;
   89212   pTab->nRowEst = 1000000;
   89213   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
   89214   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
   89215   pTab->iPKey = -1;
   89216   if( db->mallocFailed ){
   89217     sqlite3DeleteTable(db, pTab);
   89218     return 0;
   89219   }
   89220   return pTab;
   89221 }
   89222 
   89223 /*
   89224 ** Get a VDBE for the given parser context.  Create a new one if necessary.
   89225 ** If an error occurs, return NULL and leave a message in pParse.
   89226 */
   89227 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
   89228   Vdbe *v = pParse->pVdbe;
   89229   if( v==0 ){
   89230     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
   89231 #ifndef SQLITE_OMIT_TRACE
   89232     if( v ){
   89233       sqlite3VdbeAddOp0(v, OP_Trace);
   89234     }
   89235 #endif
   89236   }
   89237   return v;
   89238 }
   89239 
   89240 
   89241 /*
   89242 ** Compute the iLimit and iOffset fields of the SELECT based on the
   89243 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
   89244 ** that appear in the original SQL statement after the LIMIT and OFFSET
   89245 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
   89246 ** are the integer memory register numbers for counters used to compute
   89247 ** the limit and offset.  If there is no limit and/or offset, then
   89248 ** iLimit and iOffset are negative.
   89249 **
   89250 ** This routine changes the values of iLimit and iOffset only if
   89251 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
   89252 ** iOffset should have been preset to appropriate default values
   89253 ** (usually but not always -1) prior to calling this routine.
   89254 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
   89255 ** redefined.  The UNION ALL operator uses this property to force
   89256 ** the reuse of the same limit and offset registers across multiple
   89257 ** SELECT statements.
   89258 */
   89259 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
   89260   Vdbe *v = 0;
   89261   int iLimit = 0;
   89262   int iOffset;
   89263   int addr1, n;
   89264   if( p->iLimit ) return;
   89265 
   89266   /*
   89267   ** "LIMIT -1" always shows all rows.  There is some
   89268   ** contraversy about what the correct behavior should be.
   89269   ** The current implementation interprets "LIMIT 0" to mean
   89270   ** no rows.
   89271   */
   89272   sqlite3ExprCacheClear(pParse);
   89273   assert( p->pOffset==0 || p->pLimit!=0 );
   89274   if( p->pLimit ){
   89275     p->iLimit = iLimit = ++pParse->nMem;
   89276     v = sqlite3GetVdbe(pParse);
   89277     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
   89278     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
   89279       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
   89280       VdbeComment((v, "LIMIT counter"));
   89281       if( n==0 ){
   89282         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
   89283       }else{
   89284         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
   89285       }
   89286     }else{
   89287       sqlite3ExprCode(pParse, p->pLimit, iLimit);
   89288       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
   89289       VdbeComment((v, "LIMIT counter"));
   89290       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
   89291     }
   89292     if( p->pOffset ){
   89293       p->iOffset = iOffset = ++pParse->nMem;
   89294       pParse->nMem++;   /* Allocate an extra register for limit+offset */
   89295       sqlite3ExprCode(pParse, p->pOffset, iOffset);
   89296       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
   89297       VdbeComment((v, "OFFSET counter"));
   89298       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
   89299       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
   89300       sqlite3VdbeJumpHere(v, addr1);
   89301       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
   89302       VdbeComment((v, "LIMIT+OFFSET"));
   89303       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
   89304       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
   89305       sqlite3VdbeJumpHere(v, addr1);
   89306     }
   89307   }
   89308 }
   89309 
   89310 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   89311 /*
   89312 ** Return the appropriate collating sequence for the iCol-th column of
   89313 ** the result set for the compound-select statement "p".  Return NULL if
   89314 ** the column has no default collating sequence.
   89315 **
   89316 ** The collating sequence for the compound select is taken from the
   89317 ** left-most term of the select that has a collating sequence.
   89318 */
   89319 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
   89320   CollSeq *pRet;
   89321   if( p->pPrior ){
   89322     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
   89323   }else{
   89324     pRet = 0;
   89325   }
   89326   assert( iCol>=0 );
   89327   if( pRet==0 && iCol<p->pEList->nExpr ){
   89328     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
   89329   }
   89330   return pRet;
   89331 }
   89332 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   89333 
   89334 /* Forward reference */
   89335 static int multiSelectOrderBy(
   89336   Parse *pParse,        /* Parsing context */
   89337   Select *p,            /* The right-most of SELECTs to be coded */
   89338   SelectDest *pDest     /* What to do with query results */
   89339 );
   89340 
   89341 
   89342 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   89343 /*
   89344 ** This routine is called to process a compound query form from
   89345 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
   89346 ** INTERSECT
   89347 **
   89348 ** "p" points to the right-most of the two queries.  the query on the
   89349 ** left is p->pPrior.  The left query could also be a compound query
   89350 ** in which case this routine will be called recursively.
   89351 **
   89352 ** The results of the total query are to be written into a destination
   89353 ** of type eDest with parameter iParm.
   89354 **
   89355 ** Example 1:  Consider a three-way compound SQL statement.
   89356 **
   89357 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
   89358 **
   89359 ** This statement is parsed up as follows:
   89360 **
   89361 **     SELECT c FROM t3
   89362 **      |
   89363 **      `----->  SELECT b FROM t2
   89364 **                |
   89365 **                `------>  SELECT a FROM t1
   89366 **
   89367 ** The arrows in the diagram above represent the Select.pPrior pointer.
   89368 ** So if this routine is called with p equal to the t3 query, then
   89369 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
   89370 **
   89371 ** Notice that because of the way SQLite parses compound SELECTs, the
   89372 ** individual selects always group from left to right.
   89373 */
   89374 static int multiSelect(
   89375   Parse *pParse,        /* Parsing context */
   89376   Select *p,            /* The right-most of SELECTs to be coded */
   89377   SelectDest *pDest     /* What to do with query results */
   89378 ){
   89379   int rc = SQLITE_OK;   /* Success code from a subroutine */
   89380   Select *pPrior;       /* Another SELECT immediately to our left */
   89381   Vdbe *v;              /* Generate code to this VDBE */
   89382   SelectDest dest;      /* Alternative data destination */
   89383   Select *pDelete = 0;  /* Chain of simple selects to delete */
   89384   sqlite3 *db;          /* Database connection */
   89385 #ifndef SQLITE_OMIT_EXPLAIN
   89386   int iSub1;            /* EQP id of left-hand query */
   89387   int iSub2;            /* EQP id of right-hand query */
   89388 #endif
   89389 
   89390   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
   89391   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
   89392   */
   89393   assert( p && p->pPrior );  /* Calling function guarantees this much */
   89394   db = pParse->db;
   89395   pPrior = p->pPrior;
   89396   assert( pPrior->pRightmost!=pPrior );
   89397   assert( pPrior->pRightmost==p->pRightmost );
   89398   dest = *pDest;
   89399   if( pPrior->pOrderBy ){
   89400     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
   89401       selectOpName(p->op));
   89402     rc = 1;
   89403     goto multi_select_end;
   89404   }
   89405   if( pPrior->pLimit ){
   89406     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
   89407       selectOpName(p->op));
   89408     rc = 1;
   89409     goto multi_select_end;
   89410   }
   89411 
   89412   v = sqlite3GetVdbe(pParse);
   89413   assert( v!=0 );  /* The VDBE already created by calling function */
   89414 
   89415   /* Create the destination temporary table if necessary
   89416   */
   89417   if( dest.eDest==SRT_EphemTab ){
   89418     assert( p->pEList );
   89419     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
   89420     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   89421     dest.eDest = SRT_Table;
   89422   }
   89423 
   89424   /* Make sure all SELECTs in the statement have the same number of elements
   89425   ** in their result sets.
   89426   */
   89427   assert( p->pEList && pPrior->pEList );
   89428   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
   89429     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
   89430       " do not have the same number of result columns", selectOpName(p->op));
   89431     rc = 1;
   89432     goto multi_select_end;
   89433   }
   89434 
   89435   /* Compound SELECTs that have an ORDER BY clause are handled separately.
   89436   */
   89437   if( p->pOrderBy ){
   89438     return multiSelectOrderBy(pParse, p, pDest);
   89439   }
   89440 
   89441   /* Generate code for the left and right SELECT statements.
   89442   */
   89443   switch( p->op ){
   89444     case TK_ALL: {
   89445       int addr = 0;
   89446       int nLimit;
   89447       assert( !pPrior->pLimit );
   89448       pPrior->pLimit = p->pLimit;
   89449       pPrior->pOffset = p->pOffset;
   89450       explainSetInteger(iSub1, pParse->iNextSelectId);
   89451       rc = sqlite3Select(pParse, pPrior, &dest);
   89452       p->pLimit = 0;
   89453       p->pOffset = 0;
   89454       if( rc ){
   89455         goto multi_select_end;
   89456       }
   89457       p->pPrior = 0;
   89458       p->iLimit = pPrior->iLimit;
   89459       p->iOffset = pPrior->iOffset;
   89460       if( p->iLimit ){
   89461         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
   89462         VdbeComment((v, "Jump ahead if LIMIT reached"));
   89463       }
   89464       explainSetInteger(iSub2, pParse->iNextSelectId);
   89465       rc = sqlite3Select(pParse, p, &dest);
   89466       testcase( rc!=SQLITE_OK );
   89467       pDelete = p->pPrior;
   89468       p->pPrior = pPrior;
   89469       p->nSelectRow += pPrior->nSelectRow;
   89470       if( pPrior->pLimit
   89471        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
   89472        && p->nSelectRow > (double)nLimit
   89473       ){
   89474         p->nSelectRow = (double)nLimit;
   89475       }
   89476       if( addr ){
   89477         sqlite3VdbeJumpHere(v, addr);
   89478       }
   89479       break;
   89480     }
   89481     case TK_EXCEPT:
   89482     case TK_UNION: {
   89483       int unionTab;    /* Cursor number of the temporary table holding result */
   89484       u8 op = 0;       /* One of the SRT_ operations to apply to self */
   89485       int priorOp;     /* The SRT_ operation to apply to prior selects */
   89486       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
   89487       int addr;
   89488       SelectDest uniondest;
   89489 
   89490       testcase( p->op==TK_EXCEPT );
   89491       testcase( p->op==TK_UNION );
   89492       priorOp = SRT_Union;
   89493       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
   89494         /* We can reuse a temporary table generated by a SELECT to our
   89495         ** right.
   89496         */
   89497         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
   89498                                      ** of a 3-way or more compound */
   89499         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
   89500         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
   89501         unionTab = dest.iParm;
   89502       }else{
   89503         /* We will need to create our own temporary table to hold the
   89504         ** intermediate results.
   89505         */
   89506         unionTab = pParse->nTab++;
   89507         assert( p->pOrderBy==0 );
   89508         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
   89509         assert( p->addrOpenEphm[0] == -1 );
   89510         p->addrOpenEphm[0] = addr;
   89511         p->pRightmost->selFlags |= SF_UsesEphemeral;
   89512         assert( p->pEList );
   89513       }
   89514 
   89515       /* Code the SELECT statements to our left
   89516       */
   89517       assert( !pPrior->pOrderBy );
   89518       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
   89519       explainSetInteger(iSub1, pParse->iNextSelectId);
   89520       rc = sqlite3Select(pParse, pPrior, &uniondest);
   89521       if( rc ){
   89522         goto multi_select_end;
   89523       }
   89524 
   89525       /* Code the current SELECT statement
   89526       */
   89527       if( p->op==TK_EXCEPT ){
   89528         op = SRT_Except;
   89529       }else{
   89530         assert( p->op==TK_UNION );
   89531         op = SRT_Union;
   89532       }
   89533       p->pPrior = 0;
   89534       pLimit = p->pLimit;
   89535       p->pLimit = 0;
   89536       pOffset = p->pOffset;
   89537       p->pOffset = 0;
   89538       uniondest.eDest = op;
   89539       explainSetInteger(iSub2, pParse->iNextSelectId);
   89540       rc = sqlite3Select(pParse, p, &uniondest);
   89541       testcase( rc!=SQLITE_OK );
   89542       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
   89543       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
   89544       sqlite3ExprListDelete(db, p->pOrderBy);
   89545       pDelete = p->pPrior;
   89546       p->pPrior = pPrior;
   89547       p->pOrderBy = 0;
   89548       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
   89549       sqlite3ExprDelete(db, p->pLimit);
   89550       p->pLimit = pLimit;
   89551       p->pOffset = pOffset;
   89552       p->iLimit = 0;
   89553       p->iOffset = 0;
   89554 
   89555       /* Convert the data in the temporary table into whatever form
   89556       ** it is that we currently need.
   89557       */
   89558       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
   89559       if( dest.eDest!=priorOp ){
   89560         int iCont, iBreak, iStart;
   89561         assert( p->pEList );
   89562         if( dest.eDest==SRT_Output ){
   89563           Select *pFirst = p;
   89564           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   89565           generateColumnNames(pParse, 0, pFirst->pEList);
   89566         }
   89567         iBreak = sqlite3VdbeMakeLabel(v);
   89568         iCont = sqlite3VdbeMakeLabel(v);
   89569         computeLimitRegisters(pParse, p, iBreak);
   89570         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
   89571         iStart = sqlite3VdbeCurrentAddr(v);
   89572         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
   89573                         0, -1, &dest, iCont, iBreak);
   89574         sqlite3VdbeResolveLabel(v, iCont);
   89575         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
   89576         sqlite3VdbeResolveLabel(v, iBreak);
   89577         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
   89578       }
   89579       break;
   89580     }
   89581     default: assert( p->op==TK_INTERSECT ); {
   89582       int tab1, tab2;
   89583       int iCont, iBreak, iStart;
   89584       Expr *pLimit, *pOffset;
   89585       int addr;
   89586       SelectDest intersectdest;
   89587       int r1;
   89588 
   89589       /* INTERSECT is different from the others since it requires
   89590       ** two temporary tables.  Hence it has its own case.  Begin
   89591       ** by allocating the tables we will need.
   89592       */
   89593       tab1 = pParse->nTab++;
   89594       tab2 = pParse->nTab++;
   89595       assert( p->pOrderBy==0 );
   89596 
   89597       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
   89598       assert( p->addrOpenEphm[0] == -1 );
   89599       p->addrOpenEphm[0] = addr;
   89600       p->pRightmost->selFlags |= SF_UsesEphemeral;
   89601       assert( p->pEList );
   89602 
   89603       /* Code the SELECTs to our left into temporary table "tab1".
   89604       */
   89605       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
   89606       explainSetInteger(iSub1, pParse->iNextSelectId);
   89607       rc = sqlite3Select(pParse, pPrior, &intersectdest);
   89608       if( rc ){
   89609         goto multi_select_end;
   89610       }
   89611 
   89612       /* Code the current SELECT into temporary table "tab2"
   89613       */
   89614       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
   89615       assert( p->addrOpenEphm[1] == -1 );
   89616       p->addrOpenEphm[1] = addr;
   89617       p->pPrior = 0;
   89618       pLimit = p->pLimit;
   89619       p->pLimit = 0;
   89620       pOffset = p->pOffset;
   89621       p->pOffset = 0;
   89622       intersectdest.iParm = tab2;
   89623       explainSetInteger(iSub2, pParse->iNextSelectId);
   89624       rc = sqlite3Select(pParse, p, &intersectdest);
   89625       testcase( rc!=SQLITE_OK );
   89626       pDelete = p->pPrior;
   89627       p->pPrior = pPrior;
   89628       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   89629       sqlite3ExprDelete(db, p->pLimit);
   89630       p->pLimit = pLimit;
   89631       p->pOffset = pOffset;
   89632 
   89633       /* Generate code to take the intersection of the two temporary
   89634       ** tables.
   89635       */
   89636       assert( p->pEList );
   89637       if( dest.eDest==SRT_Output ){
   89638         Select *pFirst = p;
   89639         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   89640         generateColumnNames(pParse, 0, pFirst->pEList);
   89641       }
   89642       iBreak = sqlite3VdbeMakeLabel(v);
   89643       iCont = sqlite3VdbeMakeLabel(v);
   89644       computeLimitRegisters(pParse, p, iBreak);
   89645       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
   89646       r1 = sqlite3GetTempReg(pParse);
   89647       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
   89648       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
   89649       sqlite3ReleaseTempReg(pParse, r1);
   89650       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
   89651                       0, -1, &dest, iCont, iBreak);
   89652       sqlite3VdbeResolveLabel(v, iCont);
   89653       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
   89654       sqlite3VdbeResolveLabel(v, iBreak);
   89655       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
   89656       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
   89657       break;
   89658     }
   89659   }
   89660 
   89661   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
   89662 
   89663   /* Compute collating sequences used by
   89664   ** temporary tables needed to implement the compound select.
   89665   ** Attach the KeyInfo structure to all temporary tables.
   89666   **
   89667   ** This section is run by the right-most SELECT statement only.
   89668   ** SELECT statements to the left always skip this part.  The right-most
   89669   ** SELECT might also skip this part if it has no ORDER BY clause and
   89670   ** no temp tables are required.
   89671   */
   89672   if( p->selFlags & SF_UsesEphemeral ){
   89673     int i;                        /* Loop counter */
   89674     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
   89675     Select *pLoop;                /* For looping through SELECT statements */
   89676     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
   89677     int nCol;                     /* Number of columns in result set */
   89678 
   89679     assert( p->pRightmost==p );
   89680     nCol = p->pEList->nExpr;
   89681     pKeyInfo = sqlite3DbMallocZero(db,
   89682                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
   89683     if( !pKeyInfo ){
   89684       rc = SQLITE_NOMEM;
   89685       goto multi_select_end;
   89686     }
   89687 
   89688     pKeyInfo->enc = ENC(db);
   89689     pKeyInfo->nField = (u16)nCol;
   89690 
   89691     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
   89692       *apColl = multiSelectCollSeq(pParse, p, i);
   89693       if( 0==*apColl ){
   89694         *apColl = db->pDfltColl;
   89695       }
   89696     }
   89697 
   89698     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
   89699       for(i=0; i<2; i++){
   89700         int addr = pLoop->addrOpenEphm[i];
   89701         if( addr<0 ){
   89702           /* If [0] is unused then [1] is also unused.  So we can
   89703           ** always safely abort as soon as the first unused slot is found */
   89704           assert( pLoop->addrOpenEphm[1]<0 );
   89705           break;
   89706         }
   89707         sqlite3VdbeChangeP2(v, addr, nCol);
   89708         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
   89709         pLoop->addrOpenEphm[i] = -1;
   89710       }
   89711     }
   89712     sqlite3DbFree(db, pKeyInfo);
   89713   }
   89714 
   89715 multi_select_end:
   89716   pDest->iMem = dest.iMem;
   89717   pDest->nMem = dest.nMem;
   89718   sqlite3SelectDelete(db, pDelete);
   89719   return rc;
   89720 }
   89721 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
   89722 
   89723 /*
   89724 ** Code an output subroutine for a coroutine implementation of a
   89725 ** SELECT statment.
   89726 **
   89727 ** The data to be output is contained in pIn->iMem.  There are
   89728 ** pIn->nMem columns to be output.  pDest is where the output should
   89729 ** be sent.
   89730 **
   89731 ** regReturn is the number of the register holding the subroutine
   89732 ** return address.
   89733 **
   89734 ** If regPrev>0 then it is the first register in a vector that
   89735 ** records the previous output.  mem[regPrev] is a flag that is false
   89736 ** if there has been no previous output.  If regPrev>0 then code is
   89737 ** generated to suppress duplicates.  pKeyInfo is used for comparing
   89738 ** keys.
   89739 **
   89740 ** If the LIMIT found in p->iLimit is reached, jump immediately to
   89741 ** iBreak.
   89742 */
   89743 static int generateOutputSubroutine(
   89744   Parse *pParse,          /* Parsing context */
   89745   Select *p,              /* The SELECT statement */
   89746   SelectDest *pIn,        /* Coroutine supplying data */
   89747   SelectDest *pDest,      /* Where to send the data */
   89748   int regReturn,          /* The return address register */
   89749   int regPrev,            /* Previous result register.  No uniqueness if 0 */
   89750   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
   89751   int p4type,             /* The p4 type for pKeyInfo */
   89752   int iBreak              /* Jump here if we hit the LIMIT */
   89753 ){
   89754   Vdbe *v = pParse->pVdbe;
   89755   int iContinue;
   89756   int addr;
   89757 
   89758   addr = sqlite3VdbeCurrentAddr(v);
   89759   iContinue = sqlite3VdbeMakeLabel(v);
   89760 
   89761   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   89762   */
   89763   if( regPrev ){
   89764     int j1, j2;
   89765     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
   89766     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
   89767                               (char*)pKeyInfo, p4type);
   89768     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
   89769     sqlite3VdbeJumpHere(v, j1);
   89770     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
   89771     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
   89772   }
   89773   if( pParse->db->mallocFailed ) return 0;
   89774 
   89775   /* Suppress the the first OFFSET entries if there is an OFFSET clause
   89776   */
   89777   codeOffset(v, p, iContinue);
   89778 
   89779   switch( pDest->eDest ){
   89780     /* Store the result as data using a unique key.
   89781     */
   89782     case SRT_Table:
   89783     case SRT_EphemTab: {
   89784       int r1 = sqlite3GetTempReg(pParse);
   89785       int r2 = sqlite3GetTempReg(pParse);
   89786       testcase( pDest->eDest==SRT_Table );
   89787       testcase( pDest->eDest==SRT_EphemTab );
   89788       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
   89789       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
   89790       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
   89791       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   89792       sqlite3ReleaseTempReg(pParse, r2);
   89793       sqlite3ReleaseTempReg(pParse, r1);
   89794       break;
   89795     }
   89796 
   89797 #ifndef SQLITE_OMIT_SUBQUERY
   89798     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   89799     ** then there should be a single item on the stack.  Write this
   89800     ** item into the set table with bogus data.
   89801     */
   89802     case SRT_Set: {
   89803       int r1;
   89804       assert( pIn->nMem==1 );
   89805       p->affinity =
   89806          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
   89807       r1 = sqlite3GetTempReg(pParse);
   89808       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
   89809       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
   89810       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
   89811       sqlite3ReleaseTempReg(pParse, r1);
   89812       break;
   89813     }
   89814 
   89815 #if 0  /* Never occurs on an ORDER BY query */
   89816     /* If any row exist in the result set, record that fact and abort.
   89817     */
   89818     case SRT_Exists: {
   89819       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
   89820       /* The LIMIT clause will terminate the loop for us */
   89821       break;
   89822     }
   89823 #endif
   89824 
   89825     /* If this is a scalar select that is part of an expression, then
   89826     ** store the results in the appropriate memory cell and break out
   89827     ** of the scan loop.
   89828     */
   89829     case SRT_Mem: {
   89830       assert( pIn->nMem==1 );
   89831       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
   89832       /* The LIMIT clause will jump out of the loop for us */
   89833       break;
   89834     }
   89835 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   89836 
   89837     /* The results are stored in a sequence of registers
   89838     ** starting at pDest->iMem.  Then the co-routine yields.
   89839     */
   89840     case SRT_Coroutine: {
   89841       if( pDest->iMem==0 ){
   89842         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
   89843         pDest->nMem = pIn->nMem;
   89844       }
   89845       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
   89846       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   89847       break;
   89848     }
   89849 
   89850     /* If none of the above, then the result destination must be
   89851     ** SRT_Output.  This routine is never called with any other
   89852     ** destination other than the ones handled above or SRT_Output.
   89853     **
   89854     ** For SRT_Output, results are stored in a sequence of registers.
   89855     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
   89856     ** return the next row of result.
   89857     */
   89858     default: {
   89859       assert( pDest->eDest==SRT_Output );
   89860       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
   89861       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
   89862       break;
   89863     }
   89864   }
   89865 
   89866   /* Jump to the end of the loop if the LIMIT is reached.
   89867   */
   89868   if( p->iLimit ){
   89869     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   89870   }
   89871 
   89872   /* Generate the subroutine return
   89873   */
   89874   sqlite3VdbeResolveLabel(v, iContinue);
   89875   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
   89876 
   89877   return addr;
   89878 }
   89879 
   89880 /*
   89881 ** Alternative compound select code generator for cases when there
   89882 ** is an ORDER BY clause.
   89883 **
   89884 ** We assume a query of the following form:
   89885 **
   89886 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
   89887 **
   89888 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
   89889 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
   89890 ** co-routines.  Then run the co-routines in parallel and merge the results
   89891 ** into the output.  In addition to the two coroutines (called selectA and
   89892 ** selectB) there are 7 subroutines:
   89893 **
   89894 **    outA:    Move the output of the selectA coroutine into the output
   89895 **             of the compound query.
   89896 **
   89897 **    outB:    Move the output of the selectB coroutine into the output
   89898 **             of the compound query.  (Only generated for UNION and
   89899 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
   89900 **             appears only in B.)
   89901 **
   89902 **    AltB:    Called when there is data from both coroutines and A<B.
   89903 **
   89904 **    AeqB:    Called when there is data from both coroutines and A==B.
   89905 **
   89906 **    AgtB:    Called when there is data from both coroutines and A>B.
   89907 **
   89908 **    EofA:    Called when data is exhausted from selectA.
   89909 **
   89910 **    EofB:    Called when data is exhausted from selectB.
   89911 **
   89912 ** The implementation of the latter five subroutines depend on which
   89913 ** <operator> is used:
   89914 **
   89915 **
   89916 **             UNION ALL         UNION            EXCEPT          INTERSECT
   89917 **          -------------  -----------------  --------------  -----------------
   89918 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
   89919 **
   89920 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
   89921 **
   89922 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
   89923 **
   89924 **   EofA:   outB, nextB      outB, nextB          halt             halt
   89925 **
   89926 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
   89927 **
   89928 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
   89929 ** causes an immediate jump to EofA and an EOF on B following nextB causes
   89930 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
   89931 ** following nextX causes a jump to the end of the select processing.
   89932 **
   89933 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
   89934 ** within the output subroutine.  The regPrev register set holds the previously
   89935 ** output value.  A comparison is made against this value and the output
   89936 ** is skipped if the next results would be the same as the previous.
   89937 **
   89938 ** The implementation plan is to implement the two coroutines and seven
   89939 ** subroutines first, then put the control logic at the bottom.  Like this:
   89940 **
   89941 **          goto Init
   89942 **     coA: coroutine for left query (A)
   89943 **     coB: coroutine for right query (B)
   89944 **    outA: output one row of A
   89945 **    outB: output one row of B (UNION and UNION ALL only)
   89946 **    EofA: ...
   89947 **    EofB: ...
   89948 **    AltB: ...
   89949 **    AeqB: ...
   89950 **    AgtB: ...
   89951 **    Init: initialize coroutine registers
   89952 **          yield coA
   89953 **          if eof(A) goto EofA
   89954 **          yield coB
   89955 **          if eof(B) goto EofB
   89956 **    Cmpr: Compare A, B
   89957 **          Jump AltB, AeqB, AgtB
   89958 **     End: ...
   89959 **
   89960 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
   89961 ** actually called using Gosub and they do not Return.  EofA and EofB loop
   89962 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
   89963 ** and AgtB jump to either L2 or to one of EofA or EofB.
   89964 */
   89965 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   89966 static int multiSelectOrderBy(
   89967   Parse *pParse,        /* Parsing context */
   89968   Select *p,            /* The right-most of SELECTs to be coded */
   89969   SelectDest *pDest     /* What to do with query results */
   89970 ){
   89971   int i, j;             /* Loop counters */
   89972   Select *pPrior;       /* Another SELECT immediately to our left */
   89973   Vdbe *v;              /* Generate code to this VDBE */
   89974   SelectDest destA;     /* Destination for coroutine A */
   89975   SelectDest destB;     /* Destination for coroutine B */
   89976   int regAddrA;         /* Address register for select-A coroutine */
   89977   int regEofA;          /* Flag to indicate when select-A is complete */
   89978   int regAddrB;         /* Address register for select-B coroutine */
   89979   int regEofB;          /* Flag to indicate when select-B is complete */
   89980   int addrSelectA;      /* Address of the select-A coroutine */
   89981   int addrSelectB;      /* Address of the select-B coroutine */
   89982   int regOutA;          /* Address register for the output-A subroutine */
   89983   int regOutB;          /* Address register for the output-B subroutine */
   89984   int addrOutA;         /* Address of the output-A subroutine */
   89985   int addrOutB = 0;     /* Address of the output-B subroutine */
   89986   int addrEofA;         /* Address of the select-A-exhausted subroutine */
   89987   int addrEofB;         /* Address of the select-B-exhausted subroutine */
   89988   int addrAltB;         /* Address of the A<B subroutine */
   89989   int addrAeqB;         /* Address of the A==B subroutine */
   89990   int addrAgtB;         /* Address of the A>B subroutine */
   89991   int regLimitA;        /* Limit register for select-A */
   89992   int regLimitB;        /* Limit register for select-A */
   89993   int regPrev;          /* A range of registers to hold previous output */
   89994   int savedLimit;       /* Saved value of p->iLimit */
   89995   int savedOffset;      /* Saved value of p->iOffset */
   89996   int labelCmpr;        /* Label for the start of the merge algorithm */
   89997   int labelEnd;         /* Label for the end of the overall SELECT stmt */
   89998   int j1;               /* Jump instructions that get retargetted */
   89999   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
   90000   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
   90001   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
   90002   sqlite3 *db;          /* Database connection */
   90003   ExprList *pOrderBy;   /* The ORDER BY clause */
   90004   int nOrderBy;         /* Number of terms in the ORDER BY clause */
   90005   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
   90006 #ifndef SQLITE_OMIT_EXPLAIN
   90007   int iSub1;            /* EQP id of left-hand query */
   90008   int iSub2;            /* EQP id of right-hand query */
   90009 #endif
   90010 
   90011   assert( p->pOrderBy!=0 );
   90012   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
   90013   db = pParse->db;
   90014   v = pParse->pVdbe;
   90015   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
   90016   labelEnd = sqlite3VdbeMakeLabel(v);
   90017   labelCmpr = sqlite3VdbeMakeLabel(v);
   90018 
   90019 
   90020   /* Patch up the ORDER BY clause
   90021   */
   90022   op = p->op;
   90023   pPrior = p->pPrior;
   90024   assert( pPrior->pOrderBy==0 );
   90025   pOrderBy = p->pOrderBy;
   90026   assert( pOrderBy );
   90027   nOrderBy = pOrderBy->nExpr;
   90028 
   90029   /* For operators other than UNION ALL we have to make sure that
   90030   ** the ORDER BY clause covers every term of the result set.  Add
   90031   ** terms to the ORDER BY clause as necessary.
   90032   */
   90033   if( op!=TK_ALL ){
   90034     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
   90035       struct ExprList_item *pItem;
   90036       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
   90037         assert( pItem->iCol>0 );
   90038         if( pItem->iCol==i ) break;
   90039       }
   90040       if( j==nOrderBy ){
   90041         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
   90042         if( pNew==0 ) return SQLITE_NOMEM;
   90043         pNew->flags |= EP_IntValue;
   90044         pNew->u.iValue = i;
   90045         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
   90046         pOrderBy->a[nOrderBy++].iCol = (u16)i;
   90047       }
   90048     }
   90049   }
   90050 
   90051   /* Compute the comparison permutation and keyinfo that is used with
   90052   ** the permutation used to determine if the next
   90053   ** row of results comes from selectA or selectB.  Also add explicit
   90054   ** collations to the ORDER BY clause terms so that when the subqueries
   90055   ** to the right and the left are evaluated, they use the correct
   90056   ** collation.
   90057   */
   90058   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
   90059   if( aPermute ){
   90060     struct ExprList_item *pItem;
   90061     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
   90062       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
   90063       aPermute[i] = pItem->iCol - 1;
   90064     }
   90065     pKeyMerge =
   90066       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
   90067     if( pKeyMerge ){
   90068       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
   90069       pKeyMerge->nField = (u16)nOrderBy;
   90070       pKeyMerge->enc = ENC(db);
   90071       for(i=0; i<nOrderBy; i++){
   90072         CollSeq *pColl;
   90073         Expr *pTerm = pOrderBy->a[i].pExpr;
   90074         if( pTerm->flags & EP_ExpCollate ){
   90075           pColl = pTerm->pColl;
   90076         }else{
   90077           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
   90078           pTerm->flags |= EP_ExpCollate;
   90079           pTerm->pColl = pColl;
   90080         }
   90081         pKeyMerge->aColl[i] = pColl;
   90082         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
   90083       }
   90084     }
   90085   }else{
   90086     pKeyMerge = 0;
   90087   }
   90088 
   90089   /* Reattach the ORDER BY clause to the query.
   90090   */
   90091   p->pOrderBy = pOrderBy;
   90092   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
   90093 
   90094   /* Allocate a range of temporary registers and the KeyInfo needed
   90095   ** for the logic that removes duplicate result rows when the
   90096   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
   90097   */
   90098   if( op==TK_ALL ){
   90099     regPrev = 0;
   90100   }else{
   90101     int nExpr = p->pEList->nExpr;
   90102     assert( nOrderBy>=nExpr || db->mallocFailed );
   90103     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
   90104     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
   90105     pKeyDup = sqlite3DbMallocZero(db,
   90106                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
   90107     if( pKeyDup ){
   90108       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
   90109       pKeyDup->nField = (u16)nExpr;
   90110       pKeyDup->enc = ENC(db);
   90111       for(i=0; i<nExpr; i++){
   90112         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
   90113         pKeyDup->aSortOrder[i] = 0;
   90114       }
   90115     }
   90116   }
   90117 
   90118   /* Separate the left and the right query from one another
   90119   */
   90120   p->pPrior = 0;
   90121   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
   90122   if( pPrior->pPrior==0 ){
   90123     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
   90124   }
   90125 
   90126   /* Compute the limit registers */
   90127   computeLimitRegisters(pParse, p, labelEnd);
   90128   if( p->iLimit && op==TK_ALL ){
   90129     regLimitA = ++pParse->nMem;
   90130     regLimitB = ++pParse->nMem;
   90131     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
   90132                                   regLimitA);
   90133     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
   90134   }else{
   90135     regLimitA = regLimitB = 0;
   90136   }
   90137   sqlite3ExprDelete(db, p->pLimit);
   90138   p->pLimit = 0;
   90139   sqlite3ExprDelete(db, p->pOffset);
   90140   p->pOffset = 0;
   90141 
   90142   regAddrA = ++pParse->nMem;
   90143   regEofA = ++pParse->nMem;
   90144   regAddrB = ++pParse->nMem;
   90145   regEofB = ++pParse->nMem;
   90146   regOutA = ++pParse->nMem;
   90147   regOutB = ++pParse->nMem;
   90148   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
   90149   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
   90150 
   90151   /* Jump past the various subroutines and coroutines to the main
   90152   ** merge loop
   90153   */
   90154   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
   90155   addrSelectA = sqlite3VdbeCurrentAddr(v);
   90156 
   90157 
   90158   /* Generate a coroutine to evaluate the SELECT statement to the
   90159   ** left of the compound operator - the "A" select.
   90160   */
   90161   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
   90162   pPrior->iLimit = regLimitA;
   90163   explainSetInteger(iSub1, pParse->iNextSelectId);
   90164   sqlite3Select(pParse, pPrior, &destA);
   90165   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
   90166   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   90167   VdbeNoopComment((v, "End coroutine for left SELECT"));
   90168 
   90169   /* Generate a coroutine to evaluate the SELECT statement on
   90170   ** the right - the "B" select
   90171   */
   90172   addrSelectB = sqlite3VdbeCurrentAddr(v);
   90173   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
   90174   savedLimit = p->iLimit;
   90175   savedOffset = p->iOffset;
   90176   p->iLimit = regLimitB;
   90177   p->iOffset = 0;
   90178   explainSetInteger(iSub2, pParse->iNextSelectId);
   90179   sqlite3Select(pParse, p, &destB);
   90180   p->iLimit = savedLimit;
   90181   p->iOffset = savedOffset;
   90182   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
   90183   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   90184   VdbeNoopComment((v, "End coroutine for right SELECT"));
   90185 
   90186   /* Generate a subroutine that outputs the current row of the A
   90187   ** select as the next output row of the compound select.
   90188   */
   90189   VdbeNoopComment((v, "Output routine for A"));
   90190   addrOutA = generateOutputSubroutine(pParse,
   90191                  p, &destA, pDest, regOutA,
   90192                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
   90193 
   90194   /* Generate a subroutine that outputs the current row of the B
   90195   ** select as the next output row of the compound select.
   90196   */
   90197   if( op==TK_ALL || op==TK_UNION ){
   90198     VdbeNoopComment((v, "Output routine for B"));
   90199     addrOutB = generateOutputSubroutine(pParse,
   90200                  p, &destB, pDest, regOutB,
   90201                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
   90202   }
   90203 
   90204   /* Generate a subroutine to run when the results from select A
   90205   ** are exhausted and only data in select B remains.
   90206   */
   90207   VdbeNoopComment((v, "eof-A subroutine"));
   90208   if( op==TK_EXCEPT || op==TK_INTERSECT ){
   90209     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
   90210   }else{
   90211     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
   90212     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   90213     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   90214     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
   90215     p->nSelectRow += pPrior->nSelectRow;
   90216   }
   90217 
   90218   /* Generate a subroutine to run when the results from select B
   90219   ** are exhausted and only data in select A remains.
   90220   */
   90221   if( op==TK_INTERSECT ){
   90222     addrEofB = addrEofA;
   90223     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
   90224   }else{
   90225     VdbeNoopComment((v, "eof-B subroutine"));
   90226     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
   90227     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   90228     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   90229     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
   90230   }
   90231 
   90232   /* Generate code to handle the case of A<B
   90233   */
   90234   VdbeNoopComment((v, "A-lt-B subroutine"));
   90235   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
   90236   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   90237   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   90238   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   90239 
   90240   /* Generate code to handle the case of A==B
   90241   */
   90242   if( op==TK_ALL ){
   90243     addrAeqB = addrAltB;
   90244   }else if( op==TK_INTERSECT ){
   90245     addrAeqB = addrAltB;
   90246     addrAltB++;
   90247   }else{
   90248     VdbeNoopComment((v, "A-eq-B subroutine"));
   90249     addrAeqB =
   90250     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
   90251     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   90252     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   90253   }
   90254 
   90255   /* Generate code to handle the case of A>B
   90256   */
   90257   VdbeNoopComment((v, "A-gt-B subroutine"));
   90258   addrAgtB = sqlite3VdbeCurrentAddr(v);
   90259   if( op==TK_ALL || op==TK_UNION ){
   90260     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
   90261   }
   90262   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
   90263   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   90264   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
   90265 
   90266   /* This code runs once to initialize everything.
   90267   */
   90268   sqlite3VdbeJumpHere(v, j1);
   90269   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
   90270   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
   90271   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
   90272   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
   90273   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
   90274   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
   90275 
   90276   /* Implement the main merge loop
   90277   */
   90278   sqlite3VdbeResolveLabel(v, labelCmpr);
   90279   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
   90280   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
   90281                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
   90282   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
   90283 
   90284   /* Release temporary registers
   90285   */
   90286   if( regPrev ){
   90287     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
   90288   }
   90289 
   90290   /* Jump to the this point in order to terminate the query.
   90291   */
   90292   sqlite3VdbeResolveLabel(v, labelEnd);
   90293 
   90294   /* Set the number of output columns
   90295   */
   90296   if( pDest->eDest==SRT_Output ){
   90297     Select *pFirst = pPrior;
   90298     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
   90299     generateColumnNames(pParse, 0, pFirst->pEList);
   90300   }
   90301 
   90302   /* Reassembly the compound query so that it will be freed correctly
   90303   ** by the calling function */
   90304   if( p->pPrior ){
   90305     sqlite3SelectDelete(db, p->pPrior);
   90306   }
   90307   p->pPrior = pPrior;
   90308 
   90309   /*** TBD:  Insert subroutine calls to close cursors on incomplete
   90310   **** subqueries ****/
   90311   explainComposite(pParse, p->op, iSub1, iSub2, 0);
   90312   return SQLITE_OK;
   90313 }
   90314 #endif
   90315 
   90316 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   90317 /* Forward Declarations */
   90318 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
   90319 static void substSelect(sqlite3*, Select *, int, ExprList *);
   90320 
   90321 /*
   90322 ** Scan through the expression pExpr.  Replace every reference to
   90323 ** a column in table number iTable with a copy of the iColumn-th
   90324 ** entry in pEList.  (But leave references to the ROWID column
   90325 ** unchanged.)
   90326 **
   90327 ** This routine is part of the flattening procedure.  A subquery
   90328 ** whose result set is defined by pEList appears as entry in the
   90329 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
   90330 ** FORM clause entry is iTable.  This routine make the necessary
   90331 ** changes to pExpr so that it refers directly to the source table
   90332 ** of the subquery rather the result set of the subquery.
   90333 */
   90334 static Expr *substExpr(
   90335   sqlite3 *db,        /* Report malloc errors to this connection */
   90336   Expr *pExpr,        /* Expr in which substitution occurs */
   90337   int iTable,         /* Table to be substituted */
   90338   ExprList *pEList    /* Substitute expressions */
   90339 ){
   90340   if( pExpr==0 ) return 0;
   90341   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
   90342     if( pExpr->iColumn<0 ){
   90343       pExpr->op = TK_NULL;
   90344     }else{
   90345       Expr *pNew;
   90346       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
   90347       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
   90348       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
   90349       if( pNew && pExpr->pColl ){
   90350         pNew->pColl = pExpr->pColl;
   90351       }
   90352       sqlite3ExprDelete(db, pExpr);
   90353       pExpr = pNew;
   90354     }
   90355   }else{
   90356     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
   90357     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
   90358     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   90359       substSelect(db, pExpr->x.pSelect, iTable, pEList);
   90360     }else{
   90361       substExprList(db, pExpr->x.pList, iTable, pEList);
   90362     }
   90363   }
   90364   return pExpr;
   90365 }
   90366 static void substExprList(
   90367   sqlite3 *db,         /* Report malloc errors here */
   90368   ExprList *pList,     /* List to scan and in which to make substitutes */
   90369   int iTable,          /* Table to be substituted */
   90370   ExprList *pEList     /* Substitute values */
   90371 ){
   90372   int i;
   90373   if( pList==0 ) return;
   90374   for(i=0; i<pList->nExpr; i++){
   90375     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
   90376   }
   90377 }
   90378 static void substSelect(
   90379   sqlite3 *db,         /* Report malloc errors here */
   90380   Select *p,           /* SELECT statement in which to make substitutions */
   90381   int iTable,          /* Table to be replaced */
   90382   ExprList *pEList     /* Substitute values */
   90383 ){
   90384   SrcList *pSrc;
   90385   struct SrcList_item *pItem;
   90386   int i;
   90387   if( !p ) return;
   90388   substExprList(db, p->pEList, iTable, pEList);
   90389   substExprList(db, p->pGroupBy, iTable, pEList);
   90390   substExprList(db, p->pOrderBy, iTable, pEList);
   90391   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
   90392   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
   90393   substSelect(db, p->pPrior, iTable, pEList);
   90394   pSrc = p->pSrc;
   90395   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
   90396   if( ALWAYS(pSrc) ){
   90397     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
   90398       substSelect(db, pItem->pSelect, iTable, pEList);
   90399     }
   90400   }
   90401 }
   90402 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   90403 
   90404 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   90405 /*
   90406 ** This routine attempts to flatten subqueries in order to speed
   90407 ** execution.  It returns 1 if it makes changes and 0 if no flattening
   90408 ** occurs.
   90409 **
   90410 ** To understand the concept of flattening, consider the following
   90411 ** query:
   90412 **
   90413 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
   90414 **
   90415 ** The default way of implementing this query is to execute the
   90416 ** subquery first and store the results in a temporary table, then
   90417 ** run the outer query on that temporary table.  This requires two
   90418 ** passes over the data.  Furthermore, because the temporary table
   90419 ** has no indices, the WHERE clause on the outer query cannot be
   90420 ** optimized.
   90421 **
   90422 ** This routine attempts to rewrite queries such as the above into
   90423 ** a single flat select, like this:
   90424 **
   90425 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
   90426 **
   90427 ** The code generated for this simpification gives the same result
   90428 ** but only has to scan the data once.  And because indices might
   90429 ** exist on the table t1, a complete scan of the data might be
   90430 ** avoided.
   90431 **
   90432 ** Flattening is only attempted if all of the following are true:
   90433 **
   90434 **   (1)  The subquery and the outer query do not both use aggregates.
   90435 **
   90436 **   (2)  The subquery is not an aggregate or the outer query is not a join.
   90437 **
   90438 **   (3)  The subquery is not the right operand of a left outer join
   90439 **        (Originally ticket #306.  Strengthened by ticket #3300)
   90440 **
   90441 **   (4)  The subquery is not DISTINCT.
   90442 **
   90443 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
   90444 **        sub-queries that were excluded from this optimization. Restriction
   90445 **        (4) has since been expanded to exclude all DISTINCT subqueries.
   90446 **
   90447 **   (6)  The subquery does not use aggregates or the outer query is not
   90448 **        DISTINCT.
   90449 **
   90450 **   (7)  The subquery has a FROM clause.
   90451 **
   90452 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
   90453 **
   90454 **   (9)  The subquery does not use LIMIT or the outer query does not use
   90455 **        aggregates.
   90456 **
   90457 **  (10)  The subquery does not use aggregates or the outer query does not
   90458 **        use LIMIT.
   90459 **
   90460 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
   90461 **
   90462 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
   90463 **        a separate restriction deriving from ticket #350.
   90464 **
   90465 **  (13)  The subquery and outer query do not both use LIMIT.
   90466 **
   90467 **  (14)  The subquery does not use OFFSET.
   90468 **
   90469 **  (15)  The outer query is not part of a compound select or the
   90470 **        subquery does not have a LIMIT clause.
   90471 **        (See ticket #2339 and ticket [02a8e81d44]).
   90472 **
   90473 **  (16)  The outer query is not an aggregate or the subquery does
   90474 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
   90475 **        until we introduced the group_concat() function.
   90476 **
   90477 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
   90478 **        compound clause made up entirely of non-aggregate queries, and
   90479 **        the parent query:
   90480 **
   90481 **          * is not itself part of a compound select,
   90482 **          * is not an aggregate or DISTINCT query, and
   90483 **          * has no other tables or sub-selects in the FROM clause.
   90484 **
   90485 **        The parent and sub-query may contain WHERE clauses. Subject to
   90486 **        rules (11), (13) and (14), they may also contain ORDER BY,
   90487 **        LIMIT and OFFSET clauses.
   90488 **
   90489 **  (18)  If the sub-query is a compound select, then all terms of the
   90490 **        ORDER by clause of the parent must be simple references to
   90491 **        columns of the sub-query.
   90492 **
   90493 **  (19)  The subquery does not use LIMIT or the outer query does not
   90494 **        have a WHERE clause.
   90495 **
   90496 **  (20)  If the sub-query is a compound select, then it must not use
   90497 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
   90498 **        somewhat by saying that the terms of the ORDER BY clause must
   90499 **        appear as unmodified result columns in the outer query.  But
   90500 **        have other optimizations in mind to deal with that case.
   90501 **
   90502 ** In this routine, the "p" parameter is a pointer to the outer query.
   90503 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
   90504 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
   90505 **
   90506 ** If flattening is not attempted, this routine is a no-op and returns 0.
   90507 ** If flattening is attempted this routine returns 1.
   90508 **
   90509 ** All of the expression analysis must occur on both the outer query and
   90510 ** the subquery before this routine runs.
   90511 */
   90512 static int flattenSubquery(
   90513   Parse *pParse,       /* Parsing context */
   90514   Select *p,           /* The parent or outer SELECT statement */
   90515   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
   90516   int isAgg,           /* True if outer SELECT uses aggregate functions */
   90517   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
   90518 ){
   90519   const char *zSavedAuthContext = pParse->zAuthContext;
   90520   Select *pParent;
   90521   Select *pSub;       /* The inner query or "subquery" */
   90522   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
   90523   SrcList *pSrc;      /* The FROM clause of the outer query */
   90524   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   90525   ExprList *pList;    /* The result set of the outer query */
   90526   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   90527   int i;              /* Loop counter */
   90528   Expr *pWhere;                    /* The WHERE clause */
   90529   struct SrcList_item *pSubitem;   /* The subquery */
   90530   sqlite3 *db = pParse->db;
   90531 
   90532   /* Check to see if flattening is permitted.  Return 0 if not.
   90533   */
   90534   assert( p!=0 );
   90535   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
   90536   if( db->flags & SQLITE_QueryFlattener ) return 0;
   90537   pSrc = p->pSrc;
   90538   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
   90539   pSubitem = &pSrc->a[iFrom];
   90540   iParent = pSubitem->iCursor;
   90541   pSub = pSubitem->pSelect;
   90542   assert( pSub!=0 );
   90543   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
   90544   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
   90545   pSubSrc = pSub->pSrc;
   90546   assert( pSubSrc );
   90547   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
   90548   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
   90549   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
   90550   ** became arbitrary expressions, we were forced to add restrictions (13)
   90551   ** and (14). */
   90552   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
   90553   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
   90554   if( p->pRightmost && pSub->pLimit ){
   90555     return 0;                                            /* Restriction (15) */
   90556   }
   90557   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
   90558   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
   90559   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
   90560      return 0;         /* Restrictions (8)(9) */
   90561   }
   90562   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
   90563      return 0;         /* Restriction (6)  */
   90564   }
   90565   if( p->pOrderBy && pSub->pOrderBy ){
   90566      return 0;                                           /* Restriction (11) */
   90567   }
   90568   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
   90569   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
   90570 
   90571   /* OBSOLETE COMMENT 1:
   90572   ** Restriction 3:  If the subquery is a join, make sure the subquery is
   90573   ** not used as the right operand of an outer join.  Examples of why this
   90574   ** is not allowed:
   90575   **
   90576   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
   90577   **
   90578   ** If we flatten the above, we would get
   90579   **
   90580   **         (t1 LEFT OUTER JOIN t2) JOIN t3
   90581   **
   90582   ** which is not at all the same thing.
   90583   **
   90584   ** OBSOLETE COMMENT 2:
   90585   ** Restriction 12:  If the subquery is the right operand of a left outer
   90586   ** join, make sure the subquery has no WHERE clause.
   90587   ** An examples of why this is not allowed:
   90588   **
   90589   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
   90590   **
   90591   ** If we flatten the above, we would get
   90592   **
   90593   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
   90594   **
   90595   ** But the t2.x>0 test will always fail on a NULL row of t2, which
   90596   ** effectively converts the OUTER JOIN into an INNER JOIN.
   90597   **
   90598   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
   90599   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
   90600   ** is fraught with danger.  Best to avoid the whole thing.  If the
   90601   ** subquery is the right term of a LEFT JOIN, then do not flatten.
   90602   */
   90603   if( (pSubitem->jointype & JT_OUTER)!=0 ){
   90604     return 0;
   90605   }
   90606 
   90607   /* Restriction 17: If the sub-query is a compound SELECT, then it must
   90608   ** use only the UNION ALL operator. And none of the simple select queries
   90609   ** that make up the compound SELECT are allowed to be aggregate or distinct
   90610   ** queries.
   90611   */
   90612   if( pSub->pPrior ){
   90613     if( pSub->pOrderBy ){
   90614       return 0;  /* Restriction 20 */
   90615     }
   90616     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
   90617       return 0;
   90618     }
   90619     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
   90620       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
   90621       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
   90622       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
   90623        || (pSub1->pPrior && pSub1->op!=TK_ALL)
   90624        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
   90625       ){
   90626         return 0;
   90627       }
   90628     }
   90629 
   90630     /* Restriction 18. */
   90631     if( p->pOrderBy ){
   90632       int ii;
   90633       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
   90634         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
   90635       }
   90636     }
   90637   }
   90638 
   90639   /***** If we reach this point, flattening is permitted. *****/
   90640 
   90641   /* Authorize the subquery */
   90642   pParse->zAuthContext = pSubitem->zName;
   90643   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
   90644   pParse->zAuthContext = zSavedAuthContext;
   90645 
   90646   /* If the sub-query is a compound SELECT statement, then (by restrictions
   90647   ** 17 and 18 above) it must be a UNION ALL and the parent query must
   90648   ** be of the form:
   90649   **
   90650   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   90651   **
   90652   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
   90653   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   90654   ** OFFSET clauses and joins them to the left-hand-side of the original
   90655   ** using UNION ALL operators. In this case N is the number of simple
   90656   ** select statements in the compound sub-query.
   90657   **
   90658   ** Example:
   90659   **
   90660   **     SELECT a+1 FROM (
   90661   **        SELECT x FROM tab
   90662   **        UNION ALL
   90663   **        SELECT y FROM tab
   90664   **        UNION ALL
   90665   **        SELECT abs(z*2) FROM tab2
   90666   **     ) WHERE a!=5 ORDER BY 1
   90667   **
   90668   ** Transformed into:
   90669   **
   90670   **     SELECT x+1 FROM tab WHERE x+1!=5
   90671   **     UNION ALL
   90672   **     SELECT y+1 FROM tab WHERE y+1!=5
   90673   **     UNION ALL
   90674   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
   90675   **     ORDER BY 1
   90676   **
   90677   ** We call this the "compound-subquery flattening".
   90678   */
   90679   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
   90680     Select *pNew;
   90681     ExprList *pOrderBy = p->pOrderBy;
   90682     Expr *pLimit = p->pLimit;
   90683     Select *pPrior = p->pPrior;
   90684     p->pOrderBy = 0;
   90685     p->pSrc = 0;
   90686     p->pPrior = 0;
   90687     p->pLimit = 0;
   90688     pNew = sqlite3SelectDup(db, p, 0);
   90689     p->pLimit = pLimit;
   90690     p->pOrderBy = pOrderBy;
   90691     p->pSrc = pSrc;
   90692     p->op = TK_ALL;
   90693     p->pRightmost = 0;
   90694     if( pNew==0 ){
   90695       pNew = pPrior;
   90696     }else{
   90697       pNew->pPrior = pPrior;
   90698       pNew->pRightmost = 0;
   90699     }
   90700     p->pPrior = pNew;
   90701     if( db->mallocFailed ) return 1;
   90702   }
   90703 
   90704   /* Begin flattening the iFrom-th entry of the FROM clause
   90705   ** in the outer query.
   90706   */
   90707   pSub = pSub1 = pSubitem->pSelect;
   90708 
   90709   /* Delete the transient table structure associated with the
   90710   ** subquery
   90711   */
   90712   sqlite3DbFree(db, pSubitem->zDatabase);
   90713   sqlite3DbFree(db, pSubitem->zName);
   90714   sqlite3DbFree(db, pSubitem->zAlias);
   90715   pSubitem->zDatabase = 0;
   90716   pSubitem->zName = 0;
   90717   pSubitem->zAlias = 0;
   90718   pSubitem->pSelect = 0;
   90719 
   90720   /* Defer deleting the Table object associated with the
   90721   ** subquery until code generation is
   90722   ** complete, since there may still exist Expr.pTab entries that
   90723   ** refer to the subquery even after flattening.  Ticket #3346.
   90724   **
   90725   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
   90726   */
   90727   if( ALWAYS(pSubitem->pTab!=0) ){
   90728     Table *pTabToDel = pSubitem->pTab;
   90729     if( pTabToDel->nRef==1 ){
   90730       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   90731       pTabToDel->pNextZombie = pToplevel->pZombieTab;
   90732       pToplevel->pZombieTab = pTabToDel;
   90733     }else{
   90734       pTabToDel->nRef--;
   90735     }
   90736     pSubitem->pTab = 0;
   90737   }
   90738 
   90739   /* The following loop runs once for each term in a compound-subquery
   90740   ** flattening (as described above).  If we are doing a different kind
   90741   ** of flattening - a flattening other than a compound-subquery flattening -
   90742   ** then this loop only runs once.
   90743   **
   90744   ** This loop moves all of the FROM elements of the subquery into the
   90745   ** the FROM clause of the outer query.  Before doing this, remember
   90746   ** the cursor number for the original outer query FROM element in
   90747   ** iParent.  The iParent cursor will never be used.  Subsequent code
   90748   ** will scan expressions looking for iParent references and replace
   90749   ** those references with expressions that resolve to the subquery FROM
   90750   ** elements we are now copying in.
   90751   */
   90752   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
   90753     int nSubSrc;
   90754     u8 jointype = 0;
   90755     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
   90756     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
   90757     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
   90758 
   90759     if( pSrc ){
   90760       assert( pParent==p );  /* First time through the loop */
   90761       jointype = pSubitem->jointype;
   90762     }else{
   90763       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
   90764       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
   90765       if( pSrc==0 ){
   90766         assert( db->mallocFailed );
   90767         break;
   90768       }
   90769     }
   90770 
   90771     /* The subquery uses a single slot of the FROM clause of the outer
   90772     ** query.  If the subquery has more than one element in its FROM clause,
   90773     ** then expand the outer query to make space for it to hold all elements
   90774     ** of the subquery.
   90775     **
   90776     ** Example:
   90777     **
   90778     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
   90779     **
   90780     ** The outer query has 3 slots in its FROM clause.  One slot of the
   90781     ** outer query (the middle slot) is used by the subquery.  The next
   90782     ** block of code will expand the out query to 4 slots.  The middle
   90783     ** slot is expanded to two slots in order to make space for the
   90784     ** two elements in the FROM clause of the subquery.
   90785     */
   90786     if( nSubSrc>1 ){
   90787       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
   90788       if( db->mallocFailed ){
   90789         break;
   90790       }
   90791     }
   90792 
   90793     /* Transfer the FROM clause terms from the subquery into the
   90794     ** outer query.
   90795     */
   90796     for(i=0; i<nSubSrc; i++){
   90797       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
   90798       pSrc->a[i+iFrom] = pSubSrc->a[i];
   90799       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
   90800     }
   90801     pSrc->a[iFrom].jointype = jointype;
   90802 
   90803     /* Now begin substituting subquery result set expressions for
   90804     ** references to the iParent in the outer query.
   90805     **
   90806     ** Example:
   90807     **
   90808     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
   90809     **   \                     \_____________ subquery __________/          /
   90810     **    \_____________________ outer query ______________________________/
   90811     **
   90812     ** We look at every expression in the outer query and every place we see
   90813     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
   90814     */
   90815     pList = pParent->pEList;
   90816     for(i=0; i<pList->nExpr; i++){
   90817       if( pList->a[i].zName==0 ){
   90818         const char *zSpan = pList->a[i].zSpan;
   90819         if( ALWAYS(zSpan) ){
   90820           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
   90821         }
   90822       }
   90823     }
   90824     substExprList(db, pParent->pEList, iParent, pSub->pEList);
   90825     if( isAgg ){
   90826       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
   90827       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   90828     }
   90829     if( pSub->pOrderBy ){
   90830       assert( pParent->pOrderBy==0 );
   90831       pParent->pOrderBy = pSub->pOrderBy;
   90832       pSub->pOrderBy = 0;
   90833     }else if( pParent->pOrderBy ){
   90834       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
   90835     }
   90836     if( pSub->pWhere ){
   90837       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
   90838     }else{
   90839       pWhere = 0;
   90840     }
   90841     if( subqueryIsAgg ){
   90842       assert( pParent->pHaving==0 );
   90843       pParent->pHaving = pParent->pWhere;
   90844       pParent->pWhere = pWhere;
   90845       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
   90846       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
   90847                                   sqlite3ExprDup(db, pSub->pHaving, 0));
   90848       assert( pParent->pGroupBy==0 );
   90849       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
   90850     }else{
   90851       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
   90852       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
   90853     }
   90854 
   90855     /* The flattened query is distinct if either the inner or the
   90856     ** outer query is distinct.
   90857     */
   90858     pParent->selFlags |= pSub->selFlags & SF_Distinct;
   90859 
   90860     /*
   90861     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
   90862     **
   90863     ** One is tempted to try to add a and b to combine the limits.  But this
   90864     ** does not work if either limit is negative.
   90865     */
   90866     if( pSub->pLimit ){
   90867       pParent->pLimit = pSub->pLimit;
   90868       pSub->pLimit = 0;
   90869     }
   90870   }
   90871 
   90872   /* Finially, delete what is left of the subquery and return
   90873   ** success.
   90874   */
   90875   sqlite3SelectDelete(db, pSub1);
   90876 
   90877   return 1;
   90878 }
   90879 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
   90880 
   90881 /*
   90882 ** Analyze the SELECT statement passed as an argument to see if it
   90883 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
   90884 ** it is, or 0 otherwise. At present, a query is considered to be
   90885 ** a min()/max() query if:
   90886 **
   90887 **   1. There is a single object in the FROM clause.
   90888 **
   90889 **   2. There is a single expression in the result set, and it is
   90890 **      either min(x) or max(x), where x is a column reference.
   90891 */
   90892 static u8 minMaxQuery(Select *p){
   90893   Expr *pExpr;
   90894   ExprList *pEList = p->pEList;
   90895 
   90896   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
   90897   pExpr = pEList->a[0].pExpr;
   90898   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   90899   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
   90900   pEList = pExpr->x.pList;
   90901   if( pEList==0 || pEList->nExpr!=1 ) return 0;
   90902   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
   90903   assert( !ExprHasProperty(pExpr, EP_IntValue) );
   90904   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
   90905     return WHERE_ORDERBY_MIN;
   90906   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
   90907     return WHERE_ORDERBY_MAX;
   90908   }
   90909   return WHERE_ORDERBY_NORMAL;
   90910 }
   90911 
   90912 /*
   90913 ** The select statement passed as the first argument is an aggregate query.
   90914 ** The second argment is the associated aggregate-info object. This
   90915 ** function tests if the SELECT is of the form:
   90916 **
   90917 **   SELECT count(*) FROM <tbl>
   90918 **
   90919 ** where table is a database table, not a sub-select or view. If the query
   90920 ** does match this pattern, then a pointer to the Table object representing
   90921 ** <tbl> is returned. Otherwise, 0 is returned.
   90922 */
   90923 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
   90924   Table *pTab;
   90925   Expr *pExpr;
   90926 
   90927   assert( !p->pGroupBy );
   90928 
   90929   if( p->pWhere || p->pEList->nExpr!=1
   90930    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   90931   ){
   90932     return 0;
   90933   }
   90934   pTab = p->pSrc->a[0].pTab;
   90935   pExpr = p->pEList->a[0].pExpr;
   90936   assert( pTab && !pTab->pSelect && pExpr );
   90937 
   90938   if( IsVirtual(pTab) ) return 0;
   90939   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
   90940   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
   90941   if( pExpr->flags&EP_Distinct ) return 0;
   90942 
   90943   return pTab;
   90944 }
   90945 
   90946 /*
   90947 ** If the source-list item passed as an argument was augmented with an
   90948 ** INDEXED BY clause, then try to locate the specified index. If there
   90949 ** was such a clause and the named index cannot be found, return
   90950 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
   90951 ** pFrom->pIndex and return SQLITE_OK.
   90952 */
   90953 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
   90954   if( pFrom->pTab && pFrom->zIndex ){
   90955     Table *pTab = pFrom->pTab;
   90956     char *zIndex = pFrom->zIndex;
   90957     Index *pIdx;
   90958     for(pIdx=pTab->pIndex;
   90959         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
   90960         pIdx=pIdx->pNext
   90961     );
   90962     if( !pIdx ){
   90963       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
   90964       pParse->checkSchema = 1;
   90965       return SQLITE_ERROR;
   90966     }
   90967     pFrom->pIndex = pIdx;
   90968   }
   90969   return SQLITE_OK;
   90970 }
   90971 
   90972 /*
   90973 ** This routine is a Walker callback for "expanding" a SELECT statement.
   90974 ** "Expanding" means to do the following:
   90975 **
   90976 **    (1)  Make sure VDBE cursor numbers have been assigned to every
   90977 **         element of the FROM clause.
   90978 **
   90979 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
   90980 **         defines FROM clause.  When views appear in the FROM clause,
   90981 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
   90982 **         that implements the view.  A copy is made of the view's SELECT
   90983 **         statement so that we can freely modify or delete that statement
   90984 **         without worrying about messing up the presistent representation
   90985 **         of the view.
   90986 **
   90987 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
   90988 **         on joins and the ON and USING clause of joins.
   90989 **
   90990 **    (4)  Scan the list of columns in the result set (pEList) looking
   90991 **         for instances of the "*" operator or the TABLE.* operator.
   90992 **         If found, expand each "*" to be every column in every table
   90993 **         and TABLE.* to be every column in TABLE.
   90994 **
   90995 */
   90996 static int selectExpander(Walker *pWalker, Select *p){
   90997   Parse *pParse = pWalker->pParse;
   90998   int i, j, k;
   90999   SrcList *pTabList;
   91000   ExprList *pEList;
   91001   struct SrcList_item *pFrom;
   91002   sqlite3 *db = pParse->db;
   91003 
   91004   if( db->mallocFailed  ){
   91005     return WRC_Abort;
   91006   }
   91007   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
   91008     return WRC_Prune;
   91009   }
   91010   p->selFlags |= SF_Expanded;
   91011   pTabList = p->pSrc;
   91012   pEList = p->pEList;
   91013 
   91014   /* Make sure cursor numbers have been assigned to all entries in
   91015   ** the FROM clause of the SELECT statement.
   91016   */
   91017   sqlite3SrcListAssignCursors(pParse, pTabList);
   91018 
   91019   /* Look up every table named in the FROM clause of the select.  If
   91020   ** an entry of the FROM clause is a subquery instead of a table or view,
   91021   ** then create a transient table structure to describe the subquery.
   91022   */
   91023   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   91024     Table *pTab;
   91025     if( pFrom->pTab!=0 ){
   91026       /* This statement has already been prepared.  There is no need
   91027       ** to go further. */
   91028       assert( i==0 );
   91029       return WRC_Prune;
   91030     }
   91031     if( pFrom->zName==0 ){
   91032 #ifndef SQLITE_OMIT_SUBQUERY
   91033       Select *pSel = pFrom->pSelect;
   91034       /* A sub-query in the FROM clause of a SELECT */
   91035       assert( pSel!=0 );
   91036       assert( pFrom->pTab==0 );
   91037       sqlite3WalkSelect(pWalker, pSel);
   91038       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
   91039       if( pTab==0 ) return WRC_Abort;
   91040       pTab->nRef = 1;
   91041       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
   91042       while( pSel->pPrior ){ pSel = pSel->pPrior; }
   91043       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
   91044       pTab->iPKey = -1;
   91045       pTab->nRowEst = 1000000;
   91046       pTab->tabFlags |= TF_Ephemeral;
   91047 #endif
   91048     }else{
   91049       /* An ordinary table or view name in the FROM clause */
   91050       assert( pFrom->pTab==0 );
   91051       pFrom->pTab = pTab =
   91052         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
   91053       if( pTab==0 ) return WRC_Abort;
   91054       pTab->nRef++;
   91055 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
   91056       if( pTab->pSelect || IsVirtual(pTab) ){
   91057         /* We reach here if the named table is a really a view */
   91058         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
   91059         assert( pFrom->pSelect==0 );
   91060         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
   91061         sqlite3WalkSelect(pWalker, pFrom->pSelect);
   91062       }
   91063 #endif
   91064     }
   91065 
   91066     /* Locate the index named by the INDEXED BY clause, if any. */
   91067     if( sqlite3IndexedByLookup(pParse, pFrom) ){
   91068       return WRC_Abort;
   91069     }
   91070   }
   91071 
   91072   /* Process NATURAL keywords, and ON and USING clauses of joins.
   91073   */
   91074   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
   91075     return WRC_Abort;
   91076   }
   91077 
   91078   /* For every "*" that occurs in the column list, insert the names of
   91079   ** all columns in all tables.  And for every TABLE.* insert the names
   91080   ** of all columns in TABLE.  The parser inserted a special expression
   91081   ** with the TK_ALL operator for each "*" that it found in the column list.
   91082   ** The following code just has to locate the TK_ALL expressions and expand
   91083   ** each one to the list of all columns in all tables.
   91084   **
   91085   ** The first loop just checks to see if there are any "*" operators
   91086   ** that need expanding.
   91087   */
   91088   for(k=0; k<pEList->nExpr; k++){
   91089     Expr *pE = pEList->a[k].pExpr;
   91090     if( pE->op==TK_ALL ) break;
   91091     assert( pE->op!=TK_DOT || pE->pRight!=0 );
   91092     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
   91093     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
   91094   }
   91095   if( k<pEList->nExpr ){
   91096     /*
   91097     ** If we get here it means the result set contains one or more "*"
   91098     ** operators that need to be expanded.  Loop through each expression
   91099     ** in the result set and expand them one by one.
   91100     */
   91101     struct ExprList_item *a = pEList->a;
   91102     ExprList *pNew = 0;
   91103     int flags = pParse->db->flags;
   91104     int longNames = (flags & SQLITE_FullColNames)!=0
   91105                       && (flags & SQLITE_ShortColNames)==0;
   91106 
   91107     for(k=0; k<pEList->nExpr; k++){
   91108       Expr *pE = a[k].pExpr;
   91109       assert( pE->op!=TK_DOT || pE->pRight!=0 );
   91110       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
   91111         /* This particular expression does not need to be expanded.
   91112         */
   91113         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
   91114         if( pNew ){
   91115           pNew->a[pNew->nExpr-1].zName = a[k].zName;
   91116           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
   91117           a[k].zName = 0;
   91118           a[k].zSpan = 0;
   91119         }
   91120         a[k].pExpr = 0;
   91121       }else{
   91122         /* This expression is a "*" or a "TABLE.*" and needs to be
   91123         ** expanded. */
   91124         int tableSeen = 0;      /* Set to 1 when TABLE matches */
   91125         char *zTName;            /* text of name of TABLE */
   91126         if( pE->op==TK_DOT ){
   91127           assert( pE->pLeft!=0 );
   91128           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
   91129           zTName = pE->pLeft->u.zToken;
   91130         }else{
   91131           zTName = 0;
   91132         }
   91133         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   91134           Table *pTab = pFrom->pTab;
   91135           char *zTabName = pFrom->zAlias;
   91136           if( zTabName==0 ){
   91137             zTabName = pTab->zName;
   91138           }
   91139           if( db->mallocFailed ) break;
   91140           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
   91141             continue;
   91142           }
   91143           tableSeen = 1;
   91144           for(j=0; j<pTab->nCol; j++){
   91145             Expr *pExpr, *pRight;
   91146             char *zName = pTab->aCol[j].zName;
   91147             char *zColname;  /* The computed column name */
   91148             char *zToFree;   /* Malloced string that needs to be freed */
   91149             Token sColname;  /* Computed column name as a token */
   91150 
   91151             /* If a column is marked as 'hidden' (currently only possible
   91152             ** for virtual tables), do not include it in the expanded
   91153             ** result-set list.
   91154             */
   91155             if( IsHiddenColumn(&pTab->aCol[j]) ){
   91156               assert(IsVirtual(pTab));
   91157               continue;
   91158             }
   91159 
   91160             if( i>0 && zTName==0 ){
   91161               if( (pFrom->jointype & JT_NATURAL)!=0
   91162                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
   91163               ){
   91164                 /* In a NATURAL join, omit the join columns from the
   91165                 ** table to the right of the join */
   91166                 continue;
   91167               }
   91168               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
   91169                 /* In a join with a USING clause, omit columns in the
   91170                 ** using clause from the table on the right. */
   91171                 continue;
   91172               }
   91173             }
   91174             pRight = sqlite3Expr(db, TK_ID, zName);
   91175             zColname = zName;
   91176             zToFree = 0;
   91177             if( longNames || pTabList->nSrc>1 ){
   91178               Expr *pLeft;
   91179               pLeft = sqlite3Expr(db, TK_ID, zTabName);
   91180               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   91181               if( longNames ){
   91182                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
   91183                 zToFree = zColname;
   91184               }
   91185             }else{
   91186               pExpr = pRight;
   91187             }
   91188             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
   91189             sColname.z = zColname;
   91190             sColname.n = sqlite3Strlen30(zColname);
   91191             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
   91192             sqlite3DbFree(db, zToFree);
   91193           }
   91194         }
   91195         if( !tableSeen ){
   91196           if( zTName ){
   91197             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
   91198           }else{
   91199             sqlite3ErrorMsg(pParse, "no tables specified");
   91200           }
   91201         }
   91202       }
   91203     }
   91204     sqlite3ExprListDelete(db, pEList);
   91205     p->pEList = pNew;
   91206   }
   91207 #if SQLITE_MAX_COLUMN
   91208   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
   91209     sqlite3ErrorMsg(pParse, "too many columns in result set");
   91210   }
   91211 #endif
   91212   return WRC_Continue;
   91213 }
   91214 
   91215 /*
   91216 ** No-op routine for the parse-tree walker.
   91217 **
   91218 ** When this routine is the Walker.xExprCallback then expression trees
   91219 ** are walked without any actions being taken at each node.  Presumably,
   91220 ** when this routine is used for Walker.xExprCallback then
   91221 ** Walker.xSelectCallback is set to do something useful for every
   91222 ** subquery in the parser tree.
   91223 */
   91224 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
   91225   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   91226   return WRC_Continue;
   91227 }
   91228 
   91229 /*
   91230 ** This routine "expands" a SELECT statement and all of its subqueries.
   91231 ** For additional information on what it means to "expand" a SELECT
   91232 ** statement, see the comment on the selectExpand worker callback above.
   91233 **
   91234 ** Expanding a SELECT statement is the first step in processing a
   91235 ** SELECT statement.  The SELECT statement must be expanded before
   91236 ** name resolution is performed.
   91237 **
   91238 ** If anything goes wrong, an error message is written into pParse.
   91239 ** The calling function can detect the problem by looking at pParse->nErr
   91240 ** and/or pParse->db->mallocFailed.
   91241 */
   91242 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
   91243   Walker w;
   91244   w.xSelectCallback = selectExpander;
   91245   w.xExprCallback = exprWalkNoop;
   91246   w.pParse = pParse;
   91247   sqlite3WalkSelect(&w, pSelect);
   91248 }
   91249 
   91250 
   91251 #ifndef SQLITE_OMIT_SUBQUERY
   91252 /*
   91253 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
   91254 ** interface.
   91255 **
   91256 ** For each FROM-clause subquery, add Column.zType and Column.zColl
   91257 ** information to the Table structure that represents the result set
   91258 ** of that subquery.
   91259 **
   91260 ** The Table structure that represents the result set was constructed
   91261 ** by selectExpander() but the type and collation information was omitted
   91262 ** at that point because identifiers had not yet been resolved.  This
   91263 ** routine is called after identifier resolution.
   91264 */
   91265 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
   91266   Parse *pParse;
   91267   int i;
   91268   SrcList *pTabList;
   91269   struct SrcList_item *pFrom;
   91270 
   91271   assert( p->selFlags & SF_Resolved );
   91272   if( (p->selFlags & SF_HasTypeInfo)==0 ){
   91273     p->selFlags |= SF_HasTypeInfo;
   91274     pParse = pWalker->pParse;
   91275     pTabList = p->pSrc;
   91276     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
   91277       Table *pTab = pFrom->pTab;
   91278       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
   91279         /* A sub-query in the FROM clause of a SELECT */
   91280         Select *pSel = pFrom->pSelect;
   91281         assert( pSel );
   91282         while( pSel->pPrior ) pSel = pSel->pPrior;
   91283         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
   91284       }
   91285     }
   91286   }
   91287   return WRC_Continue;
   91288 }
   91289 #endif
   91290 
   91291 
   91292 /*
   91293 ** This routine adds datatype and collating sequence information to
   91294 ** the Table structures of all FROM-clause subqueries in a
   91295 ** SELECT statement.
   91296 **
   91297 ** Use this routine after name resolution.
   91298 */
   91299 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
   91300 #ifndef SQLITE_OMIT_SUBQUERY
   91301   Walker w;
   91302   w.xSelectCallback = selectAddSubqueryTypeInfo;
   91303   w.xExprCallback = exprWalkNoop;
   91304   w.pParse = pParse;
   91305   sqlite3WalkSelect(&w, pSelect);
   91306 #endif
   91307 }
   91308 
   91309 
   91310 /*
   91311 ** This routine sets of a SELECT statement for processing.  The
   91312 ** following is accomplished:
   91313 **
   91314 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
   91315 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
   91316 **     *  ON and USING clauses are shifted into WHERE statements
   91317 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
   91318 **     *  Identifiers in expression are matched to tables.
   91319 **
   91320 ** This routine acts recursively on all subqueries within the SELECT.
   91321 */
   91322 SQLITE_PRIVATE void sqlite3SelectPrep(
   91323   Parse *pParse,         /* The parser context */
   91324   Select *p,             /* The SELECT statement being coded. */
   91325   NameContext *pOuterNC  /* Name context for container */
   91326 ){
   91327   sqlite3 *db;
   91328   if( NEVER(p==0) ) return;
   91329   db = pParse->db;
   91330   if( p->selFlags & SF_HasTypeInfo ) return;
   91331   sqlite3SelectExpand(pParse, p);
   91332   if( pParse->nErr || db->mallocFailed ) return;
   91333   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
   91334   if( pParse->nErr || db->mallocFailed ) return;
   91335   sqlite3SelectAddTypeInfo(pParse, p);
   91336 }
   91337 
   91338 /*
   91339 ** Reset the aggregate accumulator.
   91340 **
   91341 ** The aggregate accumulator is a set of memory cells that hold
   91342 ** intermediate results while calculating an aggregate.  This
   91343 ** routine simply stores NULLs in all of those memory cells.
   91344 */
   91345 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   91346   Vdbe *v = pParse->pVdbe;
   91347   int i;
   91348   struct AggInfo_func *pFunc;
   91349   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
   91350     return;
   91351   }
   91352   for(i=0; i<pAggInfo->nColumn; i++){
   91353     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
   91354   }
   91355   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
   91356     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
   91357     if( pFunc->iDistinct>=0 ){
   91358       Expr *pE = pFunc->pExpr;
   91359       assert( !ExprHasProperty(pE, EP_xIsSelect) );
   91360       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
   91361         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
   91362            "argument");
   91363         pFunc->iDistinct = -1;
   91364       }else{
   91365         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
   91366         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
   91367                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   91368       }
   91369     }
   91370   }
   91371 }
   91372 
   91373 /*
   91374 ** Invoke the OP_AggFinalize opcode for every aggregate function
   91375 ** in the AggInfo structure.
   91376 */
   91377 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   91378   Vdbe *v = pParse->pVdbe;
   91379   int i;
   91380   struct AggInfo_func *pF;
   91381   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   91382     ExprList *pList = pF->pExpr->x.pList;
   91383     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   91384     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
   91385                       (void*)pF->pFunc, P4_FUNCDEF);
   91386   }
   91387 }
   91388 
   91389 /*
   91390 ** Update the accumulator memory cells for an aggregate based on
   91391 ** the current cursor position.
   91392 */
   91393 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
   91394   Vdbe *v = pParse->pVdbe;
   91395   int i;
   91396   struct AggInfo_func *pF;
   91397   struct AggInfo_col *pC;
   91398 
   91399   pAggInfo->directMode = 1;
   91400   sqlite3ExprCacheClear(pParse);
   91401   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
   91402     int nArg;
   91403     int addrNext = 0;
   91404     int regAgg;
   91405     ExprList *pList = pF->pExpr->x.pList;
   91406     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
   91407     if( pList ){
   91408       nArg = pList->nExpr;
   91409       regAgg = sqlite3GetTempRange(pParse, nArg);
   91410       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
   91411     }else{
   91412       nArg = 0;
   91413       regAgg = 0;
   91414     }
   91415     if( pF->iDistinct>=0 ){
   91416       addrNext = sqlite3VdbeMakeLabel(v);
   91417       assert( nArg==1 );
   91418       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
   91419     }
   91420     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
   91421       CollSeq *pColl = 0;
   91422       struct ExprList_item *pItem;
   91423       int j;
   91424       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
   91425       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
   91426         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   91427       }
   91428       if( !pColl ){
   91429         pColl = pParse->db->pDfltColl;
   91430       }
   91431       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
   91432     }
   91433     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
   91434                       (void*)pF->pFunc, P4_FUNCDEF);
   91435     sqlite3VdbeChangeP5(v, (u8)nArg);
   91436     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
   91437     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
   91438     if( addrNext ){
   91439       sqlite3VdbeResolveLabel(v, addrNext);
   91440       sqlite3ExprCacheClear(pParse);
   91441     }
   91442   }
   91443 
   91444   /* Before populating the accumulator registers, clear the column cache.
   91445   ** Otherwise, if any of the required column values are already present
   91446   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
   91447   ** to pC->iMem. But by the time the value is used, the original register
   91448   ** may have been used, invalidating the underlying buffer holding the
   91449   ** text or blob value. See ticket [883034dcb5].
   91450   **
   91451   ** Another solution would be to change the OP_SCopy used to copy cached
   91452   ** values to an OP_Copy.
   91453   */
   91454   sqlite3ExprCacheClear(pParse);
   91455   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
   91456     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
   91457   }
   91458   pAggInfo->directMode = 0;
   91459   sqlite3ExprCacheClear(pParse);
   91460 }
   91461 
   91462 /*
   91463 ** Generate code for the SELECT statement given in the p argument.
   91464 **
   91465 ** The results are distributed in various ways depending on the
   91466 ** contents of the SelectDest structure pointed to by argument pDest
   91467 ** as follows:
   91468 **
   91469 **     pDest->eDest    Result
   91470 **     ------------    -------------------------------------------
   91471 **     SRT_Output      Generate a row of output (using the OP_ResultRow
   91472 **                     opcode) for each row in the result set.
   91473 **
   91474 **     SRT_Mem         Only valid if the result is a single column.
   91475 **                     Store the first column of the first result row
   91476 **                     in register pDest->iParm then abandon the rest
   91477 **                     of the query.  This destination implies "LIMIT 1".
   91478 **
   91479 **     SRT_Set         The result must be a single column.  Store each
   91480 **                     row of result as the key in table pDest->iParm.
   91481 **                     Apply the affinity pDest->affinity before storing
   91482 **                     results.  Used to implement "IN (SELECT ...)".
   91483 **
   91484 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
   91485 **
   91486 **     SRT_Except      Remove results from the temporary table pDest->iParm.
   91487 **
   91488 **     SRT_Table       Store results in temporary table pDest->iParm.
   91489 **                     This is like SRT_EphemTab except that the table
   91490 **                     is assumed to already be open.
   91491 **
   91492 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
   91493 **                     the result there. The cursor is left open after
   91494 **                     returning.  This is like SRT_Table except that
   91495 **                     this destination uses OP_OpenEphemeral to create
   91496 **                     the table first.
   91497 **
   91498 **     SRT_Coroutine   Generate a co-routine that returns a new row of
   91499 **                     results each time it is invoked.  The entry point
   91500 **                     of the co-routine is stored in register pDest->iParm.
   91501 **
   91502 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
   91503 **                     set is not empty.
   91504 **
   91505 **     SRT_Discard     Throw the results away.  This is used by SELECT
   91506 **                     statements within triggers whose only purpose is
   91507 **                     the side-effects of functions.
   91508 **
   91509 ** This routine returns the number of errors.  If any errors are
   91510 ** encountered, then an appropriate error message is left in
   91511 ** pParse->zErrMsg.
   91512 **
   91513 ** This routine does NOT free the Select structure passed in.  The
   91514 ** calling function needs to do that.
   91515 */
   91516 SQLITE_PRIVATE int sqlite3Select(
   91517   Parse *pParse,         /* The parser context */
   91518   Select *p,             /* The SELECT statement being coded. */
   91519   SelectDest *pDest      /* What to do with the query results */
   91520 ){
   91521   int i, j;              /* Loop counters */
   91522   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
   91523   Vdbe *v;               /* The virtual machine under construction */
   91524   int isAgg;             /* True for select lists like "count(*)" */
   91525   ExprList *pEList;      /* List of columns to extract. */
   91526   SrcList *pTabList;     /* List of tables to select from */
   91527   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   91528   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
   91529   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   91530   Expr *pHaving;         /* The HAVING clause.  May be NULL */
   91531   int isDistinct;        /* True if the DISTINCT keyword is present */
   91532   int distinct;          /* Table to use for the distinct set */
   91533   int rc = 1;            /* Value to return from this function */
   91534   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
   91535   AggInfo sAggInfo;      /* Information used by aggregate queries */
   91536   int iEnd;              /* Address of the end of the query */
   91537   sqlite3 *db;           /* The database connection */
   91538 
   91539 #ifndef SQLITE_OMIT_EXPLAIN
   91540   int iRestoreSelectId = pParse->iSelectId;
   91541   pParse->iSelectId = pParse->iNextSelectId++;
   91542 #endif
   91543 
   91544   db = pParse->db;
   91545   if( p==0 || db->mallocFailed || pParse->nErr ){
   91546     return 1;
   91547   }
   91548   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
   91549   memset(&sAggInfo, 0, sizeof(sAggInfo));
   91550 
   91551   if( IgnorableOrderby(pDest) ){
   91552     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
   91553            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
   91554     /* If ORDER BY makes no difference in the output then neither does
   91555     ** DISTINCT so it can be removed too. */
   91556     sqlite3ExprListDelete(db, p->pOrderBy);
   91557     p->pOrderBy = 0;
   91558     p->selFlags &= ~SF_Distinct;
   91559   }
   91560   sqlite3SelectPrep(pParse, p, 0);
   91561   pOrderBy = p->pOrderBy;
   91562   pTabList = p->pSrc;
   91563   pEList = p->pEList;
   91564   if( pParse->nErr || db->mallocFailed ){
   91565     goto select_end;
   91566   }
   91567   isAgg = (p->selFlags & SF_Aggregate)!=0;
   91568   assert( pEList!=0 );
   91569 
   91570   /* Begin generating code.
   91571   */
   91572   v = sqlite3GetVdbe(pParse);
   91573   if( v==0 ) goto select_end;
   91574 
   91575   /* If writing to memory or generating a set
   91576   ** only a single column may be output.
   91577   */
   91578 #ifndef SQLITE_OMIT_SUBQUERY
   91579   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   91580     goto select_end;
   91581   }
   91582 #endif
   91583 
   91584   /* Generate code for all sub-queries in the FROM clause
   91585   */
   91586 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
   91587   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
   91588     struct SrcList_item *pItem = &pTabList->a[i];
   91589     SelectDest dest;
   91590     Select *pSub = pItem->pSelect;
   91591     int isAggSub;
   91592 
   91593     if( pSub==0 || pItem->isPopulated ) continue;
   91594 
   91595     /* Increment Parse.nHeight by the height of the largest expression
   91596     ** tree refered to by this, the parent select. The child select
   91597     ** may contain expression trees of at most
   91598     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
   91599     ** more conservative than necessary, but much easier than enforcing
   91600     ** an exact limit.
   91601     */
   91602     pParse->nHeight += sqlite3SelectExprHeight(p);
   91603 
   91604     /* Check to see if the subquery can be absorbed into the parent. */
   91605     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
   91606     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
   91607       if( isAggSub ){
   91608         isAgg = 1;
   91609         p->selFlags |= SF_Aggregate;
   91610       }
   91611       i = -1;
   91612     }else{
   91613       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
   91614       assert( pItem->isPopulated==0 );
   91615       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
   91616       sqlite3Select(pParse, pSub, &dest);
   91617       pItem->isPopulated = 1;
   91618       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
   91619     }
   91620     if( /*pParse->nErr ||*/ db->mallocFailed ){
   91621       goto select_end;
   91622     }
   91623     pParse->nHeight -= sqlite3SelectExprHeight(p);
   91624     pTabList = p->pSrc;
   91625     if( !IgnorableOrderby(pDest) ){
   91626       pOrderBy = p->pOrderBy;
   91627     }
   91628   }
   91629   pEList = p->pEList;
   91630 #endif
   91631   pWhere = p->pWhere;
   91632   pGroupBy = p->pGroupBy;
   91633   pHaving = p->pHaving;
   91634   isDistinct = (p->selFlags & SF_Distinct)!=0;
   91635 
   91636 #ifndef SQLITE_OMIT_COMPOUND_SELECT
   91637   /* If there is are a sequence of queries, do the earlier ones first.
   91638   */
   91639   if( p->pPrior ){
   91640     if( p->pRightmost==0 ){
   91641       Select *pLoop, *pRight = 0;
   91642       int cnt = 0;
   91643       int mxSelect;
   91644       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
   91645         pLoop->pRightmost = p;
   91646         pLoop->pNext = pRight;
   91647         pRight = pLoop;
   91648       }
   91649       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
   91650       if( mxSelect && cnt>mxSelect ){
   91651         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
   91652         goto select_end;
   91653       }
   91654     }
   91655     rc = multiSelect(pParse, p, pDest);
   91656     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   91657     return rc;
   91658   }
   91659 #endif
   91660 
   91661   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
   91662   ** GROUP BY might use an index, DISTINCT never does.
   91663   */
   91664   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
   91665   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
   91666     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
   91667     pGroupBy = p->pGroupBy;
   91668     p->selFlags &= ~SF_Distinct;
   91669   }
   91670 
   91671   /* If there is both a GROUP BY and an ORDER BY clause and they are
   91672   ** identical, then disable the ORDER BY clause since the GROUP BY
   91673   ** will cause elements to come out in the correct order.  This is
   91674   ** an optimization - the correct answer should result regardless.
   91675   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
   91676   ** to disable this optimization for testing purposes.
   91677   */
   91678   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
   91679          && (db->flags & SQLITE_GroupByOrder)==0 ){
   91680     pOrderBy = 0;
   91681   }
   91682 
   91683   /* If there is an ORDER BY clause, then this sorting
   91684   ** index might end up being unused if the data can be
   91685   ** extracted in pre-sorted order.  If that is the case, then the
   91686   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
   91687   ** we figure out that the sorting index is not needed.  The addrSortIndex
   91688   ** variable is used to facilitate that change.
   91689   */
   91690   if( pOrderBy ){
   91691     KeyInfo *pKeyInfo;
   91692     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
   91693     pOrderBy->iECursor = pParse->nTab++;
   91694     p->addrOpenEphm[2] = addrSortIndex =
   91695       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   91696                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
   91697                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   91698   }else{
   91699     addrSortIndex = -1;
   91700   }
   91701 
   91702   /* If the output is destined for a temporary table, open that table.
   91703   */
   91704   if( pDest->eDest==SRT_EphemTab ){
   91705     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
   91706   }
   91707 
   91708   /* Set the limiter.
   91709   */
   91710   iEnd = sqlite3VdbeMakeLabel(v);
   91711   p->nSelectRow = (double)LARGEST_INT64;
   91712   computeLimitRegisters(pParse, p, iEnd);
   91713 
   91714   /* Open a virtual index to use for the distinct set.
   91715   */
   91716   if( p->selFlags & SF_Distinct ){
   91717     KeyInfo *pKeyInfo;
   91718     assert( isAgg || pGroupBy );
   91719     distinct = pParse->nTab++;
   91720     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
   91721     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
   91722                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   91723     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   91724   }else{
   91725     distinct = -1;
   91726   }
   91727 
   91728   /* Aggregate and non-aggregate queries are handled differently */
   91729   if( !isAgg && pGroupBy==0 ){
   91730     /* This case is for non-aggregate queries
   91731     ** Begin the database scan
   91732     */
   91733     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
   91734     if( pWInfo==0 ) goto select_end;
   91735     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
   91736 
   91737     /* If sorting index that was created by a prior OP_OpenEphemeral
   91738     ** instruction ended up not being needed, then change the OP_OpenEphemeral
   91739     ** into an OP_Noop.
   91740     */
   91741     if( addrSortIndex>=0 && pOrderBy==0 ){
   91742       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
   91743       p->addrOpenEphm[2] = -1;
   91744     }
   91745 
   91746     /* Use the standard inner loop
   91747     */
   91748     assert(!isDistinct);
   91749     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
   91750                     pWInfo->iContinue, pWInfo->iBreak);
   91751 
   91752     /* End the database scan loop.
   91753     */
   91754     sqlite3WhereEnd(pWInfo);
   91755   }else{
   91756     /* This is the processing for aggregate queries */
   91757     NameContext sNC;    /* Name context for processing aggregate information */
   91758     int iAMem;          /* First Mem address for storing current GROUP BY */
   91759     int iBMem;          /* First Mem address for previous GROUP BY */
   91760     int iUseFlag;       /* Mem address holding flag indicating that at least
   91761                         ** one row of the input to the aggregator has been
   91762                         ** processed */
   91763     int iAbortFlag;     /* Mem address which causes query abort if positive */
   91764     int groupBySort;    /* Rows come from source in GROUP BY order */
   91765     int addrEnd;        /* End of processing for this SELECT */
   91766 
   91767     /* Remove any and all aliases between the result set and the
   91768     ** GROUP BY clause.
   91769     */
   91770     if( pGroupBy ){
   91771       int k;                        /* Loop counter */
   91772       struct ExprList_item *pItem;  /* For looping over expression in a list */
   91773 
   91774       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
   91775         pItem->iAlias = 0;
   91776       }
   91777       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
   91778         pItem->iAlias = 0;
   91779       }
   91780       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
   91781     }else{
   91782       p->nSelectRow = (double)1;
   91783     }
   91784 
   91785 
   91786     /* Create a label to jump to when we want to abort the query */
   91787     addrEnd = sqlite3VdbeMakeLabel(v);
   91788 
   91789     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
   91790     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
   91791     ** SELECT statement.
   91792     */
   91793     memset(&sNC, 0, sizeof(sNC));
   91794     sNC.pParse = pParse;
   91795     sNC.pSrcList = pTabList;
   91796     sNC.pAggInfo = &sAggInfo;
   91797     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
   91798     sAggInfo.pGroupBy = pGroupBy;
   91799     sqlite3ExprAnalyzeAggList(&sNC, pEList);
   91800     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
   91801     if( pHaving ){
   91802       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
   91803     }
   91804     sAggInfo.nAccumulator = sAggInfo.nColumn;
   91805     for(i=0; i<sAggInfo.nFunc; i++){
   91806       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
   91807       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
   91808     }
   91809     if( db->mallocFailed ) goto select_end;
   91810 
   91811     /* Processing for aggregates with GROUP BY is very different and
   91812     ** much more complex than aggregates without a GROUP BY.
   91813     */
   91814     if( pGroupBy ){
   91815       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
   91816       int j1;             /* A-vs-B comparision jump */
   91817       int addrOutputRow;  /* Start of subroutine that outputs a result row */
   91818       int regOutputRow;   /* Return address register for output subroutine */
   91819       int addrSetAbort;   /* Set the abort flag and return */
   91820       int addrTopOfLoop;  /* Top of the input loop */
   91821       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
   91822       int addrReset;      /* Subroutine for resetting the accumulator */
   91823       int regReset;       /* Return address register for reset subroutine */
   91824 
   91825       /* If there is a GROUP BY clause we might need a sorting index to
   91826       ** implement it.  Allocate that sorting index now.  If it turns out
   91827       ** that we do not need it after all, the OpenEphemeral instruction
   91828       ** will be converted into a Noop.
   91829       */
   91830       sAggInfo.sortingIdx = pParse->nTab++;
   91831       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
   91832       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
   91833           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
   91834           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
   91835 
   91836       /* Initialize memory locations used by GROUP BY aggregate processing
   91837       */
   91838       iUseFlag = ++pParse->nMem;
   91839       iAbortFlag = ++pParse->nMem;
   91840       regOutputRow = ++pParse->nMem;
   91841       addrOutputRow = sqlite3VdbeMakeLabel(v);
   91842       regReset = ++pParse->nMem;
   91843       addrReset = sqlite3VdbeMakeLabel(v);
   91844       iAMem = pParse->nMem + 1;
   91845       pParse->nMem += pGroupBy->nExpr;
   91846       iBMem = pParse->nMem + 1;
   91847       pParse->nMem += pGroupBy->nExpr;
   91848       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
   91849       VdbeComment((v, "clear abort flag"));
   91850       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
   91851       VdbeComment((v, "indicate accumulator empty"));
   91852 
   91853       /* Begin a loop that will extract all source rows in GROUP BY order.
   91854       ** This might involve two separate loops with an OP_Sort in between, or
   91855       ** it might be a single loop that uses an index to extract information
   91856       ** in the right order to begin with.
   91857       */
   91858       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   91859       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
   91860       if( pWInfo==0 ) goto select_end;
   91861       if( pGroupBy==0 ){
   91862         /* The optimizer is able to deliver rows in group by order so
   91863         ** we do not have to sort.  The OP_OpenEphemeral table will be
   91864         ** cancelled later because we still need to use the pKeyInfo
   91865         */
   91866         pGroupBy = p->pGroupBy;
   91867         groupBySort = 0;
   91868       }else{
   91869         /* Rows are coming out in undetermined order.  We have to push
   91870         ** each row into a sorting index, terminate the first loop,
   91871         ** then loop over the sorting index in order to get the output
   91872         ** in sorted order
   91873         */
   91874         int regBase;
   91875         int regRecord;
   91876         int nCol;
   91877         int nGroupBy;
   91878 
   91879         explainTempTable(pParse,
   91880             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
   91881 
   91882         groupBySort = 1;
   91883         nGroupBy = pGroupBy->nExpr;
   91884         nCol = nGroupBy + 1;
   91885         j = nGroupBy+1;
   91886         for(i=0; i<sAggInfo.nColumn; i++){
   91887           if( sAggInfo.aCol[i].iSorterColumn>=j ){
   91888             nCol++;
   91889             j++;
   91890           }
   91891         }
   91892         regBase = sqlite3GetTempRange(pParse, nCol);
   91893         sqlite3ExprCacheClear(pParse);
   91894         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
   91895         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
   91896         j = nGroupBy+1;
   91897         for(i=0; i<sAggInfo.nColumn; i++){
   91898           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
   91899           if( pCol->iSorterColumn>=j ){
   91900             int r1 = j + regBase;
   91901             int r2;
   91902 
   91903             r2 = sqlite3ExprCodeGetColumn(pParse,
   91904                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
   91905             if( r1!=r2 ){
   91906               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
   91907             }
   91908             j++;
   91909           }
   91910         }
   91911         regRecord = sqlite3GetTempReg(pParse);
   91912         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
   91913         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
   91914         sqlite3ReleaseTempReg(pParse, regRecord);
   91915         sqlite3ReleaseTempRange(pParse, regBase, nCol);
   91916         sqlite3WhereEnd(pWInfo);
   91917         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
   91918         VdbeComment((v, "GROUP BY sort"));
   91919         sAggInfo.useSortingIdx = 1;
   91920         sqlite3ExprCacheClear(pParse);
   91921       }
   91922 
   91923       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
   91924       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
   91925       ** Then compare the current GROUP BY terms against the GROUP BY terms
   91926       ** from the previous row currently stored in a0, a1, a2...
   91927       */
   91928       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
   91929       sqlite3ExprCacheClear(pParse);
   91930       for(j=0; j<pGroupBy->nExpr; j++){
   91931         if( groupBySort ){
   91932           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
   91933         }else{
   91934           sAggInfo.directMode = 1;
   91935           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
   91936         }
   91937       }
   91938       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
   91939                           (char*)pKeyInfo, P4_KEYINFO);
   91940       j1 = sqlite3VdbeCurrentAddr(v);
   91941       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
   91942 
   91943       /* Generate code that runs whenever the GROUP BY changes.
   91944       ** Changes in the GROUP BY are detected by the previous code
   91945       ** block.  If there were no changes, this block is skipped.
   91946       **
   91947       ** This code copies current group by terms in b0,b1,b2,...
   91948       ** over to a0,a1,a2.  It then calls the output subroutine
   91949       ** and resets the aggregate accumulator registers in preparation
   91950       ** for the next GROUP BY batch.
   91951       */
   91952       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
   91953       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   91954       VdbeComment((v, "output one row"));
   91955       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
   91956       VdbeComment((v, "check abort flag"));
   91957       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
   91958       VdbeComment((v, "reset accumulator"));
   91959 
   91960       /* Update the aggregate accumulators based on the content of
   91961       ** the current row
   91962       */
   91963       sqlite3VdbeJumpHere(v, j1);
   91964       updateAccumulator(pParse, &sAggInfo);
   91965       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
   91966       VdbeComment((v, "indicate data in accumulator"));
   91967 
   91968       /* End of the loop
   91969       */
   91970       if( groupBySort ){
   91971         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
   91972       }else{
   91973         sqlite3WhereEnd(pWInfo);
   91974         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
   91975       }
   91976 
   91977       /* Output the final row of result
   91978       */
   91979       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
   91980       VdbeComment((v, "output final row"));
   91981 
   91982       /* Jump over the subroutines
   91983       */
   91984       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
   91985 
   91986       /* Generate a subroutine that outputs a single row of the result
   91987       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
   91988       ** is less than or equal to zero, the subroutine is a no-op.  If
   91989       ** the processing calls for the query to abort, this subroutine
   91990       ** increments the iAbortFlag memory location before returning in
   91991       ** order to signal the caller to abort.
   91992       */
   91993       addrSetAbort = sqlite3VdbeCurrentAddr(v);
   91994       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
   91995       VdbeComment((v, "set abort flag"));
   91996       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   91997       sqlite3VdbeResolveLabel(v, addrOutputRow);
   91998       addrOutputRow = sqlite3VdbeCurrentAddr(v);
   91999       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
   92000       VdbeComment((v, "Groupby result generator entry point"));
   92001       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   92002       finalizeAggFunctions(pParse, &sAggInfo);
   92003       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
   92004       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
   92005                       distinct, pDest,
   92006                       addrOutputRow+1, addrSetAbort);
   92007       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
   92008       VdbeComment((v, "end groupby result generator"));
   92009 
   92010       /* Generate a subroutine that will reset the group-by accumulator
   92011       */
   92012       sqlite3VdbeResolveLabel(v, addrReset);
   92013       resetAccumulator(pParse, &sAggInfo);
   92014       sqlite3VdbeAddOp1(v, OP_Return, regReset);
   92015 
   92016     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
   92017     else {
   92018       ExprList *pDel = 0;
   92019 #ifndef SQLITE_OMIT_BTREECOUNT
   92020       Table *pTab;
   92021       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
   92022         /* If isSimpleCount() returns a pointer to a Table structure, then
   92023         ** the SQL statement is of the form:
   92024         **
   92025         **   SELECT count(*) FROM <tbl>
   92026         **
   92027         ** where the Table structure returned represents table <tbl>.
   92028         **
   92029         ** This statement is so common that it is optimized specially. The
   92030         ** OP_Count instruction is executed either on the intkey table that
   92031         ** contains the data for table <tbl> or on one of its indexes. It
   92032         ** is better to execute the op on an index, as indexes are almost
   92033         ** always spread across less pages than their corresponding tables.
   92034         */
   92035         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   92036         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
   92037         Index *pIdx;                         /* Iterator variable */
   92038         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
   92039         Index *pBest = 0;                    /* Best index found so far */
   92040         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
   92041 
   92042         sqlite3CodeVerifySchema(pParse, iDb);
   92043         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   92044 
   92045         /* Search for the index that has the least amount of columns. If
   92046         ** there is such an index, and it has less columns than the table
   92047         ** does, then we can assume that it consumes less space on disk and
   92048         ** will therefore be cheaper to scan to determine the query result.
   92049         ** In this case set iRoot to the root page number of the index b-tree
   92050         ** and pKeyInfo to the KeyInfo structure required to navigate the
   92051         ** index.
   92052         **
   92053         ** In practice the KeyInfo structure will not be used. It is only
   92054         ** passed to keep OP_OpenRead happy.
   92055         */
   92056         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   92057           if( !pBest || pIdx->nColumn<pBest->nColumn ){
   92058             pBest = pIdx;
   92059           }
   92060         }
   92061         if( pBest && pBest->nColumn<pTab->nCol ){
   92062           iRoot = pBest->tnum;
   92063           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
   92064         }
   92065 
   92066         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
   92067         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
   92068         if( pKeyInfo ){
   92069           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
   92070         }
   92071         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
   92072         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
   92073       }else
   92074 #endif /* SQLITE_OMIT_BTREECOUNT */
   92075       {
   92076         /* Check if the query is of one of the following forms:
   92077         **
   92078         **   SELECT min(x) FROM ...
   92079         **   SELECT max(x) FROM ...
   92080         **
   92081         ** If it is, then ask the code in where.c to attempt to sort results
   92082         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
   92083         ** If where.c is able to produce results sorted in this order, then
   92084         ** add vdbe code to break out of the processing loop after the
   92085         ** first iteration (since the first iteration of the loop is
   92086         ** guaranteed to operate on the row with the minimum or maximum
   92087         ** value of x, the only row required).
   92088         **
   92089         ** A special flag must be passed to sqlite3WhereBegin() to slightly
   92090         ** modify behaviour as follows:
   92091         **
   92092         **   + If the query is a "SELECT min(x)", then the loop coded by
   92093         **     where.c should not iterate over any values with a NULL value
   92094         **     for x.
   92095         **
   92096         **   + The optimizer code in where.c (the thing that decides which
   92097         **     index or indices to use) should place a different priority on
   92098         **     satisfying the 'ORDER BY' clause than it does in other cases.
   92099         **     Refer to code and comments in where.c for details.
   92100         */
   92101         ExprList *pMinMax = 0;
   92102         u8 flag = minMaxQuery(p);
   92103         if( flag ){
   92104           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
   92105           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
   92106           pDel = pMinMax;
   92107           if( pMinMax && !db->mallocFailed ){
   92108             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
   92109             pMinMax->a[0].pExpr->op = TK_COLUMN;
   92110           }
   92111         }
   92112 
   92113         /* This case runs if the aggregate has no GROUP BY clause.  The
   92114         ** processing is much simpler since there is only a single row
   92115         ** of output.
   92116         */
   92117         resetAccumulator(pParse, &sAggInfo);
   92118         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
   92119         if( pWInfo==0 ){
   92120           sqlite3ExprListDelete(db, pDel);
   92121           goto select_end;
   92122         }
   92123         updateAccumulator(pParse, &sAggInfo);
   92124         if( !pMinMax && flag ){
   92125           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
   92126           VdbeComment((v, "%s() by index",
   92127                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
   92128         }
   92129         sqlite3WhereEnd(pWInfo);
   92130         finalizeAggFunctions(pParse, &sAggInfo);
   92131       }
   92132 
   92133       pOrderBy = 0;
   92134       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
   92135       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
   92136                       pDest, addrEnd, addrEnd);
   92137       sqlite3ExprListDelete(db, pDel);
   92138     }
   92139     sqlite3VdbeResolveLabel(v, addrEnd);
   92140 
   92141   } /* endif aggregate query */
   92142 
   92143   if( distinct>=0 ){
   92144     explainTempTable(pParse, "DISTINCT");
   92145   }
   92146 
   92147   /* If there is an ORDER BY clause, then we need to sort the results
   92148   ** and send them to the callback one by one.
   92149   */
   92150   if( pOrderBy ){
   92151     explainTempTable(pParse, "ORDER BY");
   92152     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
   92153   }
   92154 
   92155   /* Jump here to skip this query
   92156   */
   92157   sqlite3VdbeResolveLabel(v, iEnd);
   92158 
   92159   /* The SELECT was successfully coded.   Set the return code to 0
   92160   ** to indicate no errors.
   92161   */
   92162   rc = 0;
   92163 
   92164   /* Control jumps to here if an error is encountered above, or upon
   92165   ** successful coding of the SELECT.
   92166   */
   92167 select_end:
   92168   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
   92169 
   92170   /* Identify column names if results of the SELECT are to be output.
   92171   */
   92172   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
   92173     generateColumnNames(pParse, pTabList, pEList);
   92174   }
   92175 
   92176   sqlite3DbFree(db, sAggInfo.aCol);
   92177   sqlite3DbFree(db, sAggInfo.aFunc);
   92178   return rc;
   92179 }
   92180 
   92181 #if defined(SQLITE_DEBUG)
   92182 /*
   92183 *******************************************************************************
   92184 ** The following code is used for testing and debugging only.  The code
   92185 ** that follows does not appear in normal builds.
   92186 **
   92187 ** These routines are used to print out the content of all or part of a
   92188 ** parse structures such as Select or Expr.  Such printouts are useful
   92189 ** for helping to understand what is happening inside the code generator
   92190 ** during the execution of complex SELECT statements.
   92191 **
   92192 ** These routine are not called anywhere from within the normal
   92193 ** code base.  Then are intended to be called from within the debugger
   92194 ** or from temporary "printf" statements inserted for debugging.
   92195 */
   92196 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
   92197   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
   92198     sqlite3DebugPrintf("(%s", p->u.zToken);
   92199   }else{
   92200     sqlite3DebugPrintf("(%d", p->op);
   92201   }
   92202   if( p->pLeft ){
   92203     sqlite3DebugPrintf(" ");
   92204     sqlite3PrintExpr(p->pLeft);
   92205   }
   92206   if( p->pRight ){
   92207     sqlite3DebugPrintf(" ");
   92208     sqlite3PrintExpr(p->pRight);
   92209   }
   92210   sqlite3DebugPrintf(")");
   92211 }
   92212 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
   92213   int i;
   92214   for(i=0; i<pList->nExpr; i++){
   92215     sqlite3PrintExpr(pList->a[i].pExpr);
   92216     if( i<pList->nExpr-1 ){
   92217       sqlite3DebugPrintf(", ");
   92218     }
   92219   }
   92220 }
   92221 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
   92222   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
   92223   sqlite3PrintExprList(p->pEList);
   92224   sqlite3DebugPrintf("\n");
   92225   if( p->pSrc ){
   92226     char *zPrefix;
   92227     int i;
   92228     zPrefix = "FROM";
   92229     for(i=0; i<p->pSrc->nSrc; i++){
   92230       struct SrcList_item *pItem = &p->pSrc->a[i];
   92231       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
   92232       zPrefix = "";
   92233       if( pItem->pSelect ){
   92234         sqlite3DebugPrintf("(\n");
   92235         sqlite3PrintSelect(pItem->pSelect, indent+10);
   92236         sqlite3DebugPrintf("%*s)", indent+8, "");
   92237       }else if( pItem->zName ){
   92238         sqlite3DebugPrintf("%s", pItem->zName);
   92239       }
   92240       if( pItem->pTab ){
   92241         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
   92242       }
   92243       if( pItem->zAlias ){
   92244         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
   92245       }
   92246       if( i<p->pSrc->nSrc-1 ){
   92247         sqlite3DebugPrintf(",");
   92248       }
   92249       sqlite3DebugPrintf("\n");
   92250     }
   92251   }
   92252   if( p->pWhere ){
   92253     sqlite3DebugPrintf("%*s WHERE ", indent, "");
   92254     sqlite3PrintExpr(p->pWhere);
   92255     sqlite3DebugPrintf("\n");
   92256   }
   92257   if( p->pGroupBy ){
   92258     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
   92259     sqlite3PrintExprList(p->pGroupBy);
   92260     sqlite3DebugPrintf("\n");
   92261   }
   92262   if( p->pHaving ){
   92263     sqlite3DebugPrintf("%*s HAVING ", indent, "");
   92264     sqlite3PrintExpr(p->pHaving);
   92265     sqlite3DebugPrintf("\n");
   92266   }
   92267   if( p->pOrderBy ){
   92268     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
   92269     sqlite3PrintExprList(p->pOrderBy);
   92270     sqlite3DebugPrintf("\n");
   92271   }
   92272 }
   92273 /* End of the structure debug printing code
   92274 *****************************************************************************/
   92275 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
   92276 
   92277 /************** End of select.c **********************************************/
   92278 /************** Begin file table.c *******************************************/
   92279 /*
   92280 ** 2001 September 15
   92281 **
   92282 ** The author disclaims copyright to this source code.  In place of
   92283 ** a legal notice, here is a blessing:
   92284 **
   92285 **    May you do good and not evil.
   92286 **    May you find forgiveness for yourself and forgive others.
   92287 **    May you share freely, never taking more than you give.
   92288 **
   92289 *************************************************************************
   92290 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
   92291 ** interface routines.  These are just wrappers around the main
   92292 ** interface routine of sqlite3_exec().
   92293 **
   92294 ** These routines are in a separate files so that they will not be linked
   92295 ** if they are not used.
   92296 */
   92297 
   92298 #ifndef SQLITE_OMIT_GET_TABLE
   92299 
   92300 /*
   92301 ** This structure is used to pass data from sqlite3_get_table() through
   92302 ** to the callback function is uses to build the result.
   92303 */
   92304 typedef struct TabResult {
   92305   char **azResult;   /* Accumulated output */
   92306   char *zErrMsg;     /* Error message text, if an error occurs */
   92307   int nAlloc;        /* Slots allocated for azResult[] */
   92308   int nRow;          /* Number of rows in the result */
   92309   int nColumn;       /* Number of columns in the result */
   92310   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
   92311   int rc;            /* Return code from sqlite3_exec() */
   92312 } TabResult;
   92313 
   92314 /*
   92315 ** This routine is called once for each row in the result table.  Its job
   92316 ** is to fill in the TabResult structure appropriately, allocating new
   92317 ** memory as necessary.
   92318 */
   92319 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
   92320   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
   92321   int need;                         /* Slots needed in p->azResult[] */
   92322   int i;                            /* Loop counter */
   92323   char *z;                          /* A single column of result */
   92324 
   92325   /* Make sure there is enough space in p->azResult to hold everything
   92326   ** we need to remember from this invocation of the callback.
   92327   */
   92328   if( p->nRow==0 && argv!=0 ){
   92329     need = nCol*2;
   92330   }else{
   92331     need = nCol;
   92332   }
   92333   if( p->nData + need > p->nAlloc ){
   92334     char **azNew;
   92335     p->nAlloc = p->nAlloc*2 + need;
   92336     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
   92337     if( azNew==0 ) goto malloc_failed;
   92338     p->azResult = azNew;
   92339   }
   92340 
   92341   /* If this is the first row, then generate an extra row containing
   92342   ** the names of all columns.
   92343   */
   92344   if( p->nRow==0 ){
   92345     p->nColumn = nCol;
   92346     for(i=0; i<nCol; i++){
   92347       z = sqlite3_mprintf("%s", colv[i]);
   92348       if( z==0 ) goto malloc_failed;
   92349       p->azResult[p->nData++] = z;
   92350     }
   92351   }else if( p->nColumn!=nCol ){
   92352     sqlite3_free(p->zErrMsg);
   92353     p->zErrMsg = sqlite3_mprintf(
   92354        "sqlite3_get_table() called with two or more incompatible queries"
   92355     );
   92356     p->rc = SQLITE_ERROR;
   92357     return 1;
   92358   }
   92359 
   92360   /* Copy over the row data
   92361   */
   92362   if( argv!=0 ){
   92363     for(i=0; i<nCol; i++){
   92364       if( argv[i]==0 ){
   92365         z = 0;
   92366       }else{
   92367         int n = sqlite3Strlen30(argv[i])+1;
   92368         z = sqlite3_malloc( n );
   92369         if( z==0 ) goto malloc_failed;
   92370         memcpy(z, argv[i], n);
   92371       }
   92372       p->azResult[p->nData++] = z;
   92373     }
   92374     p->nRow++;
   92375   }
   92376   return 0;
   92377 
   92378 malloc_failed:
   92379   p->rc = SQLITE_NOMEM;
   92380   return 1;
   92381 }
   92382 
   92383 /*
   92384 ** Query the database.  But instead of invoking a callback for each row,
   92385 ** malloc() for space to hold the result and return the entire results
   92386 ** at the conclusion of the call.
   92387 **
   92388 ** The result that is written to ***pazResult is held in memory obtained
   92389 ** from malloc().  But the caller cannot free this memory directly.
   92390 ** Instead, the entire table should be passed to sqlite3_free_table() when
   92391 ** the calling procedure is finished using it.
   92392 */
   92393 SQLITE_API int sqlite3_get_table(
   92394   sqlite3 *db,                /* The database on which the SQL executes */
   92395   const char *zSql,           /* The SQL to be executed */
   92396   char ***pazResult,          /* Write the result table here */
   92397   int *pnRow,                 /* Write the number of rows in the result here */
   92398   int *pnColumn,              /* Write the number of columns of result here */
   92399   char **pzErrMsg             /* Write error messages here */
   92400 ){
   92401   int rc;
   92402   TabResult res;
   92403 
   92404   *pazResult = 0;
   92405   if( pnColumn ) *pnColumn = 0;
   92406   if( pnRow ) *pnRow = 0;
   92407   if( pzErrMsg ) *pzErrMsg = 0;
   92408   res.zErrMsg = 0;
   92409   res.nRow = 0;
   92410   res.nColumn = 0;
   92411   res.nData = 1;
   92412   res.nAlloc = 20;
   92413   res.rc = SQLITE_OK;
   92414   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
   92415   if( res.azResult==0 ){
   92416      db->errCode = SQLITE_NOMEM;
   92417      return SQLITE_NOMEM;
   92418   }
   92419   res.azResult[0] = 0;
   92420   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
   92421   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
   92422   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
   92423   if( (rc&0xff)==SQLITE_ABORT ){
   92424     sqlite3_free_table(&res.azResult[1]);
   92425     if( res.zErrMsg ){
   92426       if( pzErrMsg ){
   92427         sqlite3_free(*pzErrMsg);
   92428         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
   92429       }
   92430       sqlite3_free(res.zErrMsg);
   92431     }
   92432     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
   92433     return res.rc;
   92434   }
   92435   sqlite3_free(res.zErrMsg);
   92436   if( rc!=SQLITE_OK ){
   92437     sqlite3_free_table(&res.azResult[1]);
   92438     return rc;
   92439   }
   92440   if( res.nAlloc>res.nData ){
   92441     char **azNew;
   92442     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
   92443     if( azNew==0 ){
   92444       sqlite3_free_table(&res.azResult[1]);
   92445       db->errCode = SQLITE_NOMEM;
   92446       return SQLITE_NOMEM;
   92447     }
   92448     res.azResult = azNew;
   92449   }
   92450   *pazResult = &res.azResult[1];
   92451   if( pnColumn ) *pnColumn = res.nColumn;
   92452   if( pnRow ) *pnRow = res.nRow;
   92453   return rc;
   92454 }
   92455 
   92456 /*
   92457 ** This routine frees the space the sqlite3_get_table() malloced.
   92458 */
   92459 SQLITE_API void sqlite3_free_table(
   92460   char **azResult            /* Result returned from from sqlite3_get_table() */
   92461 ){
   92462   if( azResult ){
   92463     int i, n;
   92464     azResult--;
   92465     assert( azResult!=0 );
   92466     n = SQLITE_PTR_TO_INT(azResult[0]);
   92467     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
   92468     sqlite3_free(azResult);
   92469   }
   92470 }
   92471 
   92472 #endif /* SQLITE_OMIT_GET_TABLE */
   92473 
   92474 /************** End of table.c ***********************************************/
   92475 /************** Begin file trigger.c *****************************************/
   92476 /*
   92477 **
   92478 ** The author disclaims copyright to this source code.  In place of
   92479 ** a legal notice, here is a blessing:
   92480 **
   92481 **    May you do good and not evil.
   92482 **    May you find forgiveness for yourself and forgive others.
   92483 **    May you share freely, never taking more than you give.
   92484 **
   92485 *************************************************************************
   92486 ** This file contains the implementation for TRIGGERs
   92487 */
   92488 
   92489 #ifndef SQLITE_OMIT_TRIGGER
   92490 /*
   92491 ** Delete a linked list of TriggerStep structures.
   92492 */
   92493 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
   92494   while( pTriggerStep ){
   92495     TriggerStep * pTmp = pTriggerStep;
   92496     pTriggerStep = pTriggerStep->pNext;
   92497 
   92498     sqlite3ExprDelete(db, pTmp->pWhere);
   92499     sqlite3ExprListDelete(db, pTmp->pExprList);
   92500     sqlite3SelectDelete(db, pTmp->pSelect);
   92501     sqlite3IdListDelete(db, pTmp->pIdList);
   92502 
   92503     sqlite3DbFree(db, pTmp);
   92504   }
   92505 }
   92506 
   92507 /*
   92508 ** Given table pTab, return a list of all the triggers attached to
   92509 ** the table. The list is connected by Trigger.pNext pointers.
   92510 **
   92511 ** All of the triggers on pTab that are in the same database as pTab
   92512 ** are already attached to pTab->pTrigger.  But there might be additional
   92513 ** triggers on pTab in the TEMP schema.  This routine prepends all
   92514 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
   92515 ** and returns the combined list.
   92516 **
   92517 ** To state it another way:  This routine returns a list of all triggers
   92518 ** that fire off of pTab.  The list will include any TEMP triggers on
   92519 ** pTab as well as the triggers lised in pTab->pTrigger.
   92520 */
   92521 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
   92522   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
   92523   Trigger *pList = 0;                  /* List of triggers to return */
   92524 
   92525   if( pParse->disableTriggers ){
   92526     return 0;
   92527   }
   92528 
   92529   if( pTmpSchema!=pTab->pSchema ){
   92530     HashElem *p;
   92531     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
   92532       Trigger *pTrig = (Trigger *)sqliteHashData(p);
   92533       if( pTrig->pTabSchema==pTab->pSchema
   92534        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
   92535       ){
   92536         pTrig->pNext = (pList ? pList : pTab->pTrigger);
   92537         pList = pTrig;
   92538       }
   92539     }
   92540   }
   92541 
   92542   return (pList ? pList : pTab->pTrigger);
   92543 }
   92544 
   92545 /*
   92546 ** This is called by the parser when it sees a CREATE TRIGGER statement
   92547 ** up to the point of the BEGIN before the trigger actions.  A Trigger
   92548 ** structure is generated based on the information available and stored
   92549 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
   92550 ** sqlite3FinishTrigger() function is called to complete the trigger
   92551 ** construction process.
   92552 */
   92553 SQLITE_PRIVATE void sqlite3BeginTrigger(
   92554   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
   92555   Token *pName1,      /* The name of the trigger */
   92556   Token *pName2,      /* The name of the trigger */
   92557   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
   92558   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
   92559   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
   92560   SrcList *pTableName,/* The name of the table/view the trigger applies to */
   92561   Expr *pWhen,        /* WHEN clause */
   92562   int isTemp,         /* True if the TEMPORARY keyword is present */
   92563   int noErr           /* Suppress errors if the trigger already exists */
   92564 ){
   92565   Trigger *pTrigger = 0;  /* The new trigger */
   92566   Table *pTab;            /* Table that the trigger fires off of */
   92567   char *zName = 0;        /* Name of the trigger */
   92568   sqlite3 *db = pParse->db;  /* The database connection */
   92569   int iDb;                /* The database to store the trigger in */
   92570   Token *pName;           /* The unqualified db name */
   92571   DbFixer sFix;           /* State vector for the DB fixer */
   92572   int iTabDb;             /* Index of the database holding pTab */
   92573 
   92574   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
   92575   assert( pName2!=0 );
   92576   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
   92577   assert( op>0 && op<0xff );
   92578   if( isTemp ){
   92579     /* If TEMP was specified, then the trigger name may not be qualified. */
   92580     if( pName2->n>0 ){
   92581       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
   92582       goto trigger_cleanup;
   92583     }
   92584     iDb = 1;
   92585     pName = pName1;
   92586   }else{
   92587     /* Figure out the db that the the trigger will be created in */
   92588     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
   92589     if( iDb<0 ){
   92590       goto trigger_cleanup;
   92591     }
   92592   }
   92593 
   92594   /* If the trigger name was unqualified, and the table is a temp table,
   92595   ** then set iDb to 1 to create the trigger in the temporary database.
   92596   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
   92597   ** exist, the error is caught by the block below.
   92598   */
   92599   if( !pTableName || db->mallocFailed ){
   92600     goto trigger_cleanup;
   92601   }
   92602   pTab = sqlite3SrcListLookup(pParse, pTableName);
   92603   if( db->init.busy==0 && pName2->n==0 && pTab
   92604         && pTab->pSchema==db->aDb[1].pSchema ){
   92605     iDb = 1;
   92606   }
   92607 
   92608   /* Ensure the table name matches database name and that the table exists */
   92609   if( db->mallocFailed ) goto trigger_cleanup;
   92610   assert( pTableName->nSrc==1 );
   92611   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
   92612       sqlite3FixSrcList(&sFix, pTableName) ){
   92613     goto trigger_cleanup;
   92614   }
   92615   pTab = sqlite3SrcListLookup(pParse, pTableName);
   92616   if( !pTab ){
   92617     /* The table does not exist. */
   92618     if( db->init.iDb==1 ){
   92619       /* Ticket #3810.
   92620       ** Normally, whenever a table is dropped, all associated triggers are
   92621       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
   92622       ** and the table is dropped by a different database connection, the
   92623       ** trigger is not visible to the database connection that does the
   92624       ** drop so the trigger cannot be dropped.  This results in an
   92625       ** "orphaned trigger" - a trigger whose associated table is missing.
   92626       */
   92627       db->init.orphanTrigger = 1;
   92628     }
   92629     goto trigger_cleanup;
   92630   }
   92631   if( IsVirtual(pTab) ){
   92632     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
   92633     goto trigger_cleanup;
   92634   }
   92635 
   92636   /* Check that the trigger name is not reserved and that no trigger of the
   92637   ** specified name exists */
   92638   zName = sqlite3NameFromToken(db, pName);
   92639   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
   92640     goto trigger_cleanup;
   92641   }
   92642   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
   92643                       zName, sqlite3Strlen30(zName)) ){
   92644     if( !noErr ){
   92645       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
   92646     }
   92647     goto trigger_cleanup;
   92648   }
   92649 
   92650   /* Do not create a trigger on a system table */
   92651   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
   92652     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
   92653     pParse->nErr++;
   92654     goto trigger_cleanup;
   92655   }
   92656 
   92657   /* INSTEAD of triggers are only for views and views only support INSTEAD
   92658   ** of triggers.
   92659   */
   92660   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
   92661     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
   92662         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
   92663     goto trigger_cleanup;
   92664   }
   92665   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
   92666     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
   92667         " trigger on table: %S", pTableName, 0);
   92668     goto trigger_cleanup;
   92669   }
   92670   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   92671 
   92672 #ifndef SQLITE_OMIT_AUTHORIZATION
   92673   {
   92674     int code = SQLITE_CREATE_TRIGGER;
   92675     const char *zDb = db->aDb[iTabDb].zName;
   92676     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
   92677     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
   92678     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
   92679       goto trigger_cleanup;
   92680     }
   92681     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
   92682       goto trigger_cleanup;
   92683     }
   92684   }
   92685 #endif
   92686 
   92687   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
   92688   ** cannot appear on views.  So we might as well translate every
   92689   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
   92690   ** elsewhere.
   92691   */
   92692   if (tr_tm == TK_INSTEAD){
   92693     tr_tm = TK_BEFORE;
   92694   }
   92695 
   92696   /* Build the Trigger object */
   92697   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
   92698   if( pTrigger==0 ) goto trigger_cleanup;
   92699   pTrigger->zName = zName;
   92700   zName = 0;
   92701   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
   92702   pTrigger->pSchema = db->aDb[iDb].pSchema;
   92703   pTrigger->pTabSchema = pTab->pSchema;
   92704   pTrigger->op = (u8)op;
   92705   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
   92706   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
   92707   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
   92708   assert( pParse->pNewTrigger==0 );
   92709   pParse->pNewTrigger = pTrigger;
   92710 
   92711 trigger_cleanup:
   92712   sqlite3DbFree(db, zName);
   92713   sqlite3SrcListDelete(db, pTableName);
   92714   sqlite3IdListDelete(db, pColumns);
   92715   sqlite3ExprDelete(db, pWhen);
   92716   if( !pParse->pNewTrigger ){
   92717     sqlite3DeleteTrigger(db, pTrigger);
   92718   }else{
   92719     assert( pParse->pNewTrigger==pTrigger );
   92720   }
   92721 }
   92722 
   92723 /*
   92724 ** This routine is called after all of the trigger actions have been parsed
   92725 ** in order to complete the process of building the trigger.
   92726 */
   92727 SQLITE_PRIVATE void sqlite3FinishTrigger(
   92728   Parse *pParse,          /* Parser context */
   92729   TriggerStep *pStepList, /* The triggered program */
   92730   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
   92731 ){
   92732   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
   92733   char *zName;                            /* Name of trigger */
   92734   sqlite3 *db = pParse->db;               /* The database */
   92735   DbFixer sFix;                           /* Fixer object */
   92736   int iDb;                                /* Database containing the trigger */
   92737   Token nameToken;                        /* Trigger name for error reporting */
   92738 
   92739   pTrig = pParse->pNewTrigger;
   92740   pParse->pNewTrigger = 0;
   92741   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
   92742   zName = pTrig->zName;
   92743   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
   92744   pTrig->step_list = pStepList;
   92745   while( pStepList ){
   92746     pStepList->pTrig = pTrig;
   92747     pStepList = pStepList->pNext;
   92748   }
   92749   nameToken.z = pTrig->zName;
   92750   nameToken.n = sqlite3Strlen30(nameToken.z);
   92751   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
   92752           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
   92753     goto triggerfinish_cleanup;
   92754   }
   92755 
   92756   /* if we are not initializing,
   92757   ** build the sqlite_master entry
   92758   */
   92759   if( !db->init.busy ){
   92760     Vdbe *v;
   92761     char *z;
   92762 
   92763     /* Make an entry in the sqlite_master table */
   92764     v = sqlite3GetVdbe(pParse);
   92765     if( v==0 ) goto triggerfinish_cleanup;
   92766     sqlite3BeginWriteOperation(pParse, 0, iDb);
   92767     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
   92768     sqlite3NestedParse(pParse,
   92769        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
   92770        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
   92771        pTrig->table, z);
   92772     sqlite3DbFree(db, z);
   92773     sqlite3ChangeCookie(pParse, iDb);
   92774     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
   92775         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
   92776     );
   92777   }
   92778 
   92779   if( db->init.busy ){
   92780     Trigger *pLink = pTrig;
   92781     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   92782     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
   92783     if( pTrig ){
   92784       db->mallocFailed = 1;
   92785     }else if( pLink->pSchema==pLink->pTabSchema ){
   92786       Table *pTab;
   92787       int n = sqlite3Strlen30(pLink->table);
   92788       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
   92789       assert( pTab!=0 );
   92790       pLink->pNext = pTab->pTrigger;
   92791       pTab->pTrigger = pLink;
   92792     }
   92793   }
   92794 
   92795 triggerfinish_cleanup:
   92796   sqlite3DeleteTrigger(db, pTrig);
   92797   assert( !pParse->pNewTrigger );
   92798   sqlite3DeleteTriggerStep(db, pStepList);
   92799 }
   92800 
   92801 /*
   92802 ** Turn a SELECT statement (that the pSelect parameter points to) into
   92803 ** a trigger step.  Return a pointer to a TriggerStep structure.
   92804 **
   92805 ** The parser calls this routine when it finds a SELECT statement in
   92806 ** body of a TRIGGER.
   92807 */
   92808 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
   92809   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
   92810   if( pTriggerStep==0 ) {
   92811     sqlite3SelectDelete(db, pSelect);
   92812     return 0;
   92813   }
   92814   pTriggerStep->op = TK_SELECT;
   92815   pTriggerStep->pSelect = pSelect;
   92816   pTriggerStep->orconf = OE_Default;
   92817   return pTriggerStep;
   92818 }
   92819 
   92820 /*
   92821 ** Allocate space to hold a new trigger step.  The allocated space
   92822 ** holds both the TriggerStep object and the TriggerStep.target.z string.
   92823 **
   92824 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
   92825 */
   92826 static TriggerStep *triggerStepAllocate(
   92827   sqlite3 *db,                /* Database connection */
   92828   u8 op,                      /* Trigger opcode */
   92829   Token *pName                /* The target name */
   92830 ){
   92831   TriggerStep *pTriggerStep;
   92832 
   92833   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
   92834   if( pTriggerStep ){
   92835     char *z = (char*)&pTriggerStep[1];
   92836     memcpy(z, pName->z, pName->n);
   92837     pTriggerStep->target.z = z;
   92838     pTriggerStep->target.n = pName->n;
   92839     pTriggerStep->op = op;
   92840   }
   92841   return pTriggerStep;
   92842 }
   92843 
   92844 /*
   92845 ** Build a trigger step out of an INSERT statement.  Return a pointer
   92846 ** to the new trigger step.
   92847 **
   92848 ** The parser calls this routine when it sees an INSERT inside the
   92849 ** body of a trigger.
   92850 */
   92851 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
   92852   sqlite3 *db,        /* The database connection */
   92853   Token *pTableName,  /* Name of the table into which we insert */
   92854   IdList *pColumn,    /* List of columns in pTableName to insert into */
   92855   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
   92856   Select *pSelect,    /* A SELECT statement that supplies values */
   92857   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
   92858 ){
   92859   TriggerStep *pTriggerStep;
   92860 
   92861   assert(pEList == 0 || pSelect == 0);
   92862   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
   92863 
   92864   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
   92865   if( pTriggerStep ){
   92866     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
   92867     pTriggerStep->pIdList = pColumn;
   92868     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   92869     pTriggerStep->orconf = orconf;
   92870   }else{
   92871     sqlite3IdListDelete(db, pColumn);
   92872   }
   92873   sqlite3ExprListDelete(db, pEList);
   92874   sqlite3SelectDelete(db, pSelect);
   92875 
   92876   return pTriggerStep;
   92877 }
   92878 
   92879 /*
   92880 ** Construct a trigger step that implements an UPDATE statement and return
   92881 ** a pointer to that trigger step.  The parser calls this routine when it
   92882 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
   92883 */
   92884 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   92885   sqlite3 *db,         /* The database connection */
   92886   Token *pTableName,   /* Name of the table to be updated */
   92887   ExprList *pEList,    /* The SET clause: list of column and new values */
   92888   Expr *pWhere,        /* The WHERE clause */
   92889   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
   92890 ){
   92891   TriggerStep *pTriggerStep;
   92892 
   92893   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
   92894   if( pTriggerStep ){
   92895     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
   92896     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   92897     pTriggerStep->orconf = orconf;
   92898   }
   92899   sqlite3ExprListDelete(db, pEList);
   92900   sqlite3ExprDelete(db, pWhere);
   92901   return pTriggerStep;
   92902 }
   92903 
   92904 /*
   92905 ** Construct a trigger step that implements a DELETE statement and return
   92906 ** a pointer to that trigger step.  The parser calls this routine when it
   92907 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
   92908 */
   92909 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   92910   sqlite3 *db,            /* Database connection */
   92911   Token *pTableName,      /* The table from which rows are deleted */
   92912   Expr *pWhere            /* The WHERE clause */
   92913 ){
   92914   TriggerStep *pTriggerStep;
   92915 
   92916   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
   92917   if( pTriggerStep ){
   92918     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
   92919     pTriggerStep->orconf = OE_Default;
   92920   }
   92921   sqlite3ExprDelete(db, pWhere);
   92922   return pTriggerStep;
   92923 }
   92924 
   92925 /*
   92926 ** Recursively delete a Trigger structure
   92927 */
   92928 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
   92929   if( pTrigger==0 ) return;
   92930   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
   92931   sqlite3DbFree(db, pTrigger->zName);
   92932   sqlite3DbFree(db, pTrigger->table);
   92933   sqlite3ExprDelete(db, pTrigger->pWhen);
   92934   sqlite3IdListDelete(db, pTrigger->pColumns);
   92935   sqlite3DbFree(db, pTrigger);
   92936 }
   92937 
   92938 /*
   92939 ** This function is called to drop a trigger from the database schema.
   92940 **
   92941 ** This may be called directly from the parser and therefore identifies
   92942 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
   92943 ** same job as this routine except it takes a pointer to the trigger
   92944 ** instead of the trigger name.
   92945 **/
   92946 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
   92947   Trigger *pTrigger = 0;
   92948   int i;
   92949   const char *zDb;
   92950   const char *zName;
   92951   int nName;
   92952   sqlite3 *db = pParse->db;
   92953 
   92954   if( db->mallocFailed ) goto drop_trigger_cleanup;
   92955   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
   92956     goto drop_trigger_cleanup;
   92957   }
   92958 
   92959   assert( pName->nSrc==1 );
   92960   zDb = pName->a[0].zDatabase;
   92961   zName = pName->a[0].zName;
   92962   nName = sqlite3Strlen30(zName);
   92963   for(i=OMIT_TEMPDB; i<db->nDb; i++){
   92964     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
   92965     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
   92966     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
   92967     if( pTrigger ) break;
   92968   }
   92969   if( !pTrigger ){
   92970     if( !noErr ){
   92971       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
   92972     }
   92973     pParse->checkSchema = 1;
   92974     goto drop_trigger_cleanup;
   92975   }
   92976   sqlite3DropTriggerPtr(pParse, pTrigger);
   92977 
   92978 drop_trigger_cleanup:
   92979   sqlite3SrcListDelete(db, pName);
   92980 }
   92981 
   92982 /*
   92983 ** Return a pointer to the Table structure for the table that a trigger
   92984 ** is set on.
   92985 */
   92986 static Table *tableOfTrigger(Trigger *pTrigger){
   92987   int n = sqlite3Strlen30(pTrigger->table);
   92988   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
   92989 }
   92990 
   92991 
   92992 /*
   92993 ** Drop a trigger given a pointer to that trigger.
   92994 */
   92995 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   92996   Table   *pTable;
   92997   Vdbe *v;
   92998   sqlite3 *db = pParse->db;
   92999   int iDb;
   93000 
   93001   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
   93002   assert( iDb>=0 && iDb<db->nDb );
   93003   pTable = tableOfTrigger(pTrigger);
   93004   assert( pTable );
   93005   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
   93006 #ifndef SQLITE_OMIT_AUTHORIZATION
   93007   {
   93008     int code = SQLITE_DROP_TRIGGER;
   93009     const char *zDb = db->aDb[iDb].zName;
   93010     const char *zTab = SCHEMA_TABLE(iDb);
   93011     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
   93012     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
   93013       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
   93014       return;
   93015     }
   93016   }
   93017 #endif
   93018 
   93019   /* Generate code to destroy the database record of the trigger.
   93020   */
   93021   assert( pTable!=0 );
   93022   if( (v = sqlite3GetVdbe(pParse))!=0 ){
   93023     int base;
   93024     static const VdbeOpList dropTrigger[] = {
   93025       { OP_Rewind,     0, ADDR(9),  0},
   93026       { OP_String8,    0, 1,        0}, /* 1 */
   93027       { OP_Column,     0, 1,        2},
   93028       { OP_Ne,         2, ADDR(8),  1},
   93029       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   93030       { OP_Column,     0, 0,        2},
   93031       { OP_Ne,         2, ADDR(8),  1},
   93032       { OP_Delete,     0, 0,        0},
   93033       { OP_Next,       0, ADDR(1),  0}, /* 8 */
   93034     };
   93035 
   93036     sqlite3BeginWriteOperation(pParse, 0, iDb);
   93037     sqlite3OpenMasterTable(pParse, iDb);
   93038     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
   93039     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
   93040     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   93041     sqlite3ChangeCookie(pParse, iDb);
   93042     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   93043     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   93044     if( pParse->nMem<3 ){
   93045       pParse->nMem = 3;
   93046     }
   93047   }
   93048 }
   93049 
   93050 /*
   93051 ** Remove a trigger from the hash tables of the sqlite* pointer.
   93052 */
   93053 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
   93054   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
   93055   Trigger *pTrigger;
   93056   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
   93057   if( ALWAYS(pTrigger) ){
   93058     if( pTrigger->pSchema==pTrigger->pTabSchema ){
   93059       Table *pTab = tableOfTrigger(pTrigger);
   93060       Trigger **pp;
   93061       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
   93062       *pp = (*pp)->pNext;
   93063     }
   93064     sqlite3DeleteTrigger(db, pTrigger);
   93065     db->flags |= SQLITE_InternChanges;
   93066   }
   93067 }
   93068 
   93069 /*
   93070 ** pEList is the SET clause of an UPDATE statement.  Each entry
   93071 ** in pEList is of the format <id>=<expr>.  If any of the entries
   93072 ** in pEList have an <id> which matches an identifier in pIdList,
   93073 ** then return TRUE.  If pIdList==NULL, then it is considered a
   93074 ** wildcard that matches anything.  Likewise if pEList==NULL then
   93075 ** it matches anything so always return true.  Return false only
   93076 ** if there is no match.
   93077 */
   93078 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   93079   int e;
   93080   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   93081   for(e=0; e<pEList->nExpr; e++){
   93082     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
   93083   }
   93084   return 0;
   93085 }
   93086 
   93087 /*
   93088 ** Return a list of all triggers on table pTab if there exists at least
   93089 ** one trigger that must be fired when an operation of type 'op' is
   93090 ** performed on the table, and, if that operation is an UPDATE, if at
   93091 ** least one of the columns in pChanges is being modified.
   93092 */
   93093 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
   93094   Parse *pParse,          /* Parse context */
   93095   Table *pTab,            /* The table the contains the triggers */
   93096   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
   93097   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
   93098   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   93099 ){
   93100   int mask = 0;
   93101   Trigger *pList = sqlite3TriggerList(pParse, pTab);
   93102   Trigger *p;
   93103   assert( pList==0 || IsVirtual(pTab)==0 );
   93104   for(p=pList; p; p=p->pNext){
   93105     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
   93106       mask |= p->tr_tm;
   93107     }
   93108   }
   93109   if( pMask ){
   93110     *pMask = mask;
   93111   }
   93112   return (mask ? pList : 0);
   93113 }
   93114 
   93115 /*
   93116 ** Convert the pStep->target token into a SrcList and return a pointer
   93117 ** to that SrcList.
   93118 **
   93119 ** This routine adds a specific database name, if needed, to the target when
   93120 ** forming the SrcList.  This prevents a trigger in one database from
   93121 ** referring to a target in another database.  An exception is when the
   93122 ** trigger is in TEMP in which case it can refer to any other database it
   93123 ** wants.
   93124 */
   93125 static SrcList *targetSrcList(
   93126   Parse *pParse,       /* The parsing context */
   93127   TriggerStep *pStep   /* The trigger containing the target token */
   93128 ){
   93129   int iDb;             /* Index of the database to use */
   93130   SrcList *pSrc;       /* SrcList to be returned */
   93131 
   93132   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
   93133   if( pSrc ){
   93134     assert( pSrc->nSrc>0 );
   93135     assert( pSrc->a!=0 );
   93136     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
   93137     if( iDb==0 || iDb>=2 ){
   93138       sqlite3 *db = pParse->db;
   93139       assert( iDb<pParse->db->nDb );
   93140       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
   93141     }
   93142   }
   93143   return pSrc;
   93144 }
   93145 
   93146 /*
   93147 ** Generate VDBE code for the statements inside the body of a single
   93148 ** trigger.
   93149 */
   93150 static int codeTriggerProgram(
   93151   Parse *pParse,            /* The parser context */
   93152   TriggerStep *pStepList,   /* List of statements inside the trigger body */
   93153   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
   93154 ){
   93155   TriggerStep *pStep;
   93156   Vdbe *v = pParse->pVdbe;
   93157   sqlite3 *db = pParse->db;
   93158 
   93159   assert( pParse->pTriggerTab && pParse->pToplevel );
   93160   assert( pStepList );
   93161   assert( v!=0 );
   93162   for(pStep=pStepList; pStep; pStep=pStep->pNext){
   93163     /* Figure out the ON CONFLICT policy that will be used for this step
   93164     ** of the trigger program. If the statement that caused this trigger
   93165     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
   93166     ** the ON CONFLICT policy that was specified as part of the trigger
   93167     ** step statement. Example:
   93168     **
   93169     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
   93170     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
   93171     **   END;
   93172     **
   93173     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
   93174     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
   93175     */
   93176     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
   93177 
   93178     switch( pStep->op ){
   93179       case TK_UPDATE: {
   93180         sqlite3Update(pParse,
   93181           targetSrcList(pParse, pStep),
   93182           sqlite3ExprListDup(db, pStep->pExprList, 0),
   93183           sqlite3ExprDup(db, pStep->pWhere, 0),
   93184           pParse->eOrconf
   93185         );
   93186         break;
   93187       }
   93188       case TK_INSERT: {
   93189         sqlite3Insert(pParse,
   93190           targetSrcList(pParse, pStep),
   93191           sqlite3ExprListDup(db, pStep->pExprList, 0),
   93192           sqlite3SelectDup(db, pStep->pSelect, 0),
   93193           sqlite3IdListDup(db, pStep->pIdList),
   93194           pParse->eOrconf
   93195         );
   93196         break;
   93197       }
   93198       case TK_DELETE: {
   93199         sqlite3DeleteFrom(pParse,
   93200           targetSrcList(pParse, pStep),
   93201           sqlite3ExprDup(db, pStep->pWhere, 0)
   93202         );
   93203         break;
   93204       }
   93205       default: assert( pStep->op==TK_SELECT ); {
   93206         SelectDest sDest;
   93207         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
   93208         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
   93209         sqlite3Select(pParse, pSelect, &sDest);
   93210         sqlite3SelectDelete(db, pSelect);
   93211         break;
   93212       }
   93213     }
   93214     if( pStep->op!=TK_SELECT ){
   93215       sqlite3VdbeAddOp0(v, OP_ResetCount);
   93216     }
   93217   }
   93218 
   93219   return 0;
   93220 }
   93221 
   93222 #ifdef SQLITE_DEBUG
   93223 /*
   93224 ** This function is used to add VdbeComment() annotations to a VDBE
   93225 ** program. It is not used in production code, only for debugging.
   93226 */
   93227 static const char *onErrorText(int onError){
   93228   switch( onError ){
   93229     case OE_Abort:    return "abort";
   93230     case OE_Rollback: return "rollback";
   93231     case OE_Fail:     return "fail";
   93232     case OE_Replace:  return "replace";
   93233     case OE_Ignore:   return "ignore";
   93234     case OE_Default:  return "default";
   93235   }
   93236   return "n/a";
   93237 }
   93238 #endif
   93239 
   93240 /*
   93241 ** Parse context structure pFrom has just been used to create a sub-vdbe
   93242 ** (trigger program). If an error has occurred, transfer error information
   93243 ** from pFrom to pTo.
   93244 */
   93245 static void transferParseError(Parse *pTo, Parse *pFrom){
   93246   assert( pFrom->zErrMsg==0 || pFrom->nErr );
   93247   assert( pTo->zErrMsg==0 || pTo->nErr );
   93248   if( pTo->nErr==0 ){
   93249     pTo->zErrMsg = pFrom->zErrMsg;
   93250     pTo->nErr = pFrom->nErr;
   93251   }else{
   93252     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
   93253   }
   93254 }
   93255 
   93256 /*
   93257 ** Create and populate a new TriggerPrg object with a sub-program
   93258 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
   93259 */
   93260 static TriggerPrg *codeRowTrigger(
   93261   Parse *pParse,       /* Current parse context */
   93262   Trigger *pTrigger,   /* Trigger to code */
   93263   Table *pTab,         /* The table pTrigger is attached to */
   93264   int orconf           /* ON CONFLICT policy to code trigger program with */
   93265 ){
   93266   Parse *pTop = sqlite3ParseToplevel(pParse);
   93267   sqlite3 *db = pParse->db;   /* Database handle */
   93268   TriggerPrg *pPrg;           /* Value to return */
   93269   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
   93270   Vdbe *v;                    /* Temporary VM */
   93271   NameContext sNC;            /* Name context for sub-vdbe */
   93272   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
   93273   Parse *pSubParse;           /* Parse context for sub-vdbe */
   93274   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
   93275 
   93276   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   93277   assert( pTop->pVdbe );
   93278 
   93279   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
   93280   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   93281   ** list of the top-level Parse object sooner rather than later.  */
   93282   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   93283   if( !pPrg ) return 0;
   93284   pPrg->pNext = pTop->pTriggerPrg;
   93285   pTop->pTriggerPrg = pPrg;
   93286   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
   93287   if( !pProgram ) return 0;
   93288   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
   93289   pPrg->pTrigger = pTrigger;
   93290   pPrg->orconf = orconf;
   93291   pPrg->aColmask[0] = 0xffffffff;
   93292   pPrg->aColmask[1] = 0xffffffff;
   93293 
   93294   /* Allocate and populate a new Parse context to use for coding the
   93295   ** trigger sub-program.  */
   93296   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   93297   if( !pSubParse ) return 0;
   93298   memset(&sNC, 0, sizeof(sNC));
   93299   sNC.pParse = pSubParse;
   93300   pSubParse->db = db;
   93301   pSubParse->pTriggerTab = pTab;
   93302   pSubParse->pToplevel = pTop;
   93303   pSubParse->zAuthContext = pTrigger->zName;
   93304   pSubParse->eTriggerOp = pTrigger->op;
   93305   pSubParse->nQueryLoop = pParse->nQueryLoop;
   93306 
   93307   v = sqlite3GetVdbe(pSubParse);
   93308   if( v ){
   93309     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
   93310       pTrigger->zName, onErrorText(orconf),
   93311       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
   93312         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
   93313         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
   93314         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
   93315       pTab->zName
   93316     ));
   93317 #ifndef SQLITE_OMIT_TRACE
   93318     sqlite3VdbeChangeP4(v, -1,
   93319       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
   93320     );
   93321 #endif
   93322 
   93323     /* If one was specified, code the WHEN clause. If it evaluates to false
   93324     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
   93325     ** OP_Halt inserted at the end of the program.  */
   93326     if( pTrigger->pWhen ){
   93327       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
   93328       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
   93329        && db->mallocFailed==0
   93330       ){
   93331         iEndTrigger = sqlite3VdbeMakeLabel(v);
   93332         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
   93333       }
   93334       sqlite3ExprDelete(db, pWhen);
   93335     }
   93336 
   93337     /* Code the trigger program into the sub-vdbe. */
   93338     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
   93339 
   93340     /* Insert an OP_Halt at the end of the sub-program. */
   93341     if( iEndTrigger ){
   93342       sqlite3VdbeResolveLabel(v, iEndTrigger);
   93343     }
   93344     sqlite3VdbeAddOp0(v, OP_Halt);
   93345     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
   93346 
   93347     transferParseError(pParse, pSubParse);
   93348     if( db->mallocFailed==0 ){
   93349       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
   93350     }
   93351     pProgram->nMem = pSubParse->nMem;
   93352     pProgram->nCsr = pSubParse->nTab;
   93353     pProgram->token = (void *)pTrigger;
   93354     pPrg->aColmask[0] = pSubParse->oldmask;
   93355     pPrg->aColmask[1] = pSubParse->newmask;
   93356     sqlite3VdbeDelete(v);
   93357   }
   93358 
   93359   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   93360   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
   93361   sqlite3StackFree(db, pSubParse);
   93362 
   93363   return pPrg;
   93364 }
   93365 
   93366 /*
   93367 ** Return a pointer to a TriggerPrg object containing the sub-program for
   93368 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
   93369 ** TriggerPrg object exists, a new object is allocated and populated before
   93370 ** being returned.
   93371 */
   93372 static TriggerPrg *getRowTrigger(
   93373   Parse *pParse,       /* Current parse context */
   93374   Trigger *pTrigger,   /* Trigger to code */
   93375   Table *pTab,         /* The table trigger pTrigger is attached to */
   93376   int orconf           /* ON CONFLICT algorithm. */
   93377 ){
   93378   Parse *pRoot = sqlite3ParseToplevel(pParse);
   93379   TriggerPrg *pPrg;
   93380 
   93381   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
   93382 
   93383   /* It may be that this trigger has already been coded (or is in the
   93384   ** process of being coded). If this is the case, then an entry with
   93385   ** a matching TriggerPrg.pTrigger field will be present somewhere
   93386   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
   93387   for(pPrg=pRoot->pTriggerPrg;
   93388       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
   93389       pPrg=pPrg->pNext
   93390   );
   93391 
   93392   /* If an existing TriggerPrg could not be located, create a new one. */
   93393   if( !pPrg ){
   93394     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
   93395   }
   93396 
   93397   return pPrg;
   93398 }
   93399 
   93400 /*
   93401 ** Generate code for the trigger program associated with trigger p on
   93402 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
   93403 ** function are the same as those described in the header function for
   93404 ** sqlite3CodeRowTrigger()
   93405 */
   93406 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   93407   Parse *pParse,       /* Parse context */
   93408   Trigger *p,          /* Trigger to code */
   93409   Table *pTab,         /* The table to code triggers from */
   93410   int reg,             /* Reg array containing OLD.* and NEW.* values */
   93411   int orconf,          /* ON CONFLICT policy */
   93412   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   93413 ){
   93414   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
   93415   TriggerPrg *pPrg;
   93416   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   93417   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
   93418 
   93419   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   93420   ** is a pointer to the sub-vdbe containing the trigger program.  */
   93421   if( pPrg ){
   93422     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
   93423 
   93424     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
   93425     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
   93426     VdbeComment(
   93427         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
   93428 
   93429     /* Set the P5 operand of the OP_Program instruction to non-zero if
   93430     ** recursive invocation of this trigger program is disallowed. Recursive
   93431     ** invocation is disallowed if (a) the sub-program is really a trigger,
   93432     ** not a foreign key action, and (b) the flag to enable recursive triggers
   93433     ** is clear.  */
   93434     sqlite3VdbeChangeP5(v, (u8)bRecursive);
   93435   }
   93436 }
   93437 
   93438 /*
   93439 ** This is called to code the required FOR EACH ROW triggers for an operation
   93440 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
   93441 ** is given by the op paramater. The tr_tm parameter determines whether the
   93442 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
   93443 ** parameter pChanges is passed the list of columns being modified.
   93444 **
   93445 ** If there are no triggers that fire at the specified time for the specified
   93446 ** operation on pTab, this function is a no-op.
   93447 **
   93448 ** The reg argument is the address of the first in an array of registers
   93449 ** that contain the values substituted for the new.* and old.* references
   93450 ** in the trigger program. If N is the number of columns in table pTab
   93451 ** (a copy of pTab->nCol), then registers are populated as follows:
   93452 **
   93453 **   Register       Contains
   93454 **   ------------------------------------------------------
   93455 **   reg+0          OLD.rowid
   93456 **   reg+1          OLD.* value of left-most column of pTab
   93457 **   ...            ...
   93458 **   reg+N          OLD.* value of right-most column of pTab
   93459 **   reg+N+1        NEW.rowid
   93460 **   reg+N+2        OLD.* value of left-most column of pTab
   93461 **   ...            ...
   93462 **   reg+N+N+1      NEW.* value of right-most column of pTab
   93463 **
   93464 ** For ON DELETE triggers, the registers containing the NEW.* values will
   93465 ** never be accessed by the trigger program, so they are not allocated or
   93466 ** populated by the caller (there is no data to populate them with anyway).
   93467 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
   93468 ** are never accessed, and so are not allocated by the caller. So, for an
   93469 ** ON INSERT trigger, the value passed to this function as parameter reg
   93470 ** is not a readable register, although registers (reg+N) through
   93471 ** (reg+N+N+1) are.
   93472 **
   93473 ** Parameter orconf is the default conflict resolution algorithm for the
   93474 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
   93475 ** is the instruction that control should jump to if a trigger program
   93476 ** raises an IGNORE exception.
   93477 */
   93478 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
   93479   Parse *pParse,       /* Parse context */
   93480   Trigger *pTrigger,   /* List of triggers on table pTab */
   93481   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
   93482   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   93483   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
   93484   Table *pTab,         /* The table to code triggers from */
   93485   int reg,             /* The first in an array of registers (see above) */
   93486   int orconf,          /* ON CONFLICT policy */
   93487   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
   93488 ){
   93489   Trigger *p;          /* Used to iterate through pTrigger list */
   93490 
   93491   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
   93492   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
   93493   assert( (op==TK_UPDATE)==(pChanges!=0) );
   93494 
   93495   for(p=pTrigger; p; p=p->pNext){
   93496 
   93497     /* Sanity checking:  The schema for the trigger and for the table are
   93498     ** always defined.  The trigger must be in the same schema as the table
   93499     ** or else it must be a TEMP trigger. */
   93500     assert( p->pSchema!=0 );
   93501     assert( p->pTabSchema!=0 );
   93502     assert( p->pSchema==p->pTabSchema
   93503          || p->pSchema==pParse->db->aDb[1].pSchema );
   93504 
   93505     /* Determine whether we should code this trigger */
   93506     if( p->op==op
   93507      && p->tr_tm==tr_tm
   93508      && checkColumnOverlap(p->pColumns, pChanges)
   93509     ){
   93510       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
   93511     }
   93512   }
   93513 }
   93514 
   93515 /*
   93516 ** Triggers may access values stored in the old.* or new.* pseudo-table.
   93517 ** This function returns a 32-bit bitmask indicating which columns of the
   93518 ** old.* or new.* tables actually are used by triggers. This information
   93519 ** may be used by the caller, for example, to avoid having to load the entire
   93520 ** old.* record into memory when executing an UPDATE or DELETE command.
   93521 **
   93522 ** Bit 0 of the returned mask is set if the left-most column of the
   93523 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
   93524 ** the second leftmost column value is required, and so on. If there
   93525 ** are more than 32 columns in the table, and at least one of the columns
   93526 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
   93527 **
   93528 ** It is not possible to determine if the old.rowid or new.rowid column is
   93529 ** accessed by triggers. The caller must always assume that it is.
   93530 **
   93531 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
   93532 ** applies to the old.* table. If 1, the new.* table.
   93533 **
   93534 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
   93535 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
   93536 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
   93537 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
   93538 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
   93539 */
   93540 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
   93541   Parse *pParse,       /* Parse context */
   93542   Trigger *pTrigger,   /* List of triggers on table pTab */
   93543   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
   93544   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
   93545   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   93546   Table *pTab,         /* The table to code triggers from */
   93547   int orconf           /* Default ON CONFLICT policy for trigger steps */
   93548 ){
   93549   const int op = pChanges ? TK_UPDATE : TK_DELETE;
   93550   u32 mask = 0;
   93551   Trigger *p;
   93552 
   93553   assert( isNew==1 || isNew==0 );
   93554   for(p=pTrigger; p; p=p->pNext){
   93555     if( p->op==op && (tr_tm&p->tr_tm)
   93556      && checkColumnOverlap(p->pColumns,pChanges)
   93557     ){
   93558       TriggerPrg *pPrg;
   93559       pPrg = getRowTrigger(pParse, p, pTab, orconf);
   93560       if( pPrg ){
   93561         mask |= pPrg->aColmask[isNew];
   93562       }
   93563     }
   93564   }
   93565 
   93566   return mask;
   93567 }
   93568 
   93569 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   93570 
   93571 /************** End of trigger.c *********************************************/
   93572 /************** Begin file update.c ******************************************/
   93573 /*
   93574 ** 2001 September 15
   93575 **
   93576 ** The author disclaims copyright to this source code.  In place of
   93577 ** a legal notice, here is a blessing:
   93578 **
   93579 **    May you do good and not evil.
   93580 **    May you find forgiveness for yourself and forgive others.
   93581 **    May you share freely, never taking more than you give.
   93582 **
   93583 *************************************************************************
   93584 ** This file contains C code routines that are called by the parser
   93585 ** to handle UPDATE statements.
   93586 */
   93587 
   93588 #ifndef SQLITE_OMIT_VIRTUALTABLE
   93589 /* Forward declaration */
   93590 static void updateVirtualTable(
   93591   Parse *pParse,       /* The parsing context */
   93592   SrcList *pSrc,       /* The virtual table to be modified */
   93593   Table *pTab,         /* The virtual table */
   93594   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   93595   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
   93596   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   93597   Expr *pWhere         /* WHERE clause of the UPDATE statement */
   93598 );
   93599 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   93600 
   93601 /*
   93602 ** The most recently coded instruction was an OP_Column to retrieve the
   93603 ** i-th column of table pTab. This routine sets the P4 parameter of the
   93604 ** OP_Column to the default value, if any.
   93605 **
   93606 ** The default value of a column is specified by a DEFAULT clause in the
   93607 ** column definition. This was either supplied by the user when the table
   93608 ** was created, or added later to the table definition by an ALTER TABLE
   93609 ** command. If the latter, then the row-records in the table btree on disk
   93610 ** may not contain a value for the column and the default value, taken
   93611 ** from the P4 parameter of the OP_Column instruction, is returned instead.
   93612 ** If the former, then all row-records are guaranteed to include a value
   93613 ** for the column and the P4 value is not required.
   93614 **
   93615 ** Column definitions created by an ALTER TABLE command may only have
   93616 ** literal default values specified: a number, null or a string. (If a more
   93617 ** complicated default expression value was provided, it is evaluated
   93618 ** when the ALTER TABLE is executed and one of the literal values written
   93619 ** into the sqlite_master table.)
   93620 **
   93621 ** Therefore, the P4 parameter is only required if the default value for
   93622 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
   93623 ** function is capable of transforming these types of expressions into
   93624 ** sqlite3_value objects.
   93625 **
   93626 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
   93627 ** on register iReg. This is used when an equivalent integer value is
   93628 ** stored in place of an 8-byte floating point value in order to save
   93629 ** space.
   93630 */
   93631 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   93632   assert( pTab!=0 );
   93633   if( !pTab->pSelect ){
   93634     sqlite3_value *pValue;
   93635     u8 enc = ENC(sqlite3VdbeDb(v));
   93636     Column *pCol = &pTab->aCol[i];
   93637     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
   93638     assert( i<pTab->nCol );
   93639     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
   93640                          pCol->affinity, &pValue);
   93641     if( pValue ){
   93642       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
   93643     }
   93644 #ifndef SQLITE_OMIT_FLOATING_POINT
   93645     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
   93646       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   93647     }
   93648 #endif
   93649   }
   93650 }
   93651 
   93652 /*
   93653 ** Process an UPDATE statement.
   93654 **
   93655 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
   93656 **          \_______/ \________/     \______/       \________________/
   93657 *            onError   pTabList      pChanges             pWhere
   93658 */
   93659 SQLITE_PRIVATE void sqlite3Update(
   93660   Parse *pParse,         /* The parser context */
   93661   SrcList *pTabList,     /* The table in which we should change things */
   93662   ExprList *pChanges,    /* Things to be changed */
   93663   Expr *pWhere,          /* The WHERE clause.  May be null */
   93664   int onError            /* How to handle constraint errors */
   93665 ){
   93666   int i, j;              /* Loop counters */
   93667   Table *pTab;           /* The table to be updated */
   93668   int addr = 0;          /* VDBE instruction address of the start of the loop */
   93669   WhereInfo *pWInfo;     /* Information about the WHERE clause */
   93670   Vdbe *v;               /* The virtual database engine */
   93671   Index *pIdx;           /* For looping over indices */
   93672   int nIdx;              /* Number of indices that need updating */
   93673   int iCur;              /* VDBE Cursor number of pTab */
   93674   sqlite3 *db;           /* The database structure */
   93675   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
   93676   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
   93677                          ** an expression for the i-th column of the table.
   93678                          ** aXRef[i]==-1 if the i-th column is not changed. */
   93679   int chngRowid;         /* True if the record number is being changed */
   93680   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
   93681   int openAll = 0;       /* True if all indices need to be opened */
   93682   AuthContext sContext;  /* The authorization context */
   93683   NameContext sNC;       /* The name-context to resolve expressions in */
   93684   int iDb;               /* Database containing the table being updated */
   93685   int okOnePass;         /* True for one-pass algorithm without the FIFO */
   93686   int hasFK;             /* True if foreign key processing is required */
   93687 
   93688 #ifndef SQLITE_OMIT_TRIGGER
   93689   int isView;            /* True when updating a view (INSTEAD OF trigger) */
   93690   Trigger *pTrigger;     /* List of triggers on pTab, if required */
   93691   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
   93692 #endif
   93693   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
   93694 
   93695   /* Register Allocations */
   93696   int regRowCount = 0;   /* A count of rows changed */
   93697   int regOldRowid;       /* The old rowid */
   93698   int regNewRowid;       /* The new rowid */
   93699   int regNew;
   93700   int regOld = 0;
   93701   int regRowSet = 0;     /* Rowset of rows to be updated */
   93702   int regRec;            /* Register used for new table record to insert */
   93703 
   93704   memset(&sContext, 0, sizeof(sContext));
   93705   db = pParse->db;
   93706   if( pParse->nErr || db->mallocFailed ){
   93707     goto update_cleanup;
   93708   }
   93709   assert( pTabList->nSrc==1 );
   93710 
   93711   /* Locate the table which we want to update.
   93712   */
   93713   pTab = sqlite3SrcListLookup(pParse, pTabList);
   93714   if( pTab==0 ) goto update_cleanup;
   93715   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
   93716 
   93717   /* Figure out if we have any triggers and if the table being
   93718   ** updated is a view.
   93719   */
   93720 #ifndef SQLITE_OMIT_TRIGGER
   93721   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
   93722   isView = pTab->pSelect!=0;
   93723   assert( pTrigger || tmask==0 );
   93724 #else
   93725 # define pTrigger 0
   93726 # define isView 0
   93727 # define tmask 0
   93728 #endif
   93729 #ifdef SQLITE_OMIT_VIEW
   93730 # undef isView
   93731 # define isView 0
   93732 #endif
   93733 
   93734   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
   93735     goto update_cleanup;
   93736   }
   93737   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
   93738     goto update_cleanup;
   93739   }
   93740   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
   93741   if( aXRef==0 ) goto update_cleanup;
   93742   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   93743 
   93744   /* Allocate a cursors for the main database table and for all indices.
   93745   ** The index cursors might not be used, but if they are used they
   93746   ** need to occur right after the database cursor.  So go ahead and
   93747   ** allocate enough space, just in case.
   93748   */
   93749   pTabList->a[0].iCursor = iCur = pParse->nTab++;
   93750   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   93751     pParse->nTab++;
   93752   }
   93753 
   93754   /* Initialize the name-context */
   93755   memset(&sNC, 0, sizeof(sNC));
   93756   sNC.pParse = pParse;
   93757   sNC.pSrcList = pTabList;
   93758 
   93759   /* Resolve the column names in all the expressions of the
   93760   ** of the UPDATE statement.  Also find the column index
   93761   ** for each column to be updated in the pChanges array.  For each
   93762   ** column to be updated, make sure we have authorization to change
   93763   ** that column.
   93764   */
   93765   chngRowid = 0;
   93766   for(i=0; i<pChanges->nExpr; i++){
   93767     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
   93768       goto update_cleanup;
   93769     }
   93770     for(j=0; j<pTab->nCol; j++){
   93771       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   93772         if( j==pTab->iPKey ){
   93773           chngRowid = 1;
   93774           pRowidExpr = pChanges->a[i].pExpr;
   93775         }
   93776         aXRef[j] = i;
   93777         break;
   93778       }
   93779     }
   93780     if( j>=pTab->nCol ){
   93781       if( sqlite3IsRowid(pChanges->a[i].zName) ){
   93782         chngRowid = 1;
   93783         pRowidExpr = pChanges->a[i].pExpr;
   93784       }else{
   93785         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
   93786         pParse->checkSchema = 1;
   93787         goto update_cleanup;
   93788       }
   93789     }
   93790 #ifndef SQLITE_OMIT_AUTHORIZATION
   93791     {
   93792       int rc;
   93793       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
   93794                            pTab->aCol[j].zName, db->aDb[iDb].zName);
   93795       if( rc==SQLITE_DENY ){
   93796         goto update_cleanup;
   93797       }else if( rc==SQLITE_IGNORE ){
   93798         aXRef[j] = -1;
   93799       }
   93800     }
   93801 #endif
   93802   }
   93803 
   93804   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
   93805 
   93806   /* Allocate memory for the array aRegIdx[].  There is one entry in the
   93807   ** array for each index associated with table being updated.  Fill in
   93808   ** the value with a register number for indices that are to be used
   93809   ** and with zero for unused indices.
   93810   */
   93811   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   93812   if( nIdx>0 ){
   93813     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   93814     if( aRegIdx==0 ) goto update_cleanup;
   93815   }
   93816   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   93817     int reg;
   93818     if( chngRowid ){
   93819       reg = ++pParse->nMem;
   93820     }else{
   93821       reg = 0;
   93822       for(i=0; i<pIdx->nColumn; i++){
   93823         if( aXRef[pIdx->aiColumn[i]]>=0 ){
   93824           reg = ++pParse->nMem;
   93825           break;
   93826         }
   93827       }
   93828     }
   93829     aRegIdx[j] = reg;
   93830   }
   93831 
   93832   /* Begin generating code. */
   93833   v = sqlite3GetVdbe(pParse);
   93834   if( v==0 ) goto update_cleanup;
   93835   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   93836   sqlite3BeginWriteOperation(pParse, 1, iDb);
   93837 
   93838 #ifndef SQLITE_OMIT_VIRTUALTABLE
   93839   /* Virtual tables must be handled separately */
   93840   if( IsVirtual(pTab) ){
   93841     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
   93842                        pWhere);
   93843     pWhere = 0;
   93844     pTabList = 0;
   93845     goto update_cleanup;
   93846   }
   93847 #endif
   93848 
   93849   /* Allocate required registers. */
   93850   regOldRowid = regNewRowid = ++pParse->nMem;
   93851   if( pTrigger || hasFK ){
   93852     regOld = pParse->nMem + 1;
   93853     pParse->nMem += pTab->nCol;
   93854   }
   93855   if( chngRowid || pTrigger || hasFK ){
   93856     regNewRowid = ++pParse->nMem;
   93857   }
   93858   regNew = pParse->nMem + 1;
   93859   pParse->nMem += pTab->nCol;
   93860   regRec = ++pParse->nMem;
   93861 
   93862   /* Start the view context. */
   93863   if( isView ){
   93864     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
   93865   }
   93866 
   93867   /* If we are trying to update a view, realize that view into
   93868   ** a ephemeral table.
   93869   */
   93870 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   93871   if( isView ){
   93872     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
   93873   }
   93874 #endif
   93875 
   93876   /* Resolve the column names in all the expressions in the
   93877   ** WHERE clause.
   93878   */
   93879   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
   93880     goto update_cleanup;
   93881   }
   93882 
   93883   /* Begin the database scan
   93884   */
   93885   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
   93886   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
   93887   if( pWInfo==0 ) goto update_cleanup;
   93888   okOnePass = pWInfo->okOnePass;
   93889 
   93890   /* Remember the rowid of every item to be updated.
   93891   */
   93892   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
   93893   if( !okOnePass ){
   93894     regRowSet = ++pParse->nMem;
   93895     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
   93896   }
   93897 
   93898   /* End the database scan loop.
   93899   */
   93900   sqlite3WhereEnd(pWInfo);
   93901 
   93902   /* Initialize the count of updated rows
   93903   */
   93904   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
   93905     regRowCount = ++pParse->nMem;
   93906     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   93907   }
   93908 
   93909   if( !isView ){
   93910     /*
   93911     ** Open every index that needs updating.  Note that if any
   93912     ** index could potentially invoke a REPLACE conflict resolution
   93913     ** action, then we need to open all indices because we might need
   93914     ** to be deleting some records.
   93915     */
   93916     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
   93917     if( onError==OE_Replace ){
   93918       openAll = 1;
   93919     }else{
   93920       openAll = 0;
   93921       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   93922         if( pIdx->onError==OE_Replace ){
   93923           openAll = 1;
   93924           break;
   93925         }
   93926       }
   93927     }
   93928     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   93929       if( openAll || aRegIdx[i]>0 ){
   93930         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   93931         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
   93932                        (char*)pKey, P4_KEYINFO_HANDOFF);
   93933         assert( pParse->nTab>iCur+i+1 );
   93934       }
   93935     }
   93936   }
   93937 
   93938   /* Top of the update loop */
   93939   if( okOnePass ){
   93940     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
   93941     addr = sqlite3VdbeAddOp0(v, OP_Goto);
   93942     sqlite3VdbeJumpHere(v, a1);
   93943   }else{
   93944     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
   93945   }
   93946 
   93947   /* Make cursor iCur point to the record that is being updated. If
   93948   ** this record does not exist for some reason (deleted by a trigger,
   93949   ** for example, then jump to the next iteration of the RowSet loop.  */
   93950   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   93951 
   93952   /* If the record number will change, set register regNewRowid to
   93953   ** contain the new value. If the record number is not being modified,
   93954   ** then regNewRowid is the same register as regOldRowid, which is
   93955   ** already populated.  */
   93956   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
   93957   if( chngRowid ){
   93958     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   93959     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
   93960   }
   93961 
   93962   /* If there are triggers on this table, populate an array of registers
   93963   ** with the required old.* column data.  */
   93964   if( hasFK || pTrigger ){
   93965     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   93966     oldmask |= sqlite3TriggerColmask(pParse,
   93967         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
   93968     );
   93969     for(i=0; i<pTab->nCol; i++){
   93970       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
   93971         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
   93972       }else{
   93973         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
   93974       }
   93975     }
   93976     if( chngRowid==0 ){
   93977       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
   93978     }
   93979   }
   93980 
   93981   /* Populate the array of registers beginning at regNew with the new
   93982   ** row data. This array is used to check constaints, create the new
   93983   ** table and index records, and as the values for any new.* references
   93984   ** made by triggers.
   93985   **
   93986   ** If there are one or more BEFORE triggers, then do not populate the
   93987   ** registers associated with columns that are (a) not modified by
   93988   ** this UPDATE statement and (b) not accessed by new.* references. The
   93989   ** values for registers not modified by the UPDATE must be reloaded from
   93990   ** the database after the BEFORE triggers are fired anyway (as the trigger
   93991   ** may have modified them). So not loading those that are not going to
   93992   ** be used eliminates some redundant opcodes.
   93993   */
   93994   newmask = sqlite3TriggerColmask(
   93995       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   93996   );
   93997   for(i=0; i<pTab->nCol; i++){
   93998     if( i==pTab->iPKey ){
   93999       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
   94000     }else{
   94001       j = aXRef[i];
   94002       if( j>=0 ){
   94003         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
   94004       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
   94005         /* This branch loads the value of a column that will not be changed
   94006         ** into a register. This is done if there are no BEFORE triggers, or
   94007         ** if there are one or more BEFORE triggers that use this value via
   94008         ** a new.* reference in a trigger program.
   94009         */
   94010         testcase( i==31 );
   94011         testcase( i==32 );
   94012         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   94013         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   94014       }
   94015     }
   94016   }
   94017 
   94018   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   94019   ** verified. One could argue that this is wrong.
   94020   */
   94021   if( tmask&TRIGGER_BEFORE ){
   94022     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
   94023     sqlite3TableAffinityStr(v, pTab);
   94024     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   94025         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
   94026 
   94027     /* The row-trigger may have deleted the row being updated. In this
   94028     ** case, jump to the next row. No updates or AFTER triggers are
   94029     ** required. This behaviour - what happens when the row being updated
   94030     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   94031     ** documentation.
   94032     */
   94033     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
   94034 
   94035     /* If it did not delete it, the row-trigger may still have modified
   94036     ** some of the columns of the row being updated. Load the values for
   94037     ** all columns not modified by the update statement into their
   94038     ** registers in case this has happened.
   94039     */
   94040     for(i=0; i<pTab->nCol; i++){
   94041       if( aXRef[i]<0 && i!=pTab->iPKey ){
   94042         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
   94043         sqlite3ColumnDefault(v, pTab, i, regNew+i);
   94044       }
   94045     }
   94046   }
   94047 
   94048   if( !isView ){
   94049     int j1;                       /* Address of jump instruction */
   94050 
   94051     /* Do constraint checks. */
   94052     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
   94053         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
   94054 
   94055     /* Do FK constraint checks. */
   94056     if( hasFK ){
   94057       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
   94058     }
   94059 
   94060     /* Delete the index entries associated with the current record.  */
   94061     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
   94062     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
   94063 
   94064     /* If changing the record number, delete the old record.  */
   94065     if( hasFK || chngRowid ){
   94066       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
   94067     }
   94068     sqlite3VdbeJumpHere(v, j1);
   94069 
   94070     if( hasFK ){
   94071       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
   94072     }
   94073 
   94074     /* Insert the new index entries and the new record. */
   94075     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
   94076 
   94077     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   94078     ** handle rows (possibly in other tables) that refer via a foreign key
   94079     ** to the row just updated. */
   94080     if( hasFK ){
   94081       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
   94082     }
   94083   }
   94084 
   94085   /* Increment the row counter
   94086   */
   94087   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
   94088     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   94089   }
   94090 
   94091   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
   94092       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
   94093 
   94094   /* Repeat the above with the next record to be updated, until
   94095   ** all record selected by the WHERE clause have been updated.
   94096   */
   94097   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   94098   sqlite3VdbeJumpHere(v, addr);
   94099 
   94100   /* Close all tables */
   94101   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
   94102     if( openAll || aRegIdx[i]>0 ){
   94103       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
   94104     }
   94105   }
   94106   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
   94107 
   94108   /* Update the sqlite_sequence table by storing the content of the
   94109   ** maximum rowid counter values recorded while inserting into
   94110   ** autoincrement tables.
   94111   */
   94112   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
   94113     sqlite3AutoincrementEnd(pParse);
   94114   }
   94115 
   94116   /*
   94117   ** Return the number of rows that were changed. If this routine is
   94118   ** generating code because of a call to sqlite3NestedParse(), do not
   94119   ** invoke the callback function.
   94120   */
   94121   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
   94122     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
   94123     sqlite3VdbeSetNumCols(v, 1);
   94124     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
   94125   }
   94126 
   94127 update_cleanup:
   94128   sqlite3AuthContextPop(&sContext);
   94129   sqlite3DbFree(db, aRegIdx);
   94130   sqlite3DbFree(db, aXRef);
   94131   sqlite3SrcListDelete(db, pTabList);
   94132   sqlite3ExprListDelete(db, pChanges);
   94133   sqlite3ExprDelete(db, pWhere);
   94134   return;
   94135 }
   94136 /* Make sure "isView" and other macros defined above are undefined. Otherwise
   94137 ** thely may interfere with compilation of other functions in this file
   94138 ** (or in another file, if this file becomes part of the amalgamation).  */
   94139 #ifdef isView
   94140  #undef isView
   94141 #endif
   94142 #ifdef pTrigger
   94143  #undef pTrigger
   94144 #endif
   94145 
   94146 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94147 /*
   94148 ** Generate code for an UPDATE of a virtual table.
   94149 **
   94150 ** The strategy is that we create an ephemerial table that contains
   94151 ** for each row to be changed:
   94152 **
   94153 **   (A)  The original rowid of that row.
   94154 **   (B)  The revised rowid for the row. (note1)
   94155 **   (C)  The content of every column in the row.
   94156 **
   94157 ** Then we loop over this ephemeral table and for each row in
   94158 ** the ephermeral table call VUpdate.
   94159 **
   94160 ** When finished, drop the ephemeral table.
   94161 **
   94162 ** (note1) Actually, if we know in advance that (A) is always the same
   94163 ** as (B) we only store (A), then duplicate (A) when pulling
   94164 ** it out of the ephemeral table before calling VUpdate.
   94165 */
   94166 static void updateVirtualTable(
   94167   Parse *pParse,       /* The parsing context */
   94168   SrcList *pSrc,       /* The virtual table to be modified */
   94169   Table *pTab,         /* The virtual table */
   94170   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
   94171   Expr *pRowid,        /* Expression used to recompute the rowid */
   94172   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
   94173   Expr *pWhere         /* WHERE clause of the UPDATE statement */
   94174 ){
   94175   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
   94176   ExprList *pEList = 0;     /* The result set of the SELECT statement */
   94177   Select *pSelect = 0;      /* The SELECT statement */
   94178   Expr *pExpr;              /* Temporary expression */
   94179   int ephemTab;             /* Table holding the result of the SELECT */
   94180   int i;                    /* Loop counter */
   94181   int addr;                 /* Address of top of loop */
   94182   int iReg;                 /* First register in set passed to OP_VUpdate */
   94183   sqlite3 *db = pParse->db; /* Database connection */
   94184   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
   94185   SelectDest dest;
   94186 
   94187   /* Construct the SELECT statement that will find the new values for
   94188   ** all updated rows.
   94189   */
   94190   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
   94191   if( pRowid ){
   94192     pEList = sqlite3ExprListAppend(pParse, pEList,
   94193                                    sqlite3ExprDup(db, pRowid, 0));
   94194   }
   94195   assert( pTab->iPKey<0 );
   94196   for(i=0; i<pTab->nCol; i++){
   94197     if( aXRef[i]>=0 ){
   94198       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
   94199     }else{
   94200       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
   94201     }
   94202     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
   94203   }
   94204   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
   94205 
   94206   /* Create the ephemeral table into which the update results will
   94207   ** be stored.
   94208   */
   94209   assert( v );
   94210   ephemTab = pParse->nTab++;
   94211   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
   94212   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
   94213 
   94214   /* fill the ephemeral table
   94215   */
   94216   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   94217   sqlite3Select(pParse, pSelect, &dest);
   94218 
   94219   /* Generate code to scan the ephemeral table and call VUpdate. */
   94220   iReg = ++pParse->nMem;
   94221   pParse->nMem += pTab->nCol+1;
   94222   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
   94223   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   94224   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   94225   for(i=0; i<pTab->nCol; i++){
   94226     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   94227   }
   94228   sqlite3VtabMakeWritable(pParse, pTab);
   94229   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   94230   sqlite3MayAbort(pParse);
   94231   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
   94232   sqlite3VdbeJumpHere(v, addr);
   94233   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   94234 
   94235   /* Cleanup */
   94236   sqlite3SelectDelete(db, pSelect);
   94237 }
   94238 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   94239 
   94240 /************** End of update.c **********************************************/
   94241 /************** Begin file vacuum.c ******************************************/
   94242 /*
   94243 ** 2003 April 6
   94244 **
   94245 ** The author disclaims copyright to this source code.  In place of
   94246 ** a legal notice, here is a blessing:
   94247 **
   94248 **    May you do good and not evil.
   94249 **    May you find forgiveness for yourself and forgive others.
   94250 **    May you share freely, never taking more than you give.
   94251 **
   94252 *************************************************************************
   94253 ** This file contains code used to implement the VACUUM command.
   94254 **
   94255 ** Most of the code in this file may be omitted by defining the
   94256 ** SQLITE_OMIT_VACUUM macro.
   94257 */
   94258 
   94259 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
   94260 /*
   94261 ** Finalize a prepared statement.  If there was an error, store the
   94262 ** text of the error message in *pzErrMsg.  Return the result code.
   94263 */
   94264 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
   94265   int rc;
   94266   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
   94267   if( rc ){
   94268     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   94269   }
   94270   return rc;
   94271 }
   94272 
   94273 /*
   94274 ** Execute zSql on database db. Return an error code.
   94275 */
   94276 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   94277   sqlite3_stmt *pStmt;
   94278   VVA_ONLY( int rc; )
   94279   if( !zSql ){
   94280     return SQLITE_NOMEM;
   94281   }
   94282   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
   94283     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
   94284     return sqlite3_errcode(db);
   94285   }
   94286   VVA_ONLY( rc = ) sqlite3_step(pStmt);
   94287   assert( rc!=SQLITE_ROW );
   94288   return vacuumFinalize(db, pStmt, pzErrMsg);
   94289 }
   94290 
   94291 /*
   94292 ** Execute zSql on database db. The statement returns exactly
   94293 ** one column. Execute this as SQL on the same database.
   94294 */
   94295 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
   94296   sqlite3_stmt *pStmt;
   94297   int rc;
   94298 
   94299   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
   94300   if( rc!=SQLITE_OK ) return rc;
   94301 
   94302   while( SQLITE_ROW==sqlite3_step(pStmt) ){
   94303     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
   94304     if( rc!=SQLITE_OK ){
   94305       vacuumFinalize(db, pStmt, pzErrMsg);
   94306       return rc;
   94307     }
   94308   }
   94309 
   94310   return vacuumFinalize(db, pStmt, pzErrMsg);
   94311 }
   94312 
   94313 /*
   94314 ** The non-standard VACUUM command is used to clean up the database,
   94315 ** collapse free space, etc.  It is modelled after the VACUUM command
   94316 ** in PostgreSQL.
   94317 **
   94318 ** In version 1.0.x of SQLite, the VACUUM command would call
   94319 ** gdbm_reorganize() on all the database tables.  But beginning
   94320 ** with 2.0.0, SQLite no longer uses GDBM so this command has
   94321 ** become a no-op.
   94322 */
   94323 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
   94324   Vdbe *v = sqlite3GetVdbe(pParse);
   94325   if( v ){
   94326     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
   94327   }
   94328   return;
   94329 }
   94330 
   94331 /*
   94332 ** This routine implements the OP_Vacuum opcode of the VDBE.
   94333 */
   94334 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
   94335   int rc = SQLITE_OK;     /* Return code from service routines */
   94336   Btree *pMain;           /* The database being vacuumed */
   94337   Btree *pTemp;           /* The temporary database we vacuum into */
   94338   char *zSql = 0;         /* SQL statements */
   94339   int saved_flags;        /* Saved value of the db->flags */
   94340   int saved_nChange;      /* Saved value of db->nChange */
   94341   int saved_nTotalChange; /* Saved value of db->nTotalChange */
   94342   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
   94343   Db *pDb = 0;            /* Database to detach at end of vacuum */
   94344   int isMemDb;            /* True if vacuuming a :memory: database */
   94345   int nRes;               /* Bytes of reserved space at the end of each page */
   94346   int nDb;                /* Number of attached databases */
   94347 
   94348   if( !db->autoCommit ){
   94349     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
   94350     return SQLITE_ERROR;
   94351   }
   94352   if( db->activeVdbeCnt>1 ){
   94353     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
   94354     return SQLITE_ERROR;
   94355   }
   94356 
   94357   /* Save the current value of the database flags so that it can be
   94358   ** restored before returning. Then set the writable-schema flag, and
   94359   ** disable CHECK and foreign key constraints.  */
   94360   saved_flags = db->flags;
   94361   saved_nChange = db->nChange;
   94362   saved_nTotalChange = db->nTotalChange;
   94363   saved_xTrace = db->xTrace;
   94364   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
   94365   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
   94366   db->xTrace = 0;
   94367 
   94368   pMain = db->aDb[0].pBt;
   94369   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
   94370 
   94371   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
   94372   ** can be set to 'off' for this file, as it is not recovered if a crash
   94373   ** occurs anyway. The integrity of the database is maintained by a
   94374   ** (possibly synchronous) transaction opened on the main database before
   94375   ** sqlite3BtreeCopyFile() is called.
   94376   **
   94377   ** An optimisation would be to use a non-journaled pager.
   94378   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
   94379   ** that actually made the VACUUM run slower.  Very little journalling
   94380   ** actually occurs when doing a vacuum since the vacuum_db is initially
   94381   ** empty.  Only the journal header is written.  Apparently it takes more
   94382   ** time to parse and run the PRAGMA to turn journalling off than it does
   94383   ** to write the journal header file.
   94384   */
   94385   nDb = db->nDb;
   94386   if( sqlite3TempInMemory(db) ){
   94387     zSql = "ATTACH ':memory:' AS vacuum_db;";
   94388   }else{
   94389     zSql = "ATTACH '' AS vacuum_db;";
   94390   }
   94391   rc = execSql(db, pzErrMsg, zSql);
   94392   if( db->nDb>nDb ){
   94393     pDb = &db->aDb[db->nDb-1];
   94394     assert( strcmp(pDb->zName,"vacuum_db")==0 );
   94395   }
   94396   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94397   pTemp = db->aDb[db->nDb-1].pBt;
   94398 
   94399   /* The call to execSql() to attach the temp database has left the file
   94400   ** locked (as there was more than one active statement when the transaction
   94401   ** to read the schema was concluded. Unlock it here so that this doesn't
   94402   ** cause problems for the call to BtreeSetPageSize() below.  */
   94403   sqlite3BtreeCommit(pTemp);
   94404 
   94405   nRes = sqlite3BtreeGetReserve(pMain);
   94406 
   94407   /* A VACUUM cannot change the pagesize of an encrypted database. */
   94408 #ifdef SQLITE_HAS_CODEC
   94409   if( db->nextPagesize ){
   94410     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
   94411     int nKey;
   94412     char *zKey;
   94413     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
   94414     if( nKey ) db->nextPagesize = 0;
   94415   }
   94416 #endif
   94417 
   94418   /* Do not attempt to change the page size for a WAL database */
   94419   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
   94420                                                ==PAGER_JOURNALMODE_WAL ){
   94421     db->nextPagesize = 0;
   94422   }
   94423 
   94424   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
   94425    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
   94426    || NEVER(db->mallocFailed)
   94427   ){
   94428     rc = SQLITE_NOMEM;
   94429     goto end_of_vacuum;
   94430   }
   94431   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
   94432   if( rc!=SQLITE_OK ){
   94433     goto end_of_vacuum;
   94434   }
   94435 
   94436 #ifndef SQLITE_OMIT_AUTOVACUUM
   94437   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
   94438                                            sqlite3BtreeGetAutoVacuum(pMain));
   94439 #endif
   94440 
   94441   /* Begin a transaction */
   94442   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
   94443   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94444 
   94445   /* Query the schema of the main database. Create a mirror schema
   94446   ** in the temporary database.
   94447   */
   94448   rc = execExecSql(db, pzErrMsg,
   94449       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
   94450       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
   94451       "   AND rootpage>0"
   94452   );
   94453   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94454   rc = execExecSql(db, pzErrMsg,
   94455       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
   94456       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
   94457   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94458   rc = execExecSql(db, pzErrMsg,
   94459       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
   94460       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
   94461   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94462 
   94463   /* Loop through the tables in the main database. For each, do
   94464   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
   94465   ** the contents to the temporary database.
   94466   */
   94467   rc = execExecSql(db, pzErrMsg,
   94468       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   94469       "|| ' SELECT * FROM main.' || quote(name) || ';'"
   94470       "FROM main.sqlite_master "
   94471       "WHERE type = 'table' AND name!='sqlite_sequence' "
   94472       "  AND rootpage>0"
   94473   );
   94474   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94475 
   94476   /* Copy over the sequence table
   94477   */
   94478   rc = execExecSql(db, pzErrMsg,
   94479       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
   94480       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
   94481   );
   94482   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94483   rc = execExecSql(db, pzErrMsg,
   94484       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
   94485       "|| ' SELECT * FROM main.' || quote(name) || ';' "
   94486       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
   94487   );
   94488   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94489 
   94490 
   94491   /* Copy the triggers, views, and virtual tables from the main database
   94492   ** over to the temporary database.  None of these objects has any
   94493   ** associated storage, so all we have to do is copy their entries
   94494   ** from the SQLITE_MASTER table.
   94495   */
   94496   rc = execSql(db, pzErrMsg,
   94497       "INSERT INTO vacuum_db.sqlite_master "
   94498       "  SELECT type, name, tbl_name, rootpage, sql"
   94499       "    FROM main.sqlite_master"
   94500       "   WHERE type='view' OR type='trigger'"
   94501       "      OR (type='table' AND rootpage=0)"
   94502   );
   94503   if( rc ) goto end_of_vacuum;
   94504 
   94505   /* At this point, unless the main db was completely empty, there is now a
   94506   ** transaction open on the vacuum database, but not on the main database.
   94507   ** Open a btree level transaction on the main database. This allows a
   94508   ** call to sqlite3BtreeCopyFile(). The main database btree level
   94509   ** transaction is then committed, so the SQL level never knows it was
   94510   ** opened for writing. This way, the SQL transaction used to create the
   94511   ** temporary database never needs to be committed.
   94512   */
   94513   {
   94514     u32 meta;
   94515     int i;
   94516 
   94517     /* This array determines which meta meta values are preserved in the
   94518     ** vacuum.  Even entries are the meta value number and odd entries
   94519     ** are an increment to apply to the meta value after the vacuum.
   94520     ** The increment is used to increase the schema cookie so that other
   94521     ** connections to the same database will know to reread the schema.
   94522     */
   94523     static const unsigned char aCopy[] = {
   94524        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
   94525        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
   94526        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
   94527        BTREE_USER_VERSION,       0,  /* Preserve the user version */
   94528     };
   94529 
   94530     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
   94531     assert( 1==sqlite3BtreeIsInTrans(pMain) );
   94532 
   94533     /* Copy Btree meta values */
   94534     for(i=0; i<ArraySize(aCopy); i+=2){
   94535       /* GetMeta() and UpdateMeta() cannot fail in this context because
   94536       ** we already have page 1 loaded into cache and marked dirty. */
   94537       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
   94538       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
   94539       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
   94540     }
   94541 
   94542     rc = sqlite3BtreeCopyFile(pMain, pTemp);
   94543     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94544     rc = sqlite3BtreeCommit(pTemp);
   94545     if( rc!=SQLITE_OK ) goto end_of_vacuum;
   94546 #ifndef SQLITE_OMIT_AUTOVACUUM
   94547     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
   94548 #endif
   94549   }
   94550 
   94551   assert( rc==SQLITE_OK );
   94552   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
   94553 
   94554 end_of_vacuum:
   94555   /* Restore the original value of db->flags */
   94556   db->flags = saved_flags;
   94557   db->nChange = saved_nChange;
   94558   db->nTotalChange = saved_nTotalChange;
   94559   db->xTrace = saved_xTrace;
   94560   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
   94561 
   94562   /* Currently there is an SQL level transaction open on the vacuum
   94563   ** database. No locks are held on any other files (since the main file
   94564   ** was committed at the btree level). So it safe to end the transaction
   94565   ** by manually setting the autoCommit flag to true and detaching the
   94566   ** vacuum database. The vacuum_db journal file is deleted when the pager
   94567   ** is closed by the DETACH.
   94568   */
   94569   db->autoCommit = 1;
   94570 
   94571   if( pDb ){
   94572     sqlite3BtreeClose(pDb->pBt);
   94573     pDb->pBt = 0;
   94574     pDb->pSchema = 0;
   94575   }
   94576 
   94577   sqlite3ResetInternalSchema(db, 0);
   94578 
   94579   return rc;
   94580 }
   94581 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
   94582 
   94583 /************** End of vacuum.c **********************************************/
   94584 /************** Begin file vtab.c ********************************************/
   94585 /*
   94586 ** 2006 June 10
   94587 **
   94588 ** The author disclaims copyright to this source code.  In place of
   94589 ** a legal notice, here is a blessing:
   94590 **
   94591 **    May you do good and not evil.
   94592 **    May you find forgiveness for yourself and forgive others.
   94593 **    May you share freely, never taking more than you give.
   94594 **
   94595 *************************************************************************
   94596 ** This file contains code used to help implement virtual tables.
   94597 */
   94598 #ifndef SQLITE_OMIT_VIRTUALTABLE
   94599 
   94600 /*
   94601 ** The actual function that does the work of creating a new module.
   94602 ** This function implements the sqlite3_create_module() and
   94603 ** sqlite3_create_module_v2() interfaces.
   94604 */
   94605 static int createModule(
   94606   sqlite3 *db,                    /* Database in which module is registered */
   94607   const char *zName,              /* Name assigned to this module */
   94608   const sqlite3_module *pModule,  /* The definition of the module */
   94609   void *pAux,                     /* Context pointer for xCreate/xConnect */
   94610   void (*xDestroy)(void *)        /* Module destructor function */
   94611 ){
   94612   int rc, nName;
   94613   Module *pMod;
   94614 
   94615   sqlite3_mutex_enter(db->mutex);
   94616   nName = sqlite3Strlen30(zName);
   94617   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
   94618   if( pMod ){
   94619     Module *pDel;
   94620     char *zCopy = (char *)(&pMod[1]);
   94621     memcpy(zCopy, zName, nName+1);
   94622     pMod->zName = zCopy;
   94623     pMod->pModule = pModule;
   94624     pMod->pAux = pAux;
   94625     pMod->xDestroy = xDestroy;
   94626     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
   94627     if( pDel && pDel->xDestroy ){
   94628       pDel->xDestroy(pDel->pAux);
   94629     }
   94630     sqlite3DbFree(db, pDel);
   94631     if( pDel==pMod ){
   94632       db->mallocFailed = 1;
   94633     }
   94634     sqlite3ResetInternalSchema(db, 0);
   94635   }else if( xDestroy ){
   94636     xDestroy(pAux);
   94637   }
   94638   rc = sqlite3ApiExit(db, SQLITE_OK);
   94639   sqlite3_mutex_leave(db->mutex);
   94640   return rc;
   94641 }
   94642 
   94643 
   94644 /*
   94645 ** External API function used to create a new virtual-table module.
   94646 */
   94647 SQLITE_API int sqlite3_create_module(
   94648   sqlite3 *db,                    /* Database in which module is registered */
   94649   const char *zName,              /* Name assigned to this module */
   94650   const sqlite3_module *pModule,  /* The definition of the module */
   94651   void *pAux                      /* Context pointer for xCreate/xConnect */
   94652 ){
   94653   return createModule(db, zName, pModule, pAux, 0);
   94654 }
   94655 
   94656 /*
   94657 ** External API function used to create a new virtual-table module.
   94658 */
   94659 SQLITE_API int sqlite3_create_module_v2(
   94660   sqlite3 *db,                    /* Database in which module is registered */
   94661   const char *zName,              /* Name assigned to this module */
   94662   const sqlite3_module *pModule,  /* The definition of the module */
   94663   void *pAux,                     /* Context pointer for xCreate/xConnect */
   94664   void (*xDestroy)(void *)        /* Module destructor function */
   94665 ){
   94666   return createModule(db, zName, pModule, pAux, xDestroy);
   94667 }
   94668 
   94669 /*
   94670 ** Lock the virtual table so that it cannot be disconnected.
   94671 ** Locks nest.  Every lock should have a corresponding unlock.
   94672 ** If an unlock is omitted, resources leaks will occur.
   94673 **
   94674 ** If a disconnect is attempted while a virtual table is locked,
   94675 ** the disconnect is deferred until all locks have been removed.
   94676 */
   94677 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
   94678   pVTab->nRef++;
   94679 }
   94680 
   94681 
   94682 /*
   94683 ** pTab is a pointer to a Table structure representing a virtual-table.
   94684 ** Return a pointer to the VTable object used by connection db to access
   94685 ** this virtual-table, if one has been created, or NULL otherwise.
   94686 */
   94687 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
   94688   VTable *pVtab;
   94689   assert( IsVirtual(pTab) );
   94690   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
   94691   return pVtab;
   94692 }
   94693 
   94694 /*
   94695 ** Decrement the ref-count on a virtual table object. When the ref-count
   94696 ** reaches zero, call the xDisconnect() method to delete the object.
   94697 */
   94698 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
   94699   sqlite3 *db = pVTab->db;
   94700 
   94701   assert( db );
   94702   assert( pVTab->nRef>0 );
   94703   assert( sqlite3SafetyCheckOk(db) );
   94704 
   94705   pVTab->nRef--;
   94706   if( pVTab->nRef==0 ){
   94707     sqlite3_vtab *p = pVTab->pVtab;
   94708     if( p ){
   94709       p->pModule->xDisconnect(p);
   94710     }
   94711     sqlite3DbFree(db, pVTab);
   94712   }
   94713 }
   94714 
   94715 /*
   94716 ** Table p is a virtual table. This function moves all elements in the
   94717 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
   94718 ** database connections to be disconnected at the next opportunity.
   94719 ** Except, if argument db is not NULL, then the entry associated with
   94720 ** connection db is left in the p->pVTable list.
   94721 */
   94722 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   94723   VTable *pRet = 0;
   94724   VTable *pVTable = p->pVTable;
   94725   p->pVTable = 0;
   94726 
   94727   /* Assert that the mutex (if any) associated with the BtShared database
   94728   ** that contains table p is held by the caller. See header comments
   94729   ** above function sqlite3VtabUnlockList() for an explanation of why
   94730   ** this makes it safe to access the sqlite3.pDisconnect list of any
   94731   ** database connection that may have an entry in the p->pVTable list.  */
   94732   assert( db==0 ||
   94733     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
   94734   );
   94735 
   94736   while( pVTable ){
   94737     sqlite3 *db2 = pVTable->db;
   94738     VTable *pNext = pVTable->pNext;
   94739     assert( db2 );
   94740     if( db2==db ){
   94741       pRet = pVTable;
   94742       p->pVTable = pRet;
   94743       pRet->pNext = 0;
   94744     }else{
   94745       pVTable->pNext = db2->pDisconnect;
   94746       db2->pDisconnect = pVTable;
   94747     }
   94748     pVTable = pNext;
   94749   }
   94750 
   94751   assert( !db || pRet );
   94752   return pRet;
   94753 }
   94754 
   94755 
   94756 /*
   94757 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
   94758 **
   94759 ** This function may only be called when the mutexes associated with all
   94760 ** shared b-tree databases opened using connection db are held by the
   94761 ** caller. This is done to protect the sqlite3.pDisconnect list. The
   94762 ** sqlite3.pDisconnect list is accessed only as follows:
   94763 **
   94764 **   1) By this function. In this case, all BtShared mutexes and the mutex
   94765 **      associated with the database handle itself must be held.
   94766 **
   94767 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
   94768 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
   94769 **      associated with the database the virtual table is stored in is held
   94770 **      or, if the virtual table is stored in a non-sharable database, then
   94771 **      the database handle mutex is held.
   94772 **
   94773 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
   94774 ** by multiple threads. It is thread-safe.
   94775 */
   94776 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   94777   VTable *p = db->pDisconnect;
   94778   db->pDisconnect = 0;
   94779 
   94780   assert( sqlite3BtreeHoldsAllMutexes(db) );
   94781   assert( sqlite3_mutex_held(db->mutex) );
   94782 
   94783   if( p ){
   94784     sqlite3ExpirePreparedStatements(db);
   94785     do {
   94786       VTable *pNext = p->pNext;
   94787       sqlite3VtabUnlock(p);
   94788       p = pNext;
   94789     }while( p );
   94790   }
   94791 }
   94792 
   94793 /*
   94794 ** Clear any and all virtual-table information from the Table record.
   94795 ** This routine is called, for example, just before deleting the Table
   94796 ** record.
   94797 **
   94798 ** Since it is a virtual-table, the Table structure contains a pointer
   94799 ** to the head of a linked list of VTable structures. Each VTable
   94800 ** structure is associated with a single sqlite3* user of the schema.
   94801 ** The reference count of the VTable structure associated with database
   94802 ** connection db is decremented immediately (which may lead to the
   94803 ** structure being xDisconnected and free). Any other VTable structures
   94804 ** in the list are moved to the sqlite3.pDisconnect list of the associated
   94805 ** database connection.
   94806 */
   94807 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
   94808   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
   94809   if( p->azModuleArg ){
   94810     int i;
   94811     for(i=0; i<p->nModuleArg; i++){
   94812       sqlite3DbFree(db, p->azModuleArg[i]);
   94813     }
   94814     sqlite3DbFree(db, p->azModuleArg);
   94815   }
   94816 }
   94817 
   94818 /*
   94819 ** Add a new module argument to pTable->azModuleArg[].
   94820 ** The string is not copied - the pointer is stored.  The
   94821 ** string will be freed automatically when the table is
   94822 ** deleted.
   94823 */
   94824 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
   94825   int i = pTable->nModuleArg++;
   94826   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
   94827   char **azModuleArg;
   94828   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
   94829   if( azModuleArg==0 ){
   94830     int j;
   94831     for(j=0; j<i; j++){
   94832       sqlite3DbFree(db, pTable->azModuleArg[j]);
   94833     }
   94834     sqlite3DbFree(db, zArg);
   94835     sqlite3DbFree(db, pTable->azModuleArg);
   94836     pTable->nModuleArg = 0;
   94837   }else{
   94838     azModuleArg[i] = zArg;
   94839     azModuleArg[i+1] = 0;
   94840   }
   94841   pTable->azModuleArg = azModuleArg;
   94842 }
   94843 
   94844 /*
   94845 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
   94846 ** statement.  The module name has been parsed, but the optional list
   94847 ** of parameters that follow the module name are still pending.
   94848 */
   94849 SQLITE_PRIVATE void sqlite3VtabBeginParse(
   94850   Parse *pParse,        /* Parsing context */
   94851   Token *pName1,        /* Name of new table, or database name */
   94852   Token *pName2,        /* Name of new table or NULL */
   94853   Token *pModuleName    /* Name of the module for the virtual table */
   94854 ){
   94855   int iDb;              /* The database the table is being created in */
   94856   Table *pTable;        /* The new virtual table */
   94857   sqlite3 *db;          /* Database connection */
   94858 
   94859   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
   94860   pTable = pParse->pNewTable;
   94861   if( pTable==0 ) return;
   94862   assert( 0==pTable->pIndex );
   94863 
   94864   db = pParse->db;
   94865   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
   94866   assert( iDb>=0 );
   94867 
   94868   pTable->tabFlags |= TF_Virtual;
   94869   pTable->nModuleArg = 0;
   94870   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
   94871   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
   94872   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
   94873   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
   94874 
   94875 #ifndef SQLITE_OMIT_AUTHORIZATION
   94876   /* Creating a virtual table invokes the authorization callback twice.
   94877   ** The first invocation, to obtain permission to INSERT a row into the
   94878   ** sqlite_master table, has already been made by sqlite3StartTable().
   94879   ** The second call, to obtain permission to create the table, is made now.
   94880   */
   94881   if( pTable->azModuleArg ){
   94882     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
   94883             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
   94884   }
   94885 #endif
   94886 }
   94887 
   94888 /*
   94889 ** This routine takes the module argument that has been accumulating
   94890 ** in pParse->zArg[] and appends it to the list of arguments on the
   94891 ** virtual table currently under construction in pParse->pTable.
   94892 */
   94893 static void addArgumentToVtab(Parse *pParse){
   94894   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
   94895     const char *z = (const char*)pParse->sArg.z;
   94896     int n = pParse->sArg.n;
   94897     sqlite3 *db = pParse->db;
   94898     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
   94899   }
   94900 }
   94901 
   94902 /*
   94903 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
   94904 ** has been completely parsed.
   94905 */
   94906 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   94907   Table *pTab = pParse->pNewTable;  /* The table being constructed */
   94908   sqlite3 *db = pParse->db;         /* The database connection */
   94909 
   94910   if( pTab==0 ) return;
   94911   addArgumentToVtab(pParse);
   94912   pParse->sArg.z = 0;
   94913   if( pTab->nModuleArg<1 ) return;
   94914 
   94915   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   94916   ** first time (in other words if the virtual table is actually being
   94917   ** created now instead of just being read out of sqlite_master) then
   94918   ** do additional initialization work and store the statement text
   94919   ** in the sqlite_master table.
   94920   */
   94921   if( !db->init.busy ){
   94922     char *zStmt;
   94923     char *zWhere;
   94924     int iDb;
   94925     Vdbe *v;
   94926 
   94927     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
   94928     if( pEnd ){
   94929       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
   94930     }
   94931     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
   94932 
   94933     /* A slot for the record has already been allocated in the
   94934     ** SQLITE_MASTER table.  We just need to update that slot with all
   94935     ** the information we've collected.
   94936     **
   94937     ** The VM register number pParse->regRowid holds the rowid of an
   94938     ** entry in the sqlite_master table tht was created for this vtab
   94939     ** by sqlite3StartTable().
   94940     */
   94941     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   94942     sqlite3NestedParse(pParse,
   94943       "UPDATE %Q.%s "
   94944          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
   94945        "WHERE rowid=#%d",
   94946       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
   94947       pTab->zName,
   94948       pTab->zName,
   94949       zStmt,
   94950       pParse->regRowid
   94951     );
   94952     sqlite3DbFree(db, zStmt);
   94953     v = sqlite3GetVdbe(pParse);
   94954     sqlite3ChangeCookie(pParse, iDb);
   94955 
   94956     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
   94957     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
   94958     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
   94959     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
   94960                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
   94961   }
   94962 
   94963   /* If we are rereading the sqlite_master table create the in-memory
   94964   ** record of the table. The xConnect() method is not called until
   94965   ** the first time the virtual table is used in an SQL statement. This
   94966   ** allows a schema that contains virtual tables to be loaded before
   94967   ** the required virtual table implementations are registered.  */
   94968   else {
   94969     Table *pOld;
   94970     Schema *pSchema = pTab->pSchema;
   94971     const char *zName = pTab->zName;
   94972     int nName = sqlite3Strlen30(zName);
   94973     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
   94974     if( pOld ){
   94975       db->mallocFailed = 1;
   94976       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   94977       return;
   94978     }
   94979     pParse->pNewTable = 0;
   94980   }
   94981 }
   94982 
   94983 /*
   94984 ** The parser calls this routine when it sees the first token
   94985 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
   94986 */
   94987 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
   94988   addArgumentToVtab(pParse);
   94989   pParse->sArg.z = 0;
   94990   pParse->sArg.n = 0;
   94991 }
   94992 
   94993 /*
   94994 ** The parser calls this routine for each token after the first token
   94995 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
   94996 */
   94997 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
   94998   Token *pArg = &pParse->sArg;
   94999   if( pArg->z==0 ){
   95000     pArg->z = p->z;
   95001     pArg->n = p->n;
   95002   }else{
   95003     assert(pArg->z < p->z);
   95004     pArg->n = (int)(&p->z[p->n] - pArg->z);
   95005   }
   95006 }
   95007 
   95008 /*
   95009 ** Invoke a virtual table constructor (either xCreate or xConnect). The
   95010 ** pointer to the function to invoke is passed as the fourth parameter
   95011 ** to this procedure.
   95012 */
   95013 static int vtabCallConstructor(
   95014   sqlite3 *db,
   95015   Table *pTab,
   95016   Module *pMod,
   95017   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
   95018   char **pzErr
   95019 ){
   95020   VTable *pVTable;
   95021   int rc;
   95022   const char *const*azArg = (const char *const*)pTab->azModuleArg;
   95023   int nArg = pTab->nModuleArg;
   95024   char *zErr = 0;
   95025   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
   95026 
   95027   if( !zModuleName ){
   95028     return SQLITE_NOMEM;
   95029   }
   95030 
   95031   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
   95032   if( !pVTable ){
   95033     sqlite3DbFree(db, zModuleName);
   95034     return SQLITE_NOMEM;
   95035   }
   95036   pVTable->db = db;
   95037   pVTable->pMod = pMod;
   95038 
   95039   assert( !db->pVTab );
   95040   assert( xConstruct );
   95041   db->pVTab = pTab;
   95042 
   95043   /* Invoke the virtual table constructor */
   95044   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   95045   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
   95046 
   95047   if( SQLITE_OK!=rc ){
   95048     if( zErr==0 ){
   95049       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   95050     }else {
   95051       *pzErr = sqlite3MPrintf(db, "%s", zErr);
   95052       sqlite3_free(zErr);
   95053     }
   95054     sqlite3DbFree(db, pVTable);
   95055   }else if( ALWAYS(pVTable->pVtab) ){
   95056     /* Justification of ALWAYS():  A correct vtab constructor must allocate
   95057     ** the sqlite3_vtab object if successful.  */
   95058     pVTable->pVtab->pModule = pMod->pModule;
   95059     pVTable->nRef = 1;
   95060     if( db->pVTab ){
   95061       const char *zFormat = "vtable constructor did not declare schema: %s";
   95062       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
   95063       sqlite3VtabUnlock(pVTable);
   95064       rc = SQLITE_ERROR;
   95065     }else{
   95066       int iCol;
   95067       /* If everything went according to plan, link the new VTable structure
   95068       ** into the linked list headed by pTab->pVTable. Then loop through the
   95069       ** columns of the table to see if any of them contain the token "hidden".
   95070       ** If so, set the Column.isHidden flag and remove the token from
   95071       ** the type string.  */
   95072       pVTable->pNext = pTab->pVTable;
   95073       pTab->pVTable = pVTable;
   95074 
   95075       for(iCol=0; iCol<pTab->nCol; iCol++){
   95076         char *zType = pTab->aCol[iCol].zType;
   95077         int nType;
   95078         int i = 0;
   95079         if( !zType ) continue;
   95080         nType = sqlite3Strlen30(zType);
   95081         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
   95082           for(i=0; i<nType; i++){
   95083             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
   95084              && (zType[i+7]=='\0' || zType[i+7]==' ')
   95085             ){
   95086               i++;
   95087               break;
   95088             }
   95089           }
   95090         }
   95091         if( i<nType ){
   95092           int j;
   95093           int nDel = 6 + (zType[i+6] ? 1 : 0);
   95094           for(j=i; (j+nDel)<=nType; j++){
   95095             zType[j] = zType[j+nDel];
   95096           }
   95097           if( zType[i]=='\0' && i>0 ){
   95098             assert(zType[i-1]==' ');
   95099             zType[i-1] = '\0';
   95100           }
   95101           pTab->aCol[iCol].isHidden = 1;
   95102         }
   95103       }
   95104     }
   95105   }
   95106 
   95107   sqlite3DbFree(db, zModuleName);
   95108   db->pVTab = 0;
   95109   return rc;
   95110 }
   95111 
   95112 /*
   95113 ** This function is invoked by the parser to call the xConnect() method
   95114 ** of the virtual table pTab. If an error occurs, an error code is returned
   95115 ** and an error left in pParse.
   95116 **
   95117 ** This call is a no-op if table pTab is not a virtual table.
   95118 */
   95119 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
   95120   sqlite3 *db = pParse->db;
   95121   const char *zMod;
   95122   Module *pMod;
   95123   int rc;
   95124 
   95125   assert( pTab );
   95126   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
   95127     return SQLITE_OK;
   95128   }
   95129 
   95130   /* Locate the required virtual table module */
   95131   zMod = pTab->azModuleArg[0];
   95132   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   95133 
   95134   if( !pMod ){
   95135     const char *zModule = pTab->azModuleArg[0];
   95136     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
   95137     rc = SQLITE_ERROR;
   95138   }else{
   95139     char *zErr = 0;
   95140     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
   95141     if( rc!=SQLITE_OK ){
   95142       sqlite3ErrorMsg(pParse, "%s", zErr);
   95143     }
   95144     sqlite3DbFree(db, zErr);
   95145   }
   95146 
   95147   return rc;
   95148 }
   95149 
   95150 /*
   95151 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
   95152 */
   95153 static int addToVTrans(sqlite3 *db, VTable *pVTab){
   95154   const int ARRAY_INCR = 5;
   95155 
   95156   /* Grow the sqlite3.aVTrans array if required */
   95157   if( (db->nVTrans%ARRAY_INCR)==0 ){
   95158     VTable **aVTrans;
   95159     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
   95160     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
   95161     if( !aVTrans ){
   95162       return SQLITE_NOMEM;
   95163     }
   95164     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
   95165     db->aVTrans = aVTrans;
   95166   }
   95167 
   95168   /* Add pVtab to the end of sqlite3.aVTrans */
   95169   db->aVTrans[db->nVTrans++] = pVTab;
   95170   sqlite3VtabLock(pVTab);
   95171   return SQLITE_OK;
   95172 }
   95173 
   95174 /*
   95175 ** This function is invoked by the vdbe to call the xCreate method
   95176 ** of the virtual table named zTab in database iDb.
   95177 **
   95178 ** If an error occurs, *pzErr is set to point an an English language
   95179 ** description of the error and an SQLITE_XXX error code is returned.
   95180 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
   95181 */
   95182 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
   95183   int rc = SQLITE_OK;
   95184   Table *pTab;
   95185   Module *pMod;
   95186   const char *zMod;
   95187 
   95188   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   95189   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
   95190 
   95191   /* Locate the required virtual table module */
   95192   zMod = pTab->azModuleArg[0];
   95193   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
   95194 
   95195   /* If the module has been registered and includes a Create method,
   95196   ** invoke it now. If the module has not been registered, return an
   95197   ** error. Otherwise, do nothing.
   95198   */
   95199   if( !pMod ){
   95200     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
   95201     rc = SQLITE_ERROR;
   95202   }else{
   95203     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
   95204   }
   95205 
   95206   /* Justification of ALWAYS():  The xConstructor method is required to
   95207   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
   95208   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
   95209       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
   95210   }
   95211 
   95212   return rc;
   95213 }
   95214 
   95215 /*
   95216 ** This function is used to set the schema of a virtual table.  It is only
   95217 ** valid to call this function from within the xCreate() or xConnect() of a
   95218 ** virtual table module.
   95219 */
   95220 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   95221   Parse *pParse;
   95222 
   95223   int rc = SQLITE_OK;
   95224   Table *pTab;
   95225   char *zErr = 0;
   95226 
   95227   sqlite3_mutex_enter(db->mutex);
   95228   pTab = db->pVTab;
   95229   if( !pTab ){
   95230     sqlite3Error(db, SQLITE_MISUSE, 0);
   95231     sqlite3_mutex_leave(db->mutex);
   95232     return SQLITE_MISUSE_BKPT;
   95233   }
   95234   assert( (pTab->tabFlags & TF_Virtual)!=0 );
   95235 
   95236   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
   95237   if( pParse==0 ){
   95238     rc = SQLITE_NOMEM;
   95239   }else{
   95240     pParse->declareVtab = 1;
   95241     pParse->db = db;
   95242     pParse->nQueryLoop = 1;
   95243 
   95244     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
   95245      && pParse->pNewTable
   95246      && !db->mallocFailed
   95247      && !pParse->pNewTable->pSelect
   95248      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
   95249     ){
   95250       if( !pTab->aCol ){
   95251         pTab->aCol = pParse->pNewTable->aCol;
   95252         pTab->nCol = pParse->pNewTable->nCol;
   95253         pParse->pNewTable->nCol = 0;
   95254         pParse->pNewTable->aCol = 0;
   95255       }
   95256       db->pVTab = 0;
   95257     }else{
   95258       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
   95259       sqlite3DbFree(db, zErr);
   95260       rc = SQLITE_ERROR;
   95261     }
   95262     pParse->declareVtab = 0;
   95263 
   95264     if( pParse->pVdbe ){
   95265       sqlite3VdbeFinalize(pParse->pVdbe);
   95266     }
   95267     sqlite3DeleteTable(db, pParse->pNewTable);
   95268     sqlite3StackFree(db, pParse);
   95269   }
   95270 
   95271   assert( (rc&0xff)==rc );
   95272   rc = sqlite3ApiExit(db, rc);
   95273   sqlite3_mutex_leave(db->mutex);
   95274   return rc;
   95275 }
   95276 
   95277 /*
   95278 ** This function is invoked by the vdbe to call the xDestroy method
   95279 ** of the virtual table named zTab in database iDb. This occurs
   95280 ** when a DROP TABLE is mentioned.
   95281 **
   95282 ** This call is a no-op if zTab is not a virtual table.
   95283 */
   95284 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
   95285   int rc = SQLITE_OK;
   95286   Table *pTab;
   95287 
   95288   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
   95289   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
   95290     VTable *p = vtabDisconnectAll(db, pTab);
   95291 
   95292     assert( rc==SQLITE_OK );
   95293     rc = p->pMod->pModule->xDestroy(p->pVtab);
   95294 
   95295     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
   95296     if( rc==SQLITE_OK ){
   95297       assert( pTab->pVTable==p && p->pNext==0 );
   95298       p->pVtab = 0;
   95299       pTab->pVTable = 0;
   95300       sqlite3VtabUnlock(p);
   95301     }
   95302   }
   95303 
   95304   return rc;
   95305 }
   95306 
   95307 /*
   95308 ** This function invokes either the xRollback or xCommit method
   95309 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
   95310 ** called is identified by the second argument, "offset", which is
   95311 ** the offset of the method to call in the sqlite3_module structure.
   95312 **
   95313 ** The array is cleared after invoking the callbacks.
   95314 */
   95315 static void callFinaliser(sqlite3 *db, int offset){
   95316   int i;
   95317   if( db->aVTrans ){
   95318     for(i=0; i<db->nVTrans; i++){
   95319       VTable *pVTab = db->aVTrans[i];
   95320       sqlite3_vtab *p = pVTab->pVtab;
   95321       if( p ){
   95322         int (*x)(sqlite3_vtab *);
   95323         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
   95324         if( x ) x(p);
   95325       }
   95326       sqlite3VtabUnlock(pVTab);
   95327     }
   95328     sqlite3DbFree(db, db->aVTrans);
   95329     db->nVTrans = 0;
   95330     db->aVTrans = 0;
   95331   }
   95332 }
   95333 
   95334 /*
   95335 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
   95336 ** array. Return the error code for the first error that occurs, or
   95337 ** SQLITE_OK if all xSync operations are successful.
   95338 **
   95339 ** Set *pzErrmsg to point to a buffer that should be released using
   95340 ** sqlite3DbFree() containing an error message, if one is available.
   95341 */
   95342 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
   95343   int i;
   95344   int rc = SQLITE_OK;
   95345   VTable **aVTrans = db->aVTrans;
   95346 
   95347   db->aVTrans = 0;
   95348   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
   95349     int (*x)(sqlite3_vtab *);
   95350     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
   95351     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
   95352       rc = x(pVtab);
   95353       sqlite3DbFree(db, *pzErrmsg);
   95354       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
   95355       sqlite3_free(pVtab->zErrMsg);
   95356     }
   95357   }
   95358   db->aVTrans = aVTrans;
   95359   return rc;
   95360 }
   95361 
   95362 /*
   95363 ** Invoke the xRollback method of all virtual tables in the
   95364 ** sqlite3.aVTrans array. Then clear the array itself.
   95365 */
   95366 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
   95367   callFinaliser(db, offsetof(sqlite3_module,xRollback));
   95368   return SQLITE_OK;
   95369 }
   95370 
   95371 /*
   95372 ** Invoke the xCommit method of all virtual tables in the
   95373 ** sqlite3.aVTrans array. Then clear the array itself.
   95374 */
   95375 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
   95376   callFinaliser(db, offsetof(sqlite3_module,xCommit));
   95377   return SQLITE_OK;
   95378 }
   95379 
   95380 /*
   95381 ** If the virtual table pVtab supports the transaction interface
   95382 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
   95383 ** not currently open, invoke the xBegin method now.
   95384 **
   95385 ** If the xBegin call is successful, place the sqlite3_vtab pointer
   95386 ** in the sqlite3.aVTrans array.
   95387 */
   95388 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   95389   int rc = SQLITE_OK;
   95390   const sqlite3_module *pModule;
   95391 
   95392   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   95393   ** than zero, then this function is being called from within a
   95394   ** virtual module xSync() callback. It is illegal to write to
   95395   ** virtual module tables in this case, so return SQLITE_LOCKED.
   95396   */
   95397   if( sqlite3VtabInSync(db) ){
   95398     return SQLITE_LOCKED;
   95399   }
   95400   if( !pVTab ){
   95401     return SQLITE_OK;
   95402   }
   95403   pModule = pVTab->pVtab->pModule;
   95404 
   95405   if( pModule->xBegin ){
   95406     int i;
   95407 
   95408 
   95409     /* If pVtab is already in the aVTrans array, return early */
   95410     for(i=0; i<db->nVTrans; i++){
   95411       if( db->aVTrans[i]==pVTab ){
   95412         return SQLITE_OK;
   95413       }
   95414     }
   95415 
   95416     /* Invoke the xBegin method */
   95417     rc = pModule->xBegin(pVTab->pVtab);
   95418     if( rc==SQLITE_OK ){
   95419       rc = addToVTrans(db, pVTab);
   95420     }
   95421   }
   95422   return rc;
   95423 }
   95424 
   95425 /*
   95426 ** The first parameter (pDef) is a function implementation.  The
   95427 ** second parameter (pExpr) is the first argument to this function.
   95428 ** If pExpr is a column in a virtual table, then let the virtual
   95429 ** table implementation have an opportunity to overload the function.
   95430 **
   95431 ** This routine is used to allow virtual table implementations to
   95432 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
   95433 **
   95434 ** Return either the pDef argument (indicating no change) or a
   95435 ** new FuncDef structure that is marked as ephemeral using the
   95436 ** SQLITE_FUNC_EPHEM flag.
   95437 */
   95438 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   95439   sqlite3 *db,    /* Database connection for reporting malloc problems */
   95440   FuncDef *pDef,  /* Function to possibly overload */
   95441   int nArg,       /* Number of arguments to the function */
   95442   Expr *pExpr     /* First argument to the function */
   95443 ){
   95444   Table *pTab;
   95445   sqlite3_vtab *pVtab;
   95446   sqlite3_module *pMod;
   95447   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
   95448   void *pArg = 0;
   95449   FuncDef *pNew;
   95450   int rc = 0;
   95451   char *zLowerName;
   95452   unsigned char *z;
   95453 
   95454 
   95455   /* Check to see the left operand is a column in a virtual table */
   95456   if( NEVER(pExpr==0) ) return pDef;
   95457   if( pExpr->op!=TK_COLUMN ) return pDef;
   95458   pTab = pExpr->pTab;
   95459   if( NEVER(pTab==0) ) return pDef;
   95460   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
   95461   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
   95462   assert( pVtab!=0 );
   95463   assert( pVtab->pModule!=0 );
   95464   pMod = (sqlite3_module *)pVtab->pModule;
   95465   if( pMod->xFindFunction==0 ) return pDef;
   95466 
   95467   /* Call the xFindFunction method on the virtual table implementation
   95468   ** to see if the implementation wants to overload this function
   95469   */
   95470   zLowerName = sqlite3DbStrDup(db, pDef->zName);
   95471   if( zLowerName ){
   95472     for(z=(unsigned char*)zLowerName; *z; z++){
   95473       *z = sqlite3UpperToLower[*z];
   95474     }
   95475     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
   95476     sqlite3DbFree(db, zLowerName);
   95477   }
   95478   if( rc==0 ){
   95479     return pDef;
   95480   }
   95481 
   95482   /* Create a new ephemeral function definition for the overloaded
   95483   ** function */
   95484   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
   95485                              + sqlite3Strlen30(pDef->zName) + 1);
   95486   if( pNew==0 ){
   95487     return pDef;
   95488   }
   95489   *pNew = *pDef;
   95490   pNew->zName = (char *)&pNew[1];
   95491   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
   95492   pNew->xFunc = xFunc;
   95493   pNew->pUserData = pArg;
   95494   pNew->flags |= SQLITE_FUNC_EPHEM;
   95495   return pNew;
   95496 }
   95497 
   95498 /*
   95499 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
   95500 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
   95501 ** array if it is missing.  If pTab is already in the array, this routine
   95502 ** is a no-op.
   95503 */
   95504 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
   95505   Parse *pToplevel = sqlite3ParseToplevel(pParse);
   95506   int i, n;
   95507   Table **apVtabLock;
   95508 
   95509   assert( IsVirtual(pTab) );
   95510   for(i=0; i<pToplevel->nVtabLock; i++){
   95511     if( pTab==pToplevel->apVtabLock[i] ) return;
   95512   }
   95513   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
   95514   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
   95515   if( apVtabLock ){
   95516     pToplevel->apVtabLock = apVtabLock;
   95517     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
   95518   }else{
   95519     pToplevel->db->mallocFailed = 1;
   95520   }
   95521 }
   95522 
   95523 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   95524 
   95525 /************** End of vtab.c ************************************************/
   95526 /************** Begin file where.c *******************************************/
   95527 /*
   95528 ** 2001 September 15
   95529 **
   95530 ** The author disclaims copyright to this source code.  In place of
   95531 ** a legal notice, here is a blessing:
   95532 **
   95533 **    May you do good and not evil.
   95534 **    May you find forgiveness for yourself and forgive others.
   95535 **    May you share freely, never taking more than you give.
   95536 **
   95537 *************************************************************************
   95538 ** This module contains C code that generates VDBE code used to process
   95539 ** the WHERE clause of SQL statements.  This module is responsible for
   95540 ** generating the code that loops through a table looking for applicable
   95541 ** rows.  Indices are selected and used to speed the search when doing
   95542 ** so is applicable.  Because this module is responsible for selecting
   95543 ** indices, you might also think of this module as the "query optimizer".
   95544 */
   95545 
   95546 /*
   95547 ** Trace output macros
   95548 */
   95549 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
   95550 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
   95551 #endif
   95552 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
   95553 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
   95554 #else
   95555 # define WHERETRACE(X)
   95556 #endif
   95557 
   95558 /* Forward reference
   95559 */
   95560 typedef struct WhereClause WhereClause;
   95561 typedef struct WhereMaskSet WhereMaskSet;
   95562 typedef struct WhereOrInfo WhereOrInfo;
   95563 typedef struct WhereAndInfo WhereAndInfo;
   95564 typedef struct WhereCost WhereCost;
   95565 
   95566 /*
   95567 ** The query generator uses an array of instances of this structure to
   95568 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
   95569 ** clause subexpression is separated from the others by AND operators,
   95570 ** usually, or sometimes subexpressions separated by OR.
   95571 **
   95572 ** All WhereTerms are collected into a single WhereClause structure.
   95573 ** The following identity holds:
   95574 **
   95575 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
   95576 **
   95577 ** When a term is of the form:
   95578 **
   95579 **              X <op> <expr>
   95580 **
   95581 ** where X is a column name and <op> is one of certain operators,
   95582 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
   95583 ** cursor number and column number for X.  WhereTerm.eOperator records
   95584 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
   95585 ** use of a bitmask encoding for the operator allows us to search
   95586 ** quickly for terms that match any of several different operators.
   95587 **
   95588 ** A WhereTerm might also be two or more subterms connected by OR:
   95589 **
   95590 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   95591 **
   95592 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
   95593 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   95594 ** is collected about the
   95595 **
   95596 ** If a term in the WHERE clause does not match either of the two previous
   95597 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   95598 ** to the original subexpression content and wtFlags is set up appropriately
   95599 ** but no other fields in the WhereTerm object are meaningful.
   95600 **
   95601 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
   95602 ** but they do so indirectly.  A single WhereMaskSet structure translates
   95603 ** cursor number into bits and the translated bit is stored in the prereq
   95604 ** fields.  The translation is used in order to maximize the number of
   95605 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
   95606 ** spread out over the non-negative integers.  For example, the cursor
   95607 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
   95608 ** translates these sparse cursor numbers into consecutive integers
   95609 ** beginning with 0 in order to make the best possible use of the available
   95610 ** bits in the Bitmask.  So, in the example above, the cursor numbers
   95611 ** would be mapped into integers 0 through 7.
   95612 **
   95613 ** The number of terms in a join is limited by the number of bits
   95614 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
   95615 ** is only able to process joins with 64 or fewer tables.
   95616 */
   95617 typedef struct WhereTerm WhereTerm;
   95618 struct WhereTerm {
   95619   Expr *pExpr;            /* Pointer to the subexpression that is this term */
   95620   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   95621   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
   95622   union {
   95623     int leftColumn;         /* Column number of X in "X <op> <expr>" */
   95624     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
   95625     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
   95626   } u;
   95627   u16 eOperator;          /* A WO_xx value describing <op> */
   95628   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
   95629   u8 nChild;              /* Number of children that must disable us */
   95630   WhereClause *pWC;       /* The clause this term is part of */
   95631   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
   95632   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
   95633 };
   95634 
   95635 /*
   95636 ** Allowed values of WhereTerm.wtFlags
   95637 */
   95638 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
   95639 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
   95640 #define TERM_CODED      0x04   /* This term is already coded */
   95641 #define TERM_COPIED     0x08   /* Has a child */
   95642 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
   95643 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
   95644 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
   95645 
   95646 /*
   95647 ** An instance of the following structure holds all information about a
   95648 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
   95649 */
   95650 struct WhereClause {
   95651   Parse *pParse;           /* The parser context */
   95652   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
   95653   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
   95654   u8 op;                   /* Split operator.  TK_AND or TK_OR */
   95655   int nTerm;               /* Number of terms */
   95656   int nSlot;               /* Number of entries in a[] */
   95657   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
   95658 #if defined(SQLITE_SMALL_STACK)
   95659   WhereTerm aStatic[1];    /* Initial static space for a[] */
   95660 #else
   95661   WhereTerm aStatic[8];    /* Initial static space for a[] */
   95662 #endif
   95663 };
   95664 
   95665 /*
   95666 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
   95667 ** a dynamically allocated instance of the following structure.
   95668 */
   95669 struct WhereOrInfo {
   95670   WhereClause wc;          /* Decomposition into subterms */
   95671   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
   95672 };
   95673 
   95674 /*
   95675 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
   95676 ** a dynamically allocated instance of the following structure.
   95677 */
   95678 struct WhereAndInfo {
   95679   WhereClause wc;          /* The subexpression broken out */
   95680 };
   95681 
   95682 /*
   95683 ** An instance of the following structure keeps track of a mapping
   95684 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
   95685 **
   95686 ** The VDBE cursor numbers are small integers contained in
   95687 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
   95688 ** clause, the cursor numbers might not begin with 0 and they might
   95689 ** contain gaps in the numbering sequence.  But we want to make maximum
   95690 ** use of the bits in our bitmasks.  This structure provides a mapping
   95691 ** from the sparse cursor numbers into consecutive integers beginning
   95692 ** with 0.
   95693 **
   95694 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
   95695 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
   95696 **
   95697 ** For example, if the WHERE clause expression used these VDBE
   95698 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
   95699 ** would map those cursor numbers into bits 0 through 5.
   95700 **
   95701 ** Note that the mapping is not necessarily ordered.  In the example
   95702 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
   95703 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
   95704 ** does not really matter.  What is important is that sparse cursor
   95705 ** numbers all get mapped into bit numbers that begin with 0 and contain
   95706 ** no gaps.
   95707 */
   95708 struct WhereMaskSet {
   95709   int n;                        /* Number of assigned cursor values */
   95710   int ix[BMS];                  /* Cursor assigned to each bit */
   95711 };
   95712 
   95713 /*
   95714 ** A WhereCost object records a lookup strategy and the estimated
   95715 ** cost of pursuing that strategy.
   95716 */
   95717 struct WhereCost {
   95718   WherePlan plan;    /* The lookup strategy */
   95719   double rCost;      /* Overall cost of pursuing this search strategy */
   95720   Bitmask used;      /* Bitmask of cursors used by this plan */
   95721 };
   95722 
   95723 /*
   95724 ** Bitmasks for the operators that indices are able to exploit.  An
   95725 ** OR-ed combination of these values can be used when searching for
   95726 ** terms in the where clause.
   95727 */
   95728 #define WO_IN     0x001
   95729 #define WO_EQ     0x002
   95730 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
   95731 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
   95732 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
   95733 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
   95734 #define WO_MATCH  0x040
   95735 #define WO_ISNULL 0x080
   95736 #define WO_OR     0x100       /* Two or more OR-connected terms */
   95737 #define WO_AND    0x200       /* Two or more AND-connected terms */
   95738 
   95739 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
   95740 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
   95741 
   95742 /*
   95743 ** Value for wsFlags returned by bestIndex() and stored in
   95744 ** WhereLevel.wsFlags.  These flags determine which search
   95745 ** strategies are appropriate.
   95746 **
   95747 ** The least significant 12 bits is reserved as a mask for WO_ values above.
   95748 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
   95749 ** But if the table is the right table of a left join, WhereLevel.wsFlags
   95750 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
   95751 ** the "op" parameter to findTerm when we are resolving equality constraints.
   95752 ** ISNULL constraints will then not be used on the right table of a left
   95753 ** join.  Tickets #2177 and #2189.
   95754 */
   95755 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
   95756 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
   95757 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
   95758 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
   95759 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
   95760 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
   95761 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
   95762 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
   95763 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
   95764 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
   95765 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
   95766 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
   95767 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
   95768 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
   95769 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
   95770 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
   95771 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
   95772 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
   95773 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
   95774 
   95775 /*
   95776 ** Initialize a preallocated WhereClause structure.
   95777 */
   95778 static void whereClauseInit(
   95779   WhereClause *pWC,        /* The WhereClause to be initialized */
   95780   Parse *pParse,           /* The parsing context */
   95781   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
   95782 ){
   95783   pWC->pParse = pParse;
   95784   pWC->pMaskSet = pMaskSet;
   95785   pWC->nTerm = 0;
   95786   pWC->nSlot = ArraySize(pWC->aStatic);
   95787   pWC->a = pWC->aStatic;
   95788   pWC->vmask = 0;
   95789 }
   95790 
   95791 /* Forward reference */
   95792 static void whereClauseClear(WhereClause*);
   95793 
   95794 /*
   95795 ** Deallocate all memory associated with a WhereOrInfo object.
   95796 */
   95797 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
   95798   whereClauseClear(&p->wc);
   95799   sqlite3DbFree(db, p);
   95800 }
   95801 
   95802 /*
   95803 ** Deallocate all memory associated with a WhereAndInfo object.
   95804 */
   95805 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
   95806   whereClauseClear(&p->wc);
   95807   sqlite3DbFree(db, p);
   95808 }
   95809 
   95810 /*
   95811 ** Deallocate a WhereClause structure.  The WhereClause structure
   95812 ** itself is not freed.  This routine is the inverse of whereClauseInit().
   95813 */
   95814 static void whereClauseClear(WhereClause *pWC){
   95815   int i;
   95816   WhereTerm *a;
   95817   sqlite3 *db = pWC->pParse->db;
   95818   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
   95819     if( a->wtFlags & TERM_DYNAMIC ){
   95820       sqlite3ExprDelete(db, a->pExpr);
   95821     }
   95822     if( a->wtFlags & TERM_ORINFO ){
   95823       whereOrInfoDelete(db, a->u.pOrInfo);
   95824     }else if( a->wtFlags & TERM_ANDINFO ){
   95825       whereAndInfoDelete(db, a->u.pAndInfo);
   95826     }
   95827   }
   95828   if( pWC->a!=pWC->aStatic ){
   95829     sqlite3DbFree(db, pWC->a);
   95830   }
   95831 }
   95832 
   95833 /*
   95834 ** Add a single new WhereTerm entry to the WhereClause object pWC.
   95835 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
   95836 ** The index in pWC->a[] of the new WhereTerm is returned on success.
   95837 ** 0 is returned if the new WhereTerm could not be added due to a memory
   95838 ** allocation error.  The memory allocation failure will be recorded in
   95839 ** the db->mallocFailed flag so that higher-level functions can detect it.
   95840 **
   95841 ** This routine will increase the size of the pWC->a[] array as necessary.
   95842 **
   95843 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
   95844 ** for freeing the expression p is assumed by the WhereClause object pWC.
   95845 ** This is true even if this routine fails to allocate a new WhereTerm.
   95846 **
   95847 ** WARNING:  This routine might reallocate the space used to store
   95848 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   95849 ** calling this routine.  Such pointers may be reinitialized by referencing
   95850 ** the pWC->a[] array.
   95851 */
   95852 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   95853   WhereTerm *pTerm;
   95854   int idx;
   95855   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
   95856   if( pWC->nTerm>=pWC->nSlot ){
   95857     WhereTerm *pOld = pWC->a;
   95858     sqlite3 *db = pWC->pParse->db;
   95859     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   95860     if( pWC->a==0 ){
   95861       if( wtFlags & TERM_DYNAMIC ){
   95862         sqlite3ExprDelete(db, p);
   95863       }
   95864       pWC->a = pOld;
   95865       return 0;
   95866     }
   95867     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
   95868     if( pOld!=pWC->aStatic ){
   95869       sqlite3DbFree(db, pOld);
   95870     }
   95871     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
   95872   }
   95873   pTerm = &pWC->a[idx = pWC->nTerm++];
   95874   pTerm->pExpr = p;
   95875   pTerm->wtFlags = wtFlags;
   95876   pTerm->pWC = pWC;
   95877   pTerm->iParent = -1;
   95878   return idx;
   95879 }
   95880 
   95881 /*
   95882 ** This routine identifies subexpressions in the WHERE clause where
   95883 ** each subexpression is separated by the AND operator or some other
   95884 ** operator specified in the op parameter.  The WhereClause structure
   95885 ** is filled with pointers to subexpressions.  For example:
   95886 **
   95887 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
   95888 **           \________/     \_______________/     \________________/
   95889 **            slot[0]            slot[1]               slot[2]
   95890 **
   95891 ** The original WHERE clause in pExpr is unaltered.  All this routine
   95892 ** does is make slot[] entries point to substructure within pExpr.
   95893 **
   95894 ** In the previous sentence and in the diagram, "slot[]" refers to
   95895 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
   95896 ** all terms of the WHERE clause.
   95897 */
   95898 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
   95899   pWC->op = (u8)op;
   95900   if( pExpr==0 ) return;
   95901   if( pExpr->op!=op ){
   95902     whereClauseInsert(pWC, pExpr, 0);
   95903   }else{
   95904     whereSplit(pWC, pExpr->pLeft, op);
   95905     whereSplit(pWC, pExpr->pRight, op);
   95906   }
   95907 }
   95908 
   95909 /*
   95910 ** Initialize an expression mask set (a WhereMaskSet object)
   95911 */
   95912 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
   95913 
   95914 /*
   95915 ** Return the bitmask for the given cursor number.  Return 0 if
   95916 ** iCursor is not in the set.
   95917 */
   95918 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
   95919   int i;
   95920   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
   95921   for(i=0; i<pMaskSet->n; i++){
   95922     if( pMaskSet->ix[i]==iCursor ){
   95923       return ((Bitmask)1)<<i;
   95924     }
   95925   }
   95926   return 0;
   95927 }
   95928 
   95929 /*
   95930 ** Create a new mask for cursor iCursor.
   95931 **
   95932 ** There is one cursor per table in the FROM clause.  The number of
   95933 ** tables in the FROM clause is limited by a test early in the
   95934 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
   95935 ** array will never overflow.
   95936 */
   95937 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   95938   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   95939   pMaskSet->ix[pMaskSet->n++] = iCursor;
   95940 }
   95941 
   95942 /*
   95943 ** This routine walks (recursively) an expression tree and generates
   95944 ** a bitmask indicating which tables are used in that expression
   95945 ** tree.
   95946 **
   95947 ** In order for this routine to work, the calling function must have
   95948 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
   95949 ** the header comment on that routine for additional information.
   95950 ** The sqlite3ResolveExprNames() routines looks for column names and
   95951 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
   95952 ** the VDBE cursor number of the table.  This routine just has to
   95953 ** translate the cursor numbers into bitmask values and OR all
   95954 ** the bitmasks together.
   95955 */
   95956 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   95957 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   95958 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   95959   Bitmask mask = 0;
   95960   if( p==0 ) return 0;
   95961   if( p->op==TK_COLUMN ){
   95962     mask = getMask(pMaskSet, p->iTable);
   95963     return mask;
   95964   }
   95965   mask = exprTableUsage(pMaskSet, p->pRight);
   95966   mask |= exprTableUsage(pMaskSet, p->pLeft);
   95967   if( ExprHasProperty(p, EP_xIsSelect) ){
   95968     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
   95969   }else{
   95970     mask |= exprListTableUsage(pMaskSet, p->x.pList);
   95971   }
   95972   return mask;
   95973 }
   95974 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
   95975   int i;
   95976   Bitmask mask = 0;
   95977   if( pList ){
   95978     for(i=0; i<pList->nExpr; i++){
   95979       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   95980     }
   95981   }
   95982   return mask;
   95983 }
   95984 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
   95985   Bitmask mask = 0;
   95986   while( pS ){
   95987     mask |= exprListTableUsage(pMaskSet, pS->pEList);
   95988     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
   95989     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
   95990     mask |= exprTableUsage(pMaskSet, pS->pWhere);
   95991     mask |= exprTableUsage(pMaskSet, pS->pHaving);
   95992     pS = pS->pPrior;
   95993   }
   95994   return mask;
   95995 }
   95996 
   95997 /*
   95998 ** Return TRUE if the given operator is one of the operators that is
   95999 ** allowed for an indexable WHERE clause term.  The allowed operators are
   96000 ** "=", "<", ">", "<=", ">=", and "IN".
   96001 **
   96002 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
   96003 ** of one of the following forms: column = expression column > expression
   96004 ** column >= expression column < expression column <= expression
   96005 ** expression = column expression > column expression >= column
   96006 ** expression < column expression <= column column IN
   96007 ** (expression-list) column IN (subquery) column IS NULL
   96008 */
   96009 static int allowedOp(int op){
   96010   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   96011   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   96012   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   96013   assert( TK_GE==TK_EQ+4 );
   96014   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
   96015 }
   96016 
   96017 /*
   96018 ** Swap two objects of type TYPE.
   96019 */
   96020 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
   96021 
   96022 /*
   96023 ** Commute a comparison operator.  Expressions of the form "X op Y"
   96024 ** are converted into "Y op X".
   96025 **
   96026 ** If a collation sequence is associated with either the left or right
   96027 ** side of the comparison, it remains associated with the same side after
   96028 ** the commutation. So "Y collate NOCASE op X" becomes
   96029 ** "X collate NOCASE op Y". This is because any collation sequence on
   96030 ** the left hand side of a comparison overrides any collation sequence
   96031 ** attached to the right. For the same reason the EP_ExpCollate flag
   96032 ** is not commuted.
   96033 */
   96034 static void exprCommute(Parse *pParse, Expr *pExpr){
   96035   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
   96036   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
   96037   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
   96038   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
   96039   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
   96040   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
   96041   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
   96042   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
   96043   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   96044   if( pExpr->op>=TK_GT ){
   96045     assert( TK_LT==TK_GT+2 );
   96046     assert( TK_GE==TK_LE+2 );
   96047     assert( TK_GT>TK_EQ );
   96048     assert( TK_GT<TK_LE );
   96049     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
   96050     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   96051   }
   96052 }
   96053 
   96054 /*
   96055 ** Translate from TK_xx operator to WO_xx bitmask.
   96056 */
   96057 static u16 operatorMask(int op){
   96058   u16 c;
   96059   assert( allowedOp(op) );
   96060   if( op==TK_IN ){
   96061     c = WO_IN;
   96062   }else if( op==TK_ISNULL ){
   96063     c = WO_ISNULL;
   96064   }else{
   96065     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
   96066     c = (u16)(WO_EQ<<(op-TK_EQ));
   96067   }
   96068   assert( op!=TK_ISNULL || c==WO_ISNULL );
   96069   assert( op!=TK_IN || c==WO_IN );
   96070   assert( op!=TK_EQ || c==WO_EQ );
   96071   assert( op!=TK_LT || c==WO_LT );
   96072   assert( op!=TK_LE || c==WO_LE );
   96073   assert( op!=TK_GT || c==WO_GT );
   96074   assert( op!=TK_GE || c==WO_GE );
   96075   return c;
   96076 }
   96077 
   96078 /*
   96079 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
   96080 ** where X is a reference to the iColumn of table iCur and <op> is one of
   96081 ** the WO_xx operator codes specified by the op parameter.
   96082 ** Return a pointer to the term.  Return 0 if not found.
   96083 */
   96084 static WhereTerm *findTerm(
   96085   WhereClause *pWC,     /* The WHERE clause to be searched */
   96086   int iCur,             /* Cursor number of LHS */
   96087   int iColumn,          /* Column number of LHS */
   96088   Bitmask notReady,     /* RHS must not overlap with this mask */
   96089   u32 op,               /* Mask of WO_xx values describing operator */
   96090   Index *pIdx           /* Must be compatible with this index, if not NULL */
   96091 ){
   96092   WhereTerm *pTerm;
   96093   int k;
   96094   assert( iCur>=0 );
   96095   op &= WO_ALL;
   96096   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
   96097     if( pTerm->leftCursor==iCur
   96098        && (pTerm->prereqRight & notReady)==0
   96099        && pTerm->u.leftColumn==iColumn
   96100        && (pTerm->eOperator & op)!=0
   96101     ){
   96102       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
   96103         Expr *pX = pTerm->pExpr;
   96104         CollSeq *pColl;
   96105         char idxaff;
   96106         int j;
   96107         Parse *pParse = pWC->pParse;
   96108 
   96109         idxaff = pIdx->pTable->aCol[iColumn].affinity;
   96110         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
   96111 
   96112         /* Figure out the collation sequence required from an index for
   96113         ** it to be useful for optimising expression pX. Store this
   96114         ** value in variable pColl.
   96115         */
   96116         assert(pX->pLeft);
   96117         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   96118         assert(pColl || pParse->nErr);
   96119 
   96120         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
   96121           if( NEVER(j>=pIdx->nColumn) ) return 0;
   96122         }
   96123         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
   96124       }
   96125       return pTerm;
   96126     }
   96127   }
   96128   return 0;
   96129 }
   96130 
   96131 /* Forward reference */
   96132 static void exprAnalyze(SrcList*, WhereClause*, int);
   96133 
   96134 /*
   96135 ** Call exprAnalyze on all terms in a WHERE clause.
   96136 **
   96137 **
   96138 */
   96139 static void exprAnalyzeAll(
   96140   SrcList *pTabList,       /* the FROM clause */
   96141   WhereClause *pWC         /* the WHERE clause to be analyzed */
   96142 ){
   96143   int i;
   96144   for(i=pWC->nTerm-1; i>=0; i--){
   96145     exprAnalyze(pTabList, pWC, i);
   96146   }
   96147 }
   96148 
   96149 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   96150 /*
   96151 ** Check to see if the given expression is a LIKE or GLOB operator that
   96152 ** can be optimized using inequality constraints.  Return TRUE if it is
   96153 ** so and false if not.
   96154 **
   96155 ** In order for the operator to be optimizible, the RHS must be a string
   96156 ** literal that does not begin with a wildcard.
   96157 */
   96158 static int isLikeOrGlob(
   96159   Parse *pParse,    /* Parsing and code generating context */
   96160   Expr *pExpr,      /* Test this expression */
   96161   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
   96162   int *pisComplete, /* True if the only wildcard is % in the last character */
   96163   int *pnoCase      /* True if uppercase is equivalent to lowercase */
   96164 ){
   96165   const char *z = 0;         /* String on RHS of LIKE operator */
   96166   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
   96167   ExprList *pList;           /* List of operands to the LIKE operator */
   96168   int c;                     /* One character in z[] */
   96169   int cnt;                   /* Number of non-wildcard prefix characters */
   96170   char wc[3];                /* Wildcard characters */
   96171   sqlite3 *db = pParse->db;  /* Database connection */
   96172   sqlite3_value *pVal = 0;
   96173   int op;                    /* Opcode of pRight */
   96174 
   96175   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
   96176     return 0;
   96177   }
   96178 #ifdef SQLITE_EBCDIC
   96179   if( *pnoCase ) return 0;
   96180 #endif
   96181   pList = pExpr->x.pList;
   96182   pLeft = pList->a[1].pExpr;
   96183   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
   96184     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
   96185     ** be the name of an indexed column with TEXT affinity. */
   96186     return 0;
   96187   }
   96188   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   96189 
   96190   pRight = pList->a[0].pExpr;
   96191   op = pRight->op;
   96192   if( op==TK_REGISTER ){
   96193     op = pRight->op2;
   96194   }
   96195   if( op==TK_VARIABLE ){
   96196     Vdbe *pReprepare = pParse->pReprepare;
   96197     int iCol = pRight->iColumn;
   96198     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
   96199     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   96200       z = (char *)sqlite3_value_text(pVal);
   96201     }
   96202     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
   96203     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
   96204   }else if( op==TK_STRING ){
   96205     z = pRight->u.zToken;
   96206   }
   96207   if( z ){
   96208     cnt = 0;
   96209     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
   96210       cnt++;
   96211     }
   96212     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
   96213       Expr *pPrefix;
   96214       *pisComplete = c==wc[0] && z[cnt+1]==0;
   96215       pPrefix = sqlite3Expr(db, TK_STRING, z);
   96216       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
   96217       *ppPrefix = pPrefix;
   96218       if( op==TK_VARIABLE ){
   96219         Vdbe *v = pParse->pVdbe;
   96220         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
   96221         if( *pisComplete && pRight->u.zToken[1] ){
   96222           /* If the rhs of the LIKE expression is a variable, and the current
   96223           ** value of the variable means there is no need to invoke the LIKE
   96224           ** function, then no OP_Variable will be added to the program.
   96225           ** This causes problems for the sqlite3_bind_parameter_name()
   96226           ** API. To workaround them, add a dummy OP_Variable here.
   96227           */
   96228           int r1 = sqlite3GetTempReg(pParse);
   96229           sqlite3ExprCodeTarget(pParse, pRight, r1);
   96230           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
   96231           sqlite3ReleaseTempReg(pParse, r1);
   96232         }
   96233       }
   96234     }else{
   96235       z = 0;
   96236     }
   96237   }
   96238 
   96239   sqlite3ValueFree(pVal);
   96240   return (z!=0);
   96241 }
   96242 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   96243 
   96244 
   96245 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96246 /*
   96247 ** Check to see if the given expression is of the form
   96248 **
   96249 **         column MATCH expr
   96250 **
   96251 ** If it is then return TRUE.  If not, return FALSE.
   96252 */
   96253 static int isMatchOfColumn(
   96254   Expr *pExpr      /* Test this expression */
   96255 ){
   96256   ExprList *pList;
   96257 
   96258   if( pExpr->op!=TK_FUNCTION ){
   96259     return 0;
   96260   }
   96261   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
   96262     return 0;
   96263   }
   96264   pList = pExpr->x.pList;
   96265   if( pList->nExpr!=2 ){
   96266     return 0;
   96267   }
   96268   if( pList->a[1].pExpr->op != TK_COLUMN ){
   96269     return 0;
   96270   }
   96271   return 1;
   96272 }
   96273 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   96274 
   96275 /*
   96276 ** If the pBase expression originated in the ON or USING clause of
   96277 ** a join, then transfer the appropriate markings over to derived.
   96278 */
   96279 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
   96280   pDerived->flags |= pBase->flags & EP_FromJoin;
   96281   pDerived->iRightJoinTable = pBase->iRightJoinTable;
   96282 }
   96283 
   96284 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   96285 /*
   96286 ** Analyze a term that consists of two or more OR-connected
   96287 ** subterms.  So in:
   96288 **
   96289 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
   96290 **                          ^^^^^^^^^^^^^^^^^^^^
   96291 **
   96292 ** This routine analyzes terms such as the middle term in the above example.
   96293 ** A WhereOrTerm object is computed and attached to the term under
   96294 ** analysis, regardless of the outcome of the analysis.  Hence:
   96295 **
   96296 **     WhereTerm.wtFlags   |=  TERM_ORINFO
   96297 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
   96298 **
   96299 ** The term being analyzed must have two or more of OR-connected subterms.
   96300 ** A single subterm might be a set of AND-connected sub-subterms.
   96301 ** Examples of terms under analysis:
   96302 **
   96303 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
   96304 **     (B)     x=expr1 OR expr2=x OR x=expr3
   96305 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
   96306 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
   96307 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
   96308 **
   96309 ** CASE 1:
   96310 **
   96311 ** If all subterms are of the form T.C=expr for some single column of C
   96312 ** a single table T (as shown in example B above) then create a new virtual
   96313 ** term that is an equivalent IN expression.  In other words, if the term
   96314 ** being analyzed is:
   96315 **
   96316 **      x = expr1  OR  expr2 = x  OR  x = expr3
   96317 **
   96318 ** then create a new virtual term like this:
   96319 **
   96320 **      x IN (expr1,expr2,expr3)
   96321 **
   96322 ** CASE 2:
   96323 **
   96324 ** If all subterms are indexable by a single table T, then set
   96325 **
   96326 **     WhereTerm.eOperator              =  WO_OR
   96327 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
   96328 **
   96329 ** A subterm is "indexable" if it is of the form
   96330 ** "T.C <op> <expr>" where C is any column of table T and
   96331 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
   96332 ** A subterm is also indexable if it is an AND of two or more
   96333 ** subsubterms at least one of which is indexable.  Indexable AND
   96334 ** subterms have their eOperator set to WO_AND and they have
   96335 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
   96336 **
   96337 ** From another point of view, "indexable" means that the subterm could
   96338 ** potentially be used with an index if an appropriate index exists.
   96339 ** This analysis does not consider whether or not the index exists; that
   96340 ** is something the bestIndex() routine will determine.  This analysis
   96341 ** only looks at whether subterms appropriate for indexing exist.
   96342 **
   96343 ** All examples A through E above all satisfy case 2.  But if a term
   96344 ** also statisfies case 1 (such as B) we know that the optimizer will
   96345 ** always prefer case 1, so in that case we pretend that case 2 is not
   96346 ** satisfied.
   96347 **
   96348 ** It might be the case that multiple tables are indexable.  For example,
   96349 ** (E) above is indexable on tables P, Q, and R.
   96350 **
   96351 ** Terms that satisfy case 2 are candidates for lookup by using
   96352 ** separate indices to find rowids for each subterm and composing
   96353 ** the union of all rowids using a RowSet object.  This is similar
   96354 ** to "bitmap indices" in other database engines.
   96355 **
   96356 ** OTHERWISE:
   96357 **
   96358 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
   96359 ** zero.  This term is not useful for search.
   96360 */
   96361 static void exprAnalyzeOrTerm(
   96362   SrcList *pSrc,            /* the FROM clause */
   96363   WhereClause *pWC,         /* the complete WHERE clause */
   96364   int idxTerm               /* Index of the OR-term to be analyzed */
   96365 ){
   96366   Parse *pParse = pWC->pParse;            /* Parser context */
   96367   sqlite3 *db = pParse->db;               /* Database connection */
   96368   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
   96369   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
   96370   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
   96371   int i;                                  /* Loop counters */
   96372   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
   96373   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
   96374   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
   96375   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
   96376   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
   96377 
   96378   /*
   96379   ** Break the OR clause into its separate subterms.  The subterms are
   96380   ** stored in a WhereClause structure containing within the WhereOrInfo
   96381   ** object that is attached to the original OR clause term.
   96382   */
   96383   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
   96384   assert( pExpr->op==TK_OR );
   96385   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
   96386   if( pOrInfo==0 ) return;
   96387   pTerm->wtFlags |= TERM_ORINFO;
   96388   pOrWc = &pOrInfo->wc;
   96389   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
   96390   whereSplit(pOrWc, pExpr, TK_OR);
   96391   exprAnalyzeAll(pSrc, pOrWc);
   96392   if( db->mallocFailed ) return;
   96393   assert( pOrWc->nTerm>=2 );
   96394 
   96395   /*
   96396   ** Compute the set of tables that might satisfy cases 1 or 2.
   96397   */
   96398   indexable = ~(Bitmask)0;
   96399   chngToIN = ~(pWC->vmask);
   96400   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   96401     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   96402       WhereAndInfo *pAndInfo;
   96403       assert( pOrTerm->eOperator==0 );
   96404       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   96405       chngToIN = 0;
   96406       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
   96407       if( pAndInfo ){
   96408         WhereClause *pAndWC;
   96409         WhereTerm *pAndTerm;
   96410         int j;
   96411         Bitmask b = 0;
   96412         pOrTerm->u.pAndInfo = pAndInfo;
   96413         pOrTerm->wtFlags |= TERM_ANDINFO;
   96414         pOrTerm->eOperator = WO_AND;
   96415         pAndWC = &pAndInfo->wc;
   96416         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
   96417         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   96418         exprAnalyzeAll(pSrc, pAndWC);
   96419         testcase( db->mallocFailed );
   96420         if( !db->mallocFailed ){
   96421           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   96422             assert( pAndTerm->pExpr );
   96423             if( allowedOp(pAndTerm->pExpr->op) ){
   96424               b |= getMask(pMaskSet, pAndTerm->leftCursor);
   96425             }
   96426           }
   96427         }
   96428         indexable &= b;
   96429       }
   96430     }else if( pOrTerm->wtFlags & TERM_COPIED ){
   96431       /* Skip this term for now.  We revisit it when we process the
   96432       ** corresponding TERM_VIRTUAL term */
   96433     }else{
   96434       Bitmask b;
   96435       b = getMask(pMaskSet, pOrTerm->leftCursor);
   96436       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
   96437         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
   96438         b |= getMask(pMaskSet, pOther->leftCursor);
   96439       }
   96440       indexable &= b;
   96441       if( pOrTerm->eOperator!=WO_EQ ){
   96442         chngToIN = 0;
   96443       }else{
   96444         chngToIN &= b;
   96445       }
   96446     }
   96447   }
   96448 
   96449   /*
   96450   ** Record the set of tables that satisfy case 2.  The set might be
   96451   ** empty.
   96452   */
   96453   pOrInfo->indexable = indexable;
   96454   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
   96455 
   96456   /*
   96457   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
   96458   ** we have to do some additional checking to see if case 1 really
   96459   ** is satisfied.
   96460   **
   96461   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
   96462   ** that there is no possibility of transforming the OR clause into an
   96463   ** IN operator because one or more terms in the OR clause contain
   96464   ** something other than == on a column in the single table.  The 1-bit
   96465   ** case means that every term of the OR clause is of the form
   96466   ** "table.column=expr" for some single table.  The one bit that is set
   96467   ** will correspond to the common table.  We still need to check to make
   96468   ** sure the same column is used on all terms.  The 2-bit case is when
   96469   ** the all terms are of the form "table1.column=table2.column".  It
   96470   ** might be possible to form an IN operator with either table1.column
   96471   ** or table2.column as the LHS if either is common to every term of
   96472   ** the OR clause.
   96473   **
   96474   ** Note that terms of the form "table.column1=table.column2" (the
   96475   ** same table on both sizes of the ==) cannot be optimized.
   96476   */
   96477   if( chngToIN ){
   96478     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
   96479     int iColumn = -1;         /* Column index on lhs of IN operator */
   96480     int iCursor = -1;         /* Table cursor common to all terms */
   96481     int j = 0;                /* Loop counter */
   96482 
   96483     /* Search for a table and column that appears on one side or the
   96484     ** other of the == operator in every subterm.  That table and column
   96485     ** will be recorded in iCursor and iColumn.  There might not be any
   96486     ** such table and column.  Set okToChngToIN if an appropriate table
   96487     ** and column is found but leave okToChngToIN false if not found.
   96488     */
   96489     for(j=0; j<2 && !okToChngToIN; j++){
   96490       pOrTerm = pOrWc->a;
   96491       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
   96492         assert( pOrTerm->eOperator==WO_EQ );
   96493         pOrTerm->wtFlags &= ~TERM_OR_OK;
   96494         if( pOrTerm->leftCursor==iCursor ){
   96495           /* This is the 2-bit case and we are on the second iteration and
   96496           ** current term is from the first iteration.  So skip this term. */
   96497           assert( j==1 );
   96498           continue;
   96499         }
   96500         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
   96501           /* This term must be of the form t1.a==t2.b where t2 is in the
   96502           ** chngToIN set but t1 is not.  This term will be either preceeded
   96503           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
   96504           ** and use its inversion. */
   96505           testcase( pOrTerm->wtFlags & TERM_COPIED );
   96506           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
   96507           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
   96508           continue;
   96509         }
   96510         iColumn = pOrTerm->u.leftColumn;
   96511         iCursor = pOrTerm->leftCursor;
   96512         break;
   96513       }
   96514       if( i<0 ){
   96515         /* No candidate table+column was found.  This can only occur
   96516         ** on the second iteration */
   96517         assert( j==1 );
   96518         assert( (chngToIN&(chngToIN-1))==0 );
   96519         assert( chngToIN==getMask(pMaskSet, iCursor) );
   96520         break;
   96521       }
   96522       testcase( j==1 );
   96523 
   96524       /* We have found a candidate table and column.  Check to see if that
   96525       ** table and column is common to every term in the OR clause */
   96526       okToChngToIN = 1;
   96527       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
   96528         assert( pOrTerm->eOperator==WO_EQ );
   96529         if( pOrTerm->leftCursor!=iCursor ){
   96530           pOrTerm->wtFlags &= ~TERM_OR_OK;
   96531         }else if( pOrTerm->u.leftColumn!=iColumn ){
   96532           okToChngToIN = 0;
   96533         }else{
   96534           int affLeft, affRight;
   96535           /* If the right-hand side is also a column, then the affinities
   96536           ** of both right and left sides must be such that no type
   96537           ** conversions are required on the right.  (Ticket #2249)
   96538           */
   96539           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
   96540           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
   96541           if( affRight!=0 && affRight!=affLeft ){
   96542             okToChngToIN = 0;
   96543           }else{
   96544             pOrTerm->wtFlags |= TERM_OR_OK;
   96545           }
   96546         }
   96547       }
   96548     }
   96549 
   96550     /* At this point, okToChngToIN is true if original pTerm satisfies
   96551     ** case 1.  In that case, construct a new virtual term that is
   96552     ** pTerm converted into an IN operator.
   96553     **
   96554     ** EV: R-00211-15100
   96555     */
   96556     if( okToChngToIN ){
   96557       Expr *pDup;            /* A transient duplicate expression */
   96558       ExprList *pList = 0;   /* The RHS of the IN operator */
   96559       Expr *pLeft = 0;       /* The LHS of the IN operator */
   96560       Expr *pNew;            /* The complete IN operator */
   96561 
   96562       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
   96563         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
   96564         assert( pOrTerm->eOperator==WO_EQ );
   96565         assert( pOrTerm->leftCursor==iCursor );
   96566         assert( pOrTerm->u.leftColumn==iColumn );
   96567         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
   96568         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
   96569         pLeft = pOrTerm->pExpr->pLeft;
   96570       }
   96571       assert( pLeft!=0 );
   96572       pDup = sqlite3ExprDup(db, pLeft, 0);
   96573       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
   96574       if( pNew ){
   96575         int idxNew;
   96576         transferJoinMarkings(pNew, pExpr);
   96577         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
   96578         pNew->x.pList = pList;
   96579         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
   96580         testcase( idxNew==0 );
   96581         exprAnalyze(pSrc, pWC, idxNew);
   96582         pTerm = &pWC->a[idxTerm];
   96583         pWC->a[idxNew].iParent = idxTerm;
   96584         pTerm->nChild = 1;
   96585       }else{
   96586         sqlite3ExprListDelete(db, pList);
   96587       }
   96588       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
   96589     }
   96590   }
   96591 }
   96592 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
   96593 
   96594 
   96595 /*
   96596 ** The input to this routine is an WhereTerm structure with only the
   96597 ** "pExpr" field filled in.  The job of this routine is to analyze the
   96598 ** subexpression and populate all the other fields of the WhereTerm
   96599 ** structure.
   96600 **
   96601 ** If the expression is of the form "<expr> <op> X" it gets commuted
   96602 ** to the standard form of "X <op> <expr>".
   96603 **
   96604 ** If the expression is of the form "X <op> Y" where both X and Y are
   96605 ** columns, then the original expression is unchanged and a new virtual
   96606 ** term of the form "Y <op> X" is added to the WHERE clause and
   96607 ** analyzed separately.  The original term is marked with TERM_COPIED
   96608 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
   96609 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
   96610 ** is a commuted copy of a prior term.)  The original term has nChild=1
   96611 ** and the copy has idxParent set to the index of the original term.
   96612 */
   96613 static void exprAnalyze(
   96614   SrcList *pSrc,            /* the FROM clause */
   96615   WhereClause *pWC,         /* the WHERE clause */
   96616   int idxTerm               /* Index of the term to be analyzed */
   96617 ){
   96618   WhereTerm *pTerm;                /* The term to be analyzed */
   96619   WhereMaskSet *pMaskSet;          /* Set of table index masks */
   96620   Expr *pExpr;                     /* The expression to be analyzed */
   96621   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
   96622   Bitmask prereqAll;               /* Prerequesites of pExpr */
   96623   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
   96624   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
   96625   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
   96626   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
   96627   int op;                          /* Top-level operator.  pExpr->op */
   96628   Parse *pParse = pWC->pParse;     /* Parsing context */
   96629   sqlite3 *db = pParse->db;        /* Database connection */
   96630 
   96631   if( db->mallocFailed ){
   96632     return;
   96633   }
   96634   pTerm = &pWC->a[idxTerm];
   96635   pMaskSet = pWC->pMaskSet;
   96636   pExpr = pTerm->pExpr;
   96637   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
   96638   op = pExpr->op;
   96639   if( op==TK_IN ){
   96640     assert( pExpr->pRight==0 );
   96641     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   96642       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
   96643     }else{
   96644       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
   96645     }
   96646   }else if( op==TK_ISNULL ){
   96647     pTerm->prereqRight = 0;
   96648   }else{
   96649     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
   96650   }
   96651   prereqAll = exprTableUsage(pMaskSet, pExpr);
   96652   if( ExprHasProperty(pExpr, EP_FromJoin) ){
   96653     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
   96654     prereqAll |= x;
   96655     extraRight = x-1;  /* ON clause terms may not be used with an index
   96656                        ** on left table of a LEFT JOIN.  Ticket #3015 */
   96657   }
   96658   pTerm->prereqAll = prereqAll;
   96659   pTerm->leftCursor = -1;
   96660   pTerm->iParent = -1;
   96661   pTerm->eOperator = 0;
   96662   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
   96663     Expr *pLeft = pExpr->pLeft;
   96664     Expr *pRight = pExpr->pRight;
   96665     if( pLeft->op==TK_COLUMN ){
   96666       pTerm->leftCursor = pLeft->iTable;
   96667       pTerm->u.leftColumn = pLeft->iColumn;
   96668       pTerm->eOperator = operatorMask(op);
   96669     }
   96670     if( pRight && pRight->op==TK_COLUMN ){
   96671       WhereTerm *pNew;
   96672       Expr *pDup;
   96673       if( pTerm->leftCursor>=0 ){
   96674         int idxNew;
   96675         pDup = sqlite3ExprDup(db, pExpr, 0);
   96676         if( db->mallocFailed ){
   96677           sqlite3ExprDelete(db, pDup);
   96678           return;
   96679         }
   96680         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
   96681         if( idxNew==0 ) return;
   96682         pNew = &pWC->a[idxNew];
   96683         pNew->iParent = idxTerm;
   96684         pTerm = &pWC->a[idxTerm];
   96685         pTerm->nChild = 1;
   96686         pTerm->wtFlags |= TERM_COPIED;
   96687       }else{
   96688         pDup = pExpr;
   96689         pNew = pTerm;
   96690       }
   96691       exprCommute(pParse, pDup);
   96692       pLeft = pDup->pLeft;
   96693       pNew->leftCursor = pLeft->iTable;
   96694       pNew->u.leftColumn = pLeft->iColumn;
   96695       testcase( (prereqLeft | extraRight) != prereqLeft );
   96696       pNew->prereqRight = prereqLeft | extraRight;
   96697       pNew->prereqAll = prereqAll;
   96698       pNew->eOperator = operatorMask(pDup->op);
   96699     }
   96700   }
   96701 
   96702 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
   96703   /* If a term is the BETWEEN operator, create two new virtual terms
   96704   ** that define the range that the BETWEEN implements.  For example:
   96705   **
   96706   **      a BETWEEN b AND c
   96707   **
   96708   ** is converted into:
   96709   **
   96710   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
   96711   **
   96712   ** The two new terms are added onto the end of the WhereClause object.
   96713   ** The new terms are "dynamic" and are children of the original BETWEEN
   96714   ** term.  That means that if the BETWEEN term is coded, the children are
   96715   ** skipped.  Or, if the children are satisfied by an index, the original
   96716   ** BETWEEN term is skipped.
   96717   */
   96718   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
   96719     ExprList *pList = pExpr->x.pList;
   96720     int i;
   96721     static const u8 ops[] = {TK_GE, TK_LE};
   96722     assert( pList!=0 );
   96723     assert( pList->nExpr==2 );
   96724     for(i=0; i<2; i++){
   96725       Expr *pNewExpr;
   96726       int idxNew;
   96727       pNewExpr = sqlite3PExpr(pParse, ops[i],
   96728                              sqlite3ExprDup(db, pExpr->pLeft, 0),
   96729                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
   96730       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   96731       testcase( idxNew==0 );
   96732       exprAnalyze(pSrc, pWC, idxNew);
   96733       pTerm = &pWC->a[idxTerm];
   96734       pWC->a[idxNew].iParent = idxTerm;
   96735     }
   96736     pTerm->nChild = 2;
   96737   }
   96738 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
   96739 
   96740 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
   96741   /* Analyze a term that is composed of two or more subterms connected by
   96742   ** an OR operator.
   96743   */
   96744   else if( pExpr->op==TK_OR ){
   96745     assert( pWC->op==TK_AND );
   96746     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
   96747     pTerm = &pWC->a[idxTerm];
   96748   }
   96749 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   96750 
   96751 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
   96752   /* Add constraints to reduce the search space on a LIKE or GLOB
   96753   ** operator.
   96754   **
   96755   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
   96756   **
   96757   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
   96758   **
   96759   ** The last character of the prefix "abc" is incremented to form the
   96760   ** termination condition "abd".
   96761   */
   96762   if( pWC->op==TK_AND
   96763    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   96764   ){
   96765     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
   96766     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
   96767     Expr *pNewExpr1;
   96768     Expr *pNewExpr2;
   96769     int idxNew1;
   96770     int idxNew2;
   96771     CollSeq *pColl;    /* Collating sequence to use */
   96772 
   96773     pLeft = pExpr->x.pList->a[1].pExpr;
   96774     pStr2 = sqlite3ExprDup(db, pStr1, 0);
   96775     if( !db->mallocFailed ){
   96776       u8 c, *pC;       /* Last character before the first wildcard */
   96777       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
   96778       c = *pC;
   96779       if( noCase ){
   96780         /* The point is to increment the last character before the first
   96781         ** wildcard.  But if we increment '@', that will push it into the
   96782         ** alphabetic range where case conversions will mess up the
   96783         ** inequality.  To avoid this, make sure to also run the full
   96784         ** LIKE on all candidate expressions by clearing the isComplete flag
   96785         */
   96786         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
   96787 
   96788 
   96789         c = sqlite3UpperToLower[c];
   96790       }
   96791       *pC = c + 1;
   96792     }
   96793     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
   96794     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
   96795                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   96796                      pStr1, 0);
   96797     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
   96798     testcase( idxNew1==0 );
   96799     exprAnalyze(pSrc, pWC, idxNew1);
   96800     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
   96801                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
   96802                      pStr2, 0);
   96803     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
   96804     testcase( idxNew2==0 );
   96805     exprAnalyze(pSrc, pWC, idxNew2);
   96806     pTerm = &pWC->a[idxTerm];
   96807     if( isComplete ){
   96808       pWC->a[idxNew1].iParent = idxTerm;
   96809       pWC->a[idxNew2].iParent = idxTerm;
   96810       pTerm->nChild = 2;
   96811     }
   96812   }
   96813 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
   96814 
   96815 #ifndef SQLITE_OMIT_VIRTUALTABLE
   96816   /* Add a WO_MATCH auxiliary term to the constraint set if the
   96817   ** current expression is of the form:  column MATCH expr.
   96818   ** This information is used by the xBestIndex methods of
   96819   ** virtual tables.  The native query optimizer does not attempt
   96820   ** to do anything with MATCH functions.
   96821   */
   96822   if( isMatchOfColumn(pExpr) ){
   96823     int idxNew;
   96824     Expr *pRight, *pLeft;
   96825     WhereTerm *pNewTerm;
   96826     Bitmask prereqColumn, prereqExpr;
   96827 
   96828     pRight = pExpr->x.pList->a[0].pExpr;
   96829     pLeft = pExpr->x.pList->a[1].pExpr;
   96830     prereqExpr = exprTableUsage(pMaskSet, pRight);
   96831     prereqColumn = exprTableUsage(pMaskSet, pLeft);
   96832     if( (prereqExpr & prereqColumn)==0 ){
   96833       Expr *pNewExpr;
   96834       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
   96835                               0, sqlite3ExprDup(db, pRight, 0), 0);
   96836       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
   96837       testcase( idxNew==0 );
   96838       pNewTerm = &pWC->a[idxNew];
   96839       pNewTerm->prereqRight = prereqExpr;
   96840       pNewTerm->leftCursor = pLeft->iTable;
   96841       pNewTerm->u.leftColumn = pLeft->iColumn;
   96842       pNewTerm->eOperator = WO_MATCH;
   96843       pNewTerm->iParent = idxTerm;
   96844       pTerm = &pWC->a[idxTerm];
   96845       pTerm->nChild = 1;
   96846       pTerm->wtFlags |= TERM_COPIED;
   96847       pNewTerm->prereqAll = pTerm->prereqAll;
   96848     }
   96849   }
   96850 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   96851 
   96852   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
   96853   ** an index for tables to the left of the join.
   96854   */
   96855   pTerm->prereqRight |= extraRight;
   96856 }
   96857 
   96858 /*
   96859 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
   96860 ** a reference to any table other than the iBase table.
   96861 */
   96862 static int referencesOtherTables(
   96863   ExprList *pList,          /* Search expressions in ths list */
   96864   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
   96865   int iFirst,               /* Be searching with the iFirst-th expression */
   96866   int iBase                 /* Ignore references to this table */
   96867 ){
   96868   Bitmask allowed = ~getMask(pMaskSet, iBase);
   96869   while( iFirst<pList->nExpr ){
   96870     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
   96871       return 1;
   96872     }
   96873   }
   96874   return 0;
   96875 }
   96876 
   96877 
   96878 /*
   96879 ** This routine decides if pIdx can be used to satisfy the ORDER BY
   96880 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
   96881 ** ORDER BY clause, this routine returns 0.
   96882 **
   96883 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
   96884 ** left-most table in the FROM clause of that same SELECT statement and
   96885 ** the table has a cursor number of "base".  pIdx is an index on pTab.
   96886 **
   96887 ** nEqCol is the number of columns of pIdx that are used as equality
   96888 ** constraints.  Any of these columns may be missing from the ORDER BY
   96889 ** clause and the match can still be a success.
   96890 **
   96891 ** All terms of the ORDER BY that match against the index must be either
   96892 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
   96893 ** index do not need to satisfy this constraint.)  The *pbRev value is
   96894 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
   96895 ** the ORDER BY clause is all ASC.
   96896 */
   96897 static int isSortingIndex(
   96898   Parse *pParse,          /* Parsing context */
   96899   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
   96900   Index *pIdx,            /* The index we are testing */
   96901   int base,               /* Cursor number for the table to be sorted */
   96902   ExprList *pOrderBy,     /* The ORDER BY clause */
   96903   int nEqCol,             /* Number of index columns with == constraints */
   96904   int *pbRev              /* Set to 1 if ORDER BY is DESC */
   96905 ){
   96906   int i, j;                       /* Loop counters */
   96907   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
   96908   int nTerm;                      /* Number of ORDER BY terms */
   96909   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
   96910   sqlite3 *db = pParse->db;
   96911 
   96912   assert( pOrderBy!=0 );
   96913   nTerm = pOrderBy->nExpr;
   96914   assert( nTerm>0 );
   96915 
   96916   /* Argument pIdx must either point to a 'real' named index structure,
   96917   ** or an index structure allocated on the stack by bestBtreeIndex() to
   96918   ** represent the rowid index that is part of every table.  */
   96919   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
   96920 
   96921   /* Match terms of the ORDER BY clause against columns of
   96922   ** the index.
   96923   **
   96924   ** Note that indices have pIdx->nColumn regular columns plus
   96925   ** one additional column containing the rowid.  The rowid column
   96926   ** of the index is also allowed to match against the ORDER BY
   96927   ** clause.
   96928   */
   96929   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
   96930     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
   96931     CollSeq *pColl;    /* The collating sequence of pExpr */
   96932     int termSortOrder; /* Sort order for this term */
   96933     int iColumn;       /* The i-th column of the index.  -1 for rowid */
   96934     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
   96935     const char *zColl; /* Name of the collating sequence for i-th index term */
   96936 
   96937     pExpr = pTerm->pExpr;
   96938     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
   96939       /* Can not use an index sort on anything that is not a column in the
   96940       ** left-most table of the FROM clause */
   96941       break;
   96942     }
   96943     pColl = sqlite3ExprCollSeq(pParse, pExpr);
   96944     if( !pColl ){
   96945       pColl = db->pDfltColl;
   96946     }
   96947     if( pIdx->zName && i<pIdx->nColumn ){
   96948       iColumn = pIdx->aiColumn[i];
   96949       if( iColumn==pIdx->pTable->iPKey ){
   96950         iColumn = -1;
   96951       }
   96952       iSortOrder = pIdx->aSortOrder[i];
   96953       zColl = pIdx->azColl[i];
   96954     }else{
   96955       iColumn = -1;
   96956       iSortOrder = 0;
   96957       zColl = pColl->zName;
   96958     }
   96959     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
   96960       /* Term j of the ORDER BY clause does not match column i of the index */
   96961       if( i<nEqCol ){
   96962         /* If an index column that is constrained by == fails to match an
   96963         ** ORDER BY term, that is OK.  Just ignore that column of the index
   96964         */
   96965         continue;
   96966       }else if( i==pIdx->nColumn ){
   96967         /* Index column i is the rowid.  All other terms match. */
   96968         break;
   96969       }else{
   96970         /* If an index column fails to match and is not constrained by ==
   96971         ** then the index cannot satisfy the ORDER BY constraint.
   96972         */
   96973         return 0;
   96974       }
   96975     }
   96976     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
   96977     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
   96978     assert( iSortOrder==0 || iSortOrder==1 );
   96979     termSortOrder = iSortOrder ^ pTerm->sortOrder;
   96980     if( i>nEqCol ){
   96981       if( termSortOrder!=sortOrder ){
   96982         /* Indices can only be used if all ORDER BY terms past the
   96983         ** equality constraints are all either DESC or ASC. */
   96984         return 0;
   96985       }
   96986     }else{
   96987       sortOrder = termSortOrder;
   96988     }
   96989     j++;
   96990     pTerm++;
   96991     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   96992       /* If the indexed column is the primary key and everything matches
   96993       ** so far and none of the ORDER BY terms to the right reference other
   96994       ** tables in the join, then we are assured that the index can be used
   96995       ** to sort because the primary key is unique and so none of the other
   96996       ** columns will make any difference
   96997       */
   96998       j = nTerm;
   96999     }
   97000   }
   97001 
   97002   *pbRev = sortOrder!=0;
   97003   if( j>=nTerm ){
   97004     /* All terms of the ORDER BY clause are covered by this index so
   97005     ** this index can be used for sorting. */
   97006     return 1;
   97007   }
   97008   if( pIdx->onError!=OE_None && i==pIdx->nColumn
   97009       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
   97010     /* All terms of this index match some prefix of the ORDER BY clause
   97011     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
   97012     ** clause reference other tables in a join.  If this is all true then
   97013     ** the order by clause is superfluous. */
   97014     return 1;
   97015   }
   97016   return 0;
   97017 }
   97018 
   97019 /*
   97020 ** Prepare a crude estimate of the logarithm of the input value.
   97021 ** The results need not be exact.  This is only used for estimating
   97022 ** the total cost of performing operations with O(logN) or O(NlogN)
   97023 ** complexity.  Because N is just a guess, it is no great tragedy if
   97024 ** logN is a little off.
   97025 */
   97026 static double estLog(double N){
   97027   double logN = 1;
   97028   double x = 10;
   97029   while( N>x ){
   97030     logN += 1;
   97031     x *= 10;
   97032   }
   97033   return logN;
   97034 }
   97035 
   97036 /*
   97037 ** Two routines for printing the content of an sqlite3_index_info
   97038 ** structure.  Used for testing and debugging only.  If neither
   97039 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
   97040 ** are no-ops.
   97041 */
   97042 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
   97043 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
   97044   int i;
   97045   if( !sqlite3WhereTrace ) return;
   97046   for(i=0; i<p->nConstraint; i++){
   97047     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
   97048        i,
   97049        p->aConstraint[i].iColumn,
   97050        p->aConstraint[i].iTermOffset,
   97051        p->aConstraint[i].op,
   97052        p->aConstraint[i].usable);
   97053   }
   97054   for(i=0; i<p->nOrderBy; i++){
   97055     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
   97056        i,
   97057        p->aOrderBy[i].iColumn,
   97058        p->aOrderBy[i].desc);
   97059   }
   97060 }
   97061 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   97062   int i;
   97063   if( !sqlite3WhereTrace ) return;
   97064   for(i=0; i<p->nConstraint; i++){
   97065     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
   97066        i,
   97067        p->aConstraintUsage[i].argvIndex,
   97068        p->aConstraintUsage[i].omit);
   97069   }
   97070   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
   97071   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
   97072   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
   97073   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
   97074 }
   97075 #else
   97076 #define TRACE_IDX_INPUTS(A)
   97077 #define TRACE_IDX_OUTPUTS(A)
   97078 #endif
   97079 
   97080 /*
   97081 ** Required because bestIndex() is called by bestOrClauseIndex()
   97082 */
   97083 static void bestIndex(
   97084     Parse*, WhereClause*, struct SrcList_item*,
   97085     Bitmask, Bitmask, ExprList*, WhereCost*);
   97086 
   97087 /*
   97088 ** This routine attempts to find an scanning strategy that can be used
   97089 ** to optimize an 'OR' expression that is part of a WHERE clause.
   97090 **
   97091 ** The table associated with FROM clause term pSrc may be either a
   97092 ** regular B-Tree table or a virtual table.
   97093 */
   97094 static void bestOrClauseIndex(
   97095   Parse *pParse,              /* The parsing context */
   97096   WhereClause *pWC,           /* The WHERE clause */
   97097   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   97098   Bitmask notReady,           /* Mask of cursors not available for indexing */
   97099   Bitmask notValid,           /* Cursors not available for any purpose */
   97100   ExprList *pOrderBy,         /* The ORDER BY clause */
   97101   WhereCost *pCost            /* Lowest cost query plan */
   97102 ){
   97103 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   97104   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   97105   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
   97106   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
   97107   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
   97108 
   97109   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
   97110   ** are used */
   97111   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
   97112     return;
   97113   }
   97114 
   97115   /* Search the WHERE clause terms for a usable WO_OR term. */
   97116   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   97117     if( pTerm->eOperator==WO_OR
   97118      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
   97119      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
   97120     ){
   97121       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
   97122       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
   97123       WhereTerm *pOrTerm;
   97124       int flags = WHERE_MULTI_OR;
   97125       double rTotal = 0;
   97126       double nRow = 0;
   97127       Bitmask used = 0;
   97128 
   97129       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
   97130         WhereCost sTermCost;
   97131         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
   97132           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
   97133         ));
   97134         if( pOrTerm->eOperator==WO_AND ){
   97135           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
   97136           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
   97137         }else if( pOrTerm->leftCursor==iCur ){
   97138           WhereClause tempWC;
   97139           tempWC.pParse = pWC->pParse;
   97140           tempWC.pMaskSet = pWC->pMaskSet;
   97141           tempWC.op = TK_AND;
   97142           tempWC.a = pOrTerm;
   97143           tempWC.nTerm = 1;
   97144           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
   97145         }else{
   97146           continue;
   97147         }
   97148         rTotal += sTermCost.rCost;
   97149         nRow += sTermCost.plan.nRow;
   97150         used |= sTermCost.used;
   97151         if( rTotal>=pCost->rCost ) break;
   97152       }
   97153 
   97154       /* If there is an ORDER BY clause, increase the scan cost to account
   97155       ** for the cost of the sort. */
   97156       if( pOrderBy!=0 ){
   97157         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
   97158                     rTotal, rTotal+nRow*estLog(nRow)));
   97159         rTotal += nRow*estLog(nRow);
   97160       }
   97161 
   97162       /* If the cost of scanning using this OR term for optimization is
   97163       ** less than the current cost stored in pCost, replace the contents
   97164       ** of pCost. */
   97165       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
   97166       if( rTotal<pCost->rCost ){
   97167         pCost->rCost = rTotal;
   97168         pCost->used = used;
   97169         pCost->plan.nRow = nRow;
   97170         pCost->plan.wsFlags = flags;
   97171         pCost->plan.u.pTerm = pTerm;
   97172       }
   97173     }
   97174   }
   97175 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   97176 }
   97177 
   97178 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   97179 /*
   97180 ** Return TRUE if the WHERE clause term pTerm is of a form where it
   97181 ** could be used with an index to access pSrc, assuming an appropriate
   97182 ** index existed.
   97183 */
   97184 static int termCanDriveIndex(
   97185   WhereTerm *pTerm,              /* WHERE clause term to check */
   97186   struct SrcList_item *pSrc,     /* Table we are trying to access */
   97187   Bitmask notReady               /* Tables in outer loops of the join */
   97188 ){
   97189   char aff;
   97190   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   97191   if( pTerm->eOperator!=WO_EQ ) return 0;
   97192   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
   97193   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
   97194   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   97195   return 1;
   97196 }
   97197 #endif
   97198 
   97199 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   97200 /*
   97201 ** If the query plan for pSrc specified in pCost is a full table scan
   97202 ** and indexing is allows (if there is no NOT INDEXED clause) and it
   97203 ** possible to construct a transient index that would perform better
   97204 ** than a full table scan even when the cost of constructing the index
   97205 ** is taken into account, then alter the query plan to use the
   97206 ** transient index.
   97207 */
   97208 static void bestAutomaticIndex(
   97209   Parse *pParse,              /* The parsing context */
   97210   WhereClause *pWC,           /* The WHERE clause */
   97211   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   97212   Bitmask notReady,           /* Mask of cursors that are not available */
   97213   WhereCost *pCost            /* Lowest cost query plan */
   97214 ){
   97215   double nTableRow;           /* Rows in the input table */
   97216   double logN;                /* log(nTableRow) */
   97217   double costTempIdx;         /* per-query cost of the transient index */
   97218   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   97219   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   97220   Table *pTable;              /* Table tht might be indexed */
   97221 
   97222   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
   97223     /* Automatic indices are disabled at run-time */
   97224     return;
   97225   }
   97226   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
   97227     /* We already have some kind of index in use for this query. */
   97228     return;
   97229   }
   97230   if( pSrc->notIndexed ){
   97231     /* The NOT INDEXED clause appears in the SQL. */
   97232     return;
   97233   }
   97234 
   97235   assert( pParse->nQueryLoop >= (double)1 );
   97236   pTable = pSrc->pTab;
   97237   nTableRow = pTable->nRowEst;
   97238   logN = estLog(nTableRow);
   97239   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
   97240   if( costTempIdx>=pCost->rCost ){
   97241     /* The cost of creating the transient table would be greater than
   97242     ** doing the full table scan */
   97243     return;
   97244   }
   97245 
   97246   /* Search for any equality comparison term */
   97247   pWCEnd = &pWC->a[pWC->nTerm];
   97248   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   97249     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   97250       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
   97251                     pCost->rCost, costTempIdx));
   97252       pCost->rCost = costTempIdx;
   97253       pCost->plan.nRow = logN + 1;
   97254       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
   97255       pCost->used = pTerm->prereqRight;
   97256       break;
   97257     }
   97258   }
   97259 }
   97260 #else
   97261 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
   97262 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   97263 
   97264 
   97265 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   97266 /*
   97267 ** Generate code to construct the Index object for an automatic index
   97268 ** and to set up the WhereLevel object pLevel so that the code generator
   97269 ** makes use of the automatic index.
   97270 */
   97271 static void constructAutomaticIndex(
   97272   Parse *pParse,              /* The parsing context */
   97273   WhereClause *pWC,           /* The WHERE clause */
   97274   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
   97275   Bitmask notReady,           /* Mask of cursors that are not available */
   97276   WhereLevel *pLevel          /* Write new index here */
   97277 ){
   97278   int nColumn;                /* Number of columns in the constructed index */
   97279   WhereTerm *pTerm;           /* A single term of the WHERE clause */
   97280   WhereTerm *pWCEnd;          /* End of pWC->a[] */
   97281   int nByte;                  /* Byte of memory needed for pIdx */
   97282   Index *pIdx;                /* Object describing the transient index */
   97283   Vdbe *v;                    /* Prepared statement under construction */
   97284   int regIsInit;              /* Register set by initialization */
   97285   int addrInit;               /* Address of the initialization bypass jump */
   97286   Table *pTable;              /* The table being indexed */
   97287   KeyInfo *pKeyinfo;          /* Key information for the index */
   97288   int addrTop;                /* Top of the index fill loop */
   97289   int regRecord;              /* Register holding an index record */
   97290   int n;                      /* Column counter */
   97291   int i;                      /* Loop counter */
   97292   int mxBitCol;               /* Maximum column in pSrc->colUsed */
   97293   CollSeq *pColl;             /* Collating sequence to on a column */
   97294   Bitmask idxCols;            /* Bitmap of columns used for indexing */
   97295   Bitmask extraCols;          /* Bitmap of additional columns */
   97296 
   97297   /* Generate code to skip over the creation and initialization of the
   97298   ** transient index on 2nd and subsequent iterations of the loop. */
   97299   v = pParse->pVdbe;
   97300   assert( v!=0 );
   97301   regIsInit = ++pParse->nMem;
   97302   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
   97303   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
   97304 
   97305   /* Count the number of columns that will be added to the index
   97306   ** and used to match WHERE clause constraints */
   97307   nColumn = 0;
   97308   pTable = pSrc->pTab;
   97309   pWCEnd = &pWC->a[pWC->nTerm];
   97310   idxCols = 0;
   97311   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   97312     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   97313       int iCol = pTerm->u.leftColumn;
   97314       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   97315       testcase( iCol==BMS );
   97316       testcase( iCol==BMS-1 );
   97317       if( (idxCols & cMask)==0 ){
   97318         nColumn++;
   97319         idxCols |= cMask;
   97320       }
   97321     }
   97322   }
   97323   assert( nColumn>0 );
   97324   pLevel->plan.nEq = nColumn;
   97325 
   97326   /* Count the number of additional columns needed to create a
   97327   ** covering index.  A "covering index" is an index that contains all
   97328   ** columns that are needed by the query.  With a covering index, the
   97329   ** original table never needs to be accessed.  Automatic indices must
   97330   ** be a covering index because the index will not be updated if the
   97331   ** original table changes and the index and table cannot both be used
   97332   ** if they go out of sync.
   97333   */
   97334   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
   97335   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
   97336   testcase( pTable->nCol==BMS-1 );
   97337   testcase( pTable->nCol==BMS-2 );
   97338   for(i=0; i<mxBitCol; i++){
   97339     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
   97340   }
   97341   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   97342     nColumn += pTable->nCol - BMS + 1;
   97343   }
   97344   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
   97345 
   97346   /* Construct the Index object to describe this index */
   97347   nByte = sizeof(Index);
   97348   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
   97349   nByte += nColumn*sizeof(char*);   /* Index.azColl */
   97350   nByte += nColumn;                 /* Index.aSortOrder */
   97351   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
   97352   if( pIdx==0 ) return;
   97353   pLevel->plan.u.pIdx = pIdx;
   97354   pIdx->azColl = (char**)&pIdx[1];
   97355   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
   97356   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
   97357   pIdx->zName = "auto-index";
   97358   pIdx->nColumn = nColumn;
   97359   pIdx->pTable = pTable;
   97360   n = 0;
   97361   idxCols = 0;
   97362   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
   97363     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
   97364       int iCol = pTerm->u.leftColumn;
   97365       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
   97366       if( (idxCols & cMask)==0 ){
   97367         Expr *pX = pTerm->pExpr;
   97368         idxCols |= cMask;
   97369         pIdx->aiColumn[n] = pTerm->u.leftColumn;
   97370         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
   97371         pIdx->azColl[n] = pColl->zName;
   97372         n++;
   97373       }
   97374     }
   97375   }
   97376   assert( (u32)n==pLevel->plan.nEq );
   97377 
   97378   /* Add additional columns needed to make the automatic index into
   97379   ** a covering index */
   97380   for(i=0; i<mxBitCol; i++){
   97381     if( extraCols & (((Bitmask)1)<<i) ){
   97382       pIdx->aiColumn[n] = i;
   97383       pIdx->azColl[n] = "BINARY";
   97384       n++;
   97385     }
   97386   }
   97387   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
   97388     for(i=BMS-1; i<pTable->nCol; i++){
   97389       pIdx->aiColumn[n] = i;
   97390       pIdx->azColl[n] = "BINARY";
   97391       n++;
   97392     }
   97393   }
   97394   assert( n==nColumn );
   97395 
   97396   /* Create the automatic index */
   97397   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
   97398   assert( pLevel->iIdxCur>=0 );
   97399   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
   97400                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
   97401   VdbeComment((v, "for %s", pTable->zName));
   97402 
   97403   /* Fill the automatic index with content */
   97404   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
   97405   regRecord = sqlite3GetTempReg(pParse);
   97406   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
   97407   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
   97408   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   97409   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
   97410   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   97411   sqlite3VdbeJumpHere(v, addrTop);
   97412   sqlite3ReleaseTempReg(pParse, regRecord);
   97413 
   97414   /* Jump here when skipping the initialization */
   97415   sqlite3VdbeJumpHere(v, addrInit);
   97416 }
   97417 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
   97418 
   97419 #ifndef SQLITE_OMIT_VIRTUALTABLE
   97420 /*
   97421 ** Allocate and populate an sqlite3_index_info structure. It is the
   97422 ** responsibility of the caller to eventually release the structure
   97423 ** by passing the pointer returned by this function to sqlite3_free().
   97424 */
   97425 static sqlite3_index_info *allocateIndexInfo(
   97426   Parse *pParse,
   97427   WhereClause *pWC,
   97428   struct SrcList_item *pSrc,
   97429   ExprList *pOrderBy
   97430 ){
   97431   int i, j;
   97432   int nTerm;
   97433   struct sqlite3_index_constraint *pIdxCons;
   97434   struct sqlite3_index_orderby *pIdxOrderBy;
   97435   struct sqlite3_index_constraint_usage *pUsage;
   97436   WhereTerm *pTerm;
   97437   int nOrderBy;
   97438   sqlite3_index_info *pIdxInfo;
   97439 
   97440   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
   97441 
   97442   /* Count the number of possible WHERE clause constraints referring
   97443   ** to this virtual table */
   97444   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   97445     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   97446     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   97447     testcase( pTerm->eOperator==WO_IN );
   97448     testcase( pTerm->eOperator==WO_ISNULL );
   97449     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   97450     nTerm++;
   97451   }
   97452 
   97453   /* If the ORDER BY clause contains only columns in the current
   97454   ** virtual table then allocate space for the aOrderBy part of
   97455   ** the sqlite3_index_info structure.
   97456   */
   97457   nOrderBy = 0;
   97458   if( pOrderBy ){
   97459     for(i=0; i<pOrderBy->nExpr; i++){
   97460       Expr *pExpr = pOrderBy->a[i].pExpr;
   97461       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
   97462     }
   97463     if( i==pOrderBy->nExpr ){
   97464       nOrderBy = pOrderBy->nExpr;
   97465     }
   97466   }
   97467 
   97468   /* Allocate the sqlite3_index_info structure
   97469   */
   97470   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
   97471                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
   97472                            + sizeof(*pIdxOrderBy)*nOrderBy );
   97473   if( pIdxInfo==0 ){
   97474     sqlite3ErrorMsg(pParse, "out of memory");
   97475     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
   97476     return 0;
   97477   }
   97478 
   97479   /* Initialize the structure.  The sqlite3_index_info structure contains
   97480   ** many fields that are declared "const" to prevent xBestIndex from
   97481   ** changing them.  We have to do some funky casting in order to
   97482   ** initialize those fields.
   97483   */
   97484   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
   97485   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   97486   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
   97487   *(int*)&pIdxInfo->nConstraint = nTerm;
   97488   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
   97489   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
   97490   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
   97491   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
   97492                                                                    pUsage;
   97493 
   97494   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
   97495     if( pTerm->leftCursor != pSrc->iCursor ) continue;
   97496     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
   97497     testcase( pTerm->eOperator==WO_IN );
   97498     testcase( pTerm->eOperator==WO_ISNULL );
   97499     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
   97500     pIdxCons[j].iColumn = pTerm->u.leftColumn;
   97501     pIdxCons[j].iTermOffset = i;
   97502     pIdxCons[j].op = (u8)pTerm->eOperator;
   97503     /* The direct assignment in the previous line is possible only because
   97504     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
   97505     ** following asserts verify this fact. */
   97506     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
   97507     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
   97508     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
   97509     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
   97510     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
   97511     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
   97512     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
   97513     j++;
   97514   }
   97515   for(i=0; i<nOrderBy; i++){
   97516     Expr *pExpr = pOrderBy->a[i].pExpr;
   97517     pIdxOrderBy[i].iColumn = pExpr->iColumn;
   97518     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
   97519   }
   97520 
   97521   return pIdxInfo;
   97522 }
   97523 
   97524 /*
   97525 ** The table object reference passed as the second argument to this function
   97526 ** must represent a virtual table. This function invokes the xBestIndex()
   97527 ** method of the virtual table with the sqlite3_index_info pointer passed
   97528 ** as the argument.
   97529 **
   97530 ** If an error occurs, pParse is populated with an error message and a
   97531 ** non-zero value is returned. Otherwise, 0 is returned and the output
   97532 ** part of the sqlite3_index_info structure is left populated.
   97533 **
   97534 ** Whether or not an error is returned, it is the responsibility of the
   97535 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
   97536 ** that this is required.
   97537 */
   97538 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   97539   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   97540   int i;
   97541   int rc;
   97542 
   97543   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
   97544   TRACE_IDX_INPUTS(p);
   97545   rc = pVtab->pModule->xBestIndex(pVtab, p);
   97546   TRACE_IDX_OUTPUTS(p);
   97547 
   97548   if( rc!=SQLITE_OK ){
   97549     if( rc==SQLITE_NOMEM ){
   97550       pParse->db->mallocFailed = 1;
   97551     }else if( !pVtab->zErrMsg ){
   97552       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   97553     }else{
   97554       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   97555     }
   97556   }
   97557   sqlite3_free(pVtab->zErrMsg);
   97558   pVtab->zErrMsg = 0;
   97559 
   97560   for(i=0; i<p->nConstraint; i++){
   97561     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
   97562       sqlite3ErrorMsg(pParse,
   97563           "table %s: xBestIndex returned an invalid plan", pTab->zName);
   97564     }
   97565   }
   97566 
   97567   return pParse->nErr;
   97568 }
   97569 
   97570 
   97571 /*
   97572 ** Compute the best index for a virtual table.
   97573 **
   97574 ** The best index is computed by the xBestIndex method of the virtual
   97575 ** table module.  This routine is really just a wrapper that sets up
   97576 ** the sqlite3_index_info structure that is used to communicate with
   97577 ** xBestIndex.
   97578 **
   97579 ** In a join, this routine might be called multiple times for the
   97580 ** same virtual table.  The sqlite3_index_info structure is created
   97581 ** and initialized on the first invocation and reused on all subsequent
   97582 ** invocations.  The sqlite3_index_info structure is also used when
   97583 ** code is generated to access the virtual table.  The whereInfoDelete()
   97584 ** routine takes care of freeing the sqlite3_index_info structure after
   97585 ** everybody has finished with it.
   97586 */
   97587 static void bestVirtualIndex(
   97588   Parse *pParse,                  /* The parsing context */
   97589   WhereClause *pWC,               /* The WHERE clause */
   97590   struct SrcList_item *pSrc,      /* The FROM clause term to search */
   97591   Bitmask notReady,               /* Mask of cursors not available for index */
   97592   Bitmask notValid,               /* Cursors not valid for any purpose */
   97593   ExprList *pOrderBy,             /* The order by clause */
   97594   WhereCost *pCost,               /* Lowest cost query plan */
   97595   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
   97596 ){
   97597   Table *pTab = pSrc->pTab;
   97598   sqlite3_index_info *pIdxInfo;
   97599   struct sqlite3_index_constraint *pIdxCons;
   97600   struct sqlite3_index_constraint_usage *pUsage;
   97601   WhereTerm *pTerm;
   97602   int i, j;
   97603   int nOrderBy;
   97604   double rCost;
   97605 
   97606   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
   97607   ** malloc in allocateIndexInfo() fails and this function returns leaving
   97608   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
   97609   */
   97610   memset(pCost, 0, sizeof(*pCost));
   97611   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
   97612 
   97613   /* If the sqlite3_index_info structure has not been previously
   97614   ** allocated and initialized, then allocate and initialize it now.
   97615   */
   97616   pIdxInfo = *ppIdxInfo;
   97617   if( pIdxInfo==0 ){
   97618     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
   97619   }
   97620   if( pIdxInfo==0 ){
   97621     return;
   97622   }
   97623 
   97624   /* At this point, the sqlite3_index_info structure that pIdxInfo points
   97625   ** to will have been initialized, either during the current invocation or
   97626   ** during some prior invocation.  Now we just have to customize the
   97627   ** details of pIdxInfo for the current invocation and pass it to
   97628   ** xBestIndex.
   97629   */
   97630 
   97631   /* The module name must be defined. Also, by this point there must
   97632   ** be a pointer to an sqlite3_vtab structure. Otherwise
   97633   ** sqlite3ViewGetColumnNames() would have picked up the error.
   97634   */
   97635   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
   97636   assert( sqlite3GetVTable(pParse->db, pTab) );
   97637 
   97638   /* Set the aConstraint[].usable fields and initialize all
   97639   ** output variables to zero.
   97640   **
   97641   ** aConstraint[].usable is true for constraints where the right-hand
   97642   ** side contains only references to tables to the left of the current
   97643   ** table.  In other words, if the constraint is of the form:
   97644   **
   97645   **           column = expr
   97646   **
   97647   ** and we are evaluating a join, then the constraint on column is
   97648   ** only valid if all tables referenced in expr occur to the left
   97649   ** of the table containing column.
   97650   **
   97651   ** The aConstraints[] array contains entries for all constraints
   97652   ** on the current table.  That way we only have to compute it once
   97653   ** even though we might try to pick the best index multiple times.
   97654   ** For each attempt at picking an index, the order of tables in the
   97655   ** join might be different so we have to recompute the usable flag
   97656   ** each time.
   97657   */
   97658   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   97659   pUsage = pIdxInfo->aConstraintUsage;
   97660   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
   97661     j = pIdxCons->iTermOffset;
   97662     pTerm = &pWC->a[j];
   97663     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
   97664   }
   97665   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
   97666   if( pIdxInfo->needToFreeIdxStr ){
   97667     sqlite3_free(pIdxInfo->idxStr);
   97668   }
   97669   pIdxInfo->idxStr = 0;
   97670   pIdxInfo->idxNum = 0;
   97671   pIdxInfo->needToFreeIdxStr = 0;
   97672   pIdxInfo->orderByConsumed = 0;
   97673   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
   97674   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
   97675   nOrderBy = pIdxInfo->nOrderBy;
   97676   if( !pOrderBy ){
   97677     pIdxInfo->nOrderBy = 0;
   97678   }
   97679 
   97680   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
   97681     return;
   97682   }
   97683 
   97684   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   97685   for(i=0; i<pIdxInfo->nConstraint; i++){
   97686     if( pUsage[i].argvIndex>0 ){
   97687       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
   97688     }
   97689   }
   97690 
   97691   /* If there is an ORDER BY clause, and the selected virtual table index
   97692   ** does not satisfy it, increase the cost of the scan accordingly. This
   97693   ** matches the processing for non-virtual tables in bestBtreeIndex().
   97694   */
   97695   rCost = pIdxInfo->estimatedCost;
   97696   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
   97697     rCost += estLog(rCost)*rCost;
   97698   }
   97699 
   97700   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
   97701   ** inital value of lowestCost in this loop. If it is, then the
   97702   ** (cost<lowestCost) test below will never be true.
   97703   **
   97704   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
   97705   ** is defined.
   97706   */
   97707   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
   97708     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
   97709   }else{
   97710     pCost->rCost = rCost;
   97711   }
   97712   pCost->plan.u.pVtabIdx = pIdxInfo;
   97713   if( pIdxInfo->orderByConsumed ){
   97714     pCost->plan.wsFlags |= WHERE_ORDERBY;
   97715   }
   97716   pCost->plan.nEq = 0;
   97717   pIdxInfo->nOrderBy = nOrderBy;
   97718 
   97719   /* Try to find a more efficient access pattern by using multiple indexes
   97720   ** to optimize an OR expression within the WHERE clause.
   97721   */
   97722   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   97723 }
   97724 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   97725 
   97726 /*
   97727 ** Argument pIdx is a pointer to an index structure that has an array of
   97728 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
   97729 ** stored in Index.aSample. The domain of values stored in said column
   97730 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
   97731 ** Region 0 contains all values smaller than the first sample value. Region
   97732 ** 1 contains values larger than or equal to the value of the first sample,
   97733 ** but smaller than the value of the second. And so on.
   97734 **
   97735 ** If successful, this function determines which of the regions value
   97736 ** pVal lies in, sets *piRegion to the region index (a value between 0
   97737 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
   97738 ** Or, if an OOM occurs while converting text values between encodings,
   97739 ** SQLITE_NOMEM is returned and *piRegion is undefined.
   97740 */
   97741 #ifdef SQLITE_ENABLE_STAT2
   97742 static int whereRangeRegion(
   97743   Parse *pParse,              /* Database connection */
   97744   Index *pIdx,                /* Index to consider domain of */
   97745   sqlite3_value *pVal,        /* Value to consider */
   97746   int *piRegion               /* OUT: Region of domain in which value lies */
   97747 ){
   97748   if( ALWAYS(pVal) ){
   97749     IndexSample *aSample = pIdx->aSample;
   97750     int i = 0;
   97751     int eType = sqlite3_value_type(pVal);
   97752 
   97753     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
   97754       double r = sqlite3_value_double(pVal);
   97755       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
   97756         if( aSample[i].eType==SQLITE_NULL ) continue;
   97757         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
   97758       }
   97759     }else{
   97760       sqlite3 *db = pParse->db;
   97761       CollSeq *pColl;
   97762       const u8 *z;
   97763       int n;
   97764 
   97765       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
   97766       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
   97767 
   97768       if( eType==SQLITE_BLOB ){
   97769         z = (const u8 *)sqlite3_value_blob(pVal);
   97770         pColl = db->pDfltColl;
   97771         assert( pColl->enc==SQLITE_UTF8 );
   97772       }else{
   97773         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
   97774         if( pColl==0 ){
   97775           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
   97776                           *pIdx->azColl);
   97777           return SQLITE_ERROR;
   97778         }
   97779         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
   97780         if( !z ){
   97781           return SQLITE_NOMEM;
   97782         }
   97783         assert( z && pColl && pColl->xCmp );
   97784       }
   97785       n = sqlite3ValueBytes(pVal, pColl->enc);
   97786 
   97787       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
   97788         int r;
   97789         int eSampletype = aSample[i].eType;
   97790         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
   97791         if( (eSampletype!=eType) ) break;
   97792 #ifndef SQLITE_OMIT_UTF16
   97793         if( pColl->enc!=SQLITE_UTF8 ){
   97794           int nSample;
   97795           char *zSample = sqlite3Utf8to16(
   97796               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
   97797           );
   97798           if( !zSample ){
   97799             assert( db->mallocFailed );
   97800             return SQLITE_NOMEM;
   97801           }
   97802           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
   97803           sqlite3DbFree(db, zSample);
   97804         }else
   97805 #endif
   97806         {
   97807           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
   97808         }
   97809         if( r>0 ) break;
   97810       }
   97811     }
   97812 
   97813     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
   97814     *piRegion = i;
   97815   }
   97816   return SQLITE_OK;
   97817 }
   97818 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
   97819 
   97820 /*
   97821 ** If expression pExpr represents a literal value, set *pp to point to
   97822 ** an sqlite3_value structure containing the same value, with affinity
   97823 ** aff applied to it, before returning. It is the responsibility of the
   97824 ** caller to eventually release this structure by passing it to
   97825 ** sqlite3ValueFree().
   97826 **
   97827 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
   97828 ** is an SQL variable that currently has a non-NULL value bound to it,
   97829 ** create an sqlite3_value structure containing this value, again with
   97830 ** affinity aff applied to it, instead.
   97831 **
   97832 ** If neither of the above apply, set *pp to NULL.
   97833 **
   97834 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
   97835 */
   97836 #ifdef SQLITE_ENABLE_STAT2
   97837 static int valueFromExpr(
   97838   Parse *pParse,
   97839   Expr *pExpr,
   97840   u8 aff,
   97841   sqlite3_value **pp
   97842 ){
   97843   if( pExpr->op==TK_VARIABLE
   97844    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
   97845   ){
   97846     int iVar = pExpr->iColumn;
   97847     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
   97848     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
   97849     return SQLITE_OK;
   97850   }
   97851   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
   97852 }
   97853 #endif
   97854 
   97855 /*
   97856 ** This function is used to estimate the number of rows that will be visited
   97857 ** by scanning an index for a range of values. The range may have an upper
   97858 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
   97859 ** and lower bounds are represented by pLower and pUpper respectively. For
   97860 ** example, assuming that index p is on t1(a):
   97861 **
   97862 **   ... FROM t1 WHERE a > ? AND a < ? ...
   97863 **                    |_____|   |_____|
   97864 **                       |         |
   97865 **                     pLower    pUpper
   97866 **
   97867 ** If either of the upper or lower bound is not present, then NULL is passed in
   97868 ** place of the corresponding WhereTerm.
   97869 **
   97870 ** The nEq parameter is passed the index of the index column subject to the
   97871 ** range constraint. Or, equivalently, the number of equality constraints
   97872 ** optimized by the proposed index scan. For example, assuming index p is
   97873 ** on t1(a, b), and the SQL query is:
   97874 **
   97875 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
   97876 **
   97877 ** then nEq should be passed the value 1 (as the range restricted column,
   97878 ** b, is the second left-most column of the index). Or, if the query is:
   97879 **
   97880 **   ... FROM t1 WHERE a > ? AND a < ? ...
   97881 **
   97882 ** then nEq should be passed 0.
   97883 **
   97884 ** The returned value is an integer between 1 and 100, inclusive. A return
   97885 ** value of 1 indicates that the proposed range scan is expected to visit
   97886 ** approximately 1/100th (1%) of the rows selected by the nEq equality
   97887 ** constraints (if any). A return value of 100 indicates that it is expected
   97888 ** that the range scan will visit every row (100%) selected by the equality
   97889 ** constraints.
   97890 **
   97891 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
   97892 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
   97893 ** results in a return of 33 and a range constraint (x>? AND x<?) results
   97894 ** in a return of 11.
   97895 */
   97896 static int whereRangeScanEst(
   97897   Parse *pParse,       /* Parsing & code generating context */
   97898   Index *p,            /* The index containing the range-compared column; "x" */
   97899   int nEq,             /* index into p->aCol[] of the range-compared column */
   97900   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
   97901   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
   97902   int *piEst           /* OUT: Return value */
   97903 ){
   97904   int rc = SQLITE_OK;
   97905 
   97906 #ifdef SQLITE_ENABLE_STAT2
   97907 
   97908   if( nEq==0 && p->aSample ){
   97909     sqlite3_value *pLowerVal = 0;
   97910     sqlite3_value *pUpperVal = 0;
   97911     int iEst;
   97912     int iLower = 0;
   97913     int iUpper = SQLITE_INDEX_SAMPLES;
   97914     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
   97915 
   97916     if( pLower ){
   97917       Expr *pExpr = pLower->pExpr->pRight;
   97918       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
   97919     }
   97920     if( rc==SQLITE_OK && pUpper ){
   97921       Expr *pExpr = pUpper->pExpr->pRight;
   97922       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
   97923     }
   97924 
   97925     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
   97926       sqlite3ValueFree(pLowerVal);
   97927       sqlite3ValueFree(pUpperVal);
   97928       goto range_est_fallback;
   97929     }else if( pLowerVal==0 ){
   97930       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
   97931       if( pLower ) iLower = iUpper/2;
   97932     }else if( pUpperVal==0 ){
   97933       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
   97934       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
   97935     }else{
   97936       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
   97937       if( rc==SQLITE_OK ){
   97938         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
   97939       }
   97940     }
   97941 
   97942     iEst = iUpper - iLower;
   97943     testcase( iEst==SQLITE_INDEX_SAMPLES );
   97944     assert( iEst<=SQLITE_INDEX_SAMPLES );
   97945     if( iEst<1 ){
   97946       iEst = 1;
   97947     }
   97948 
   97949     sqlite3ValueFree(pLowerVal);
   97950     sqlite3ValueFree(pUpperVal);
   97951     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
   97952     return rc;
   97953   }
   97954 range_est_fallback:
   97955 #else
   97956   UNUSED_PARAMETER(pParse);
   97957   UNUSED_PARAMETER(p);
   97958   UNUSED_PARAMETER(nEq);
   97959 #endif
   97960   assert( pLower || pUpper );
   97961   if( pLower && pUpper ){
   97962     *piEst = 11;
   97963   }else{
   97964     *piEst = 33;
   97965   }
   97966   return rc;
   97967 }
   97968 
   97969 
   97970 /*
   97971 ** Find the query plan for accessing a particular table.  Write the
   97972 ** best query plan and its cost into the WhereCost object supplied as the
   97973 ** last parameter.
   97974 **
   97975 ** The lowest cost plan wins.  The cost is an estimate of the amount of
   97976 ** CPU and disk I/O need to process the request using the selected plan.
   97977 ** Factors that influence cost include:
   97978 **
   97979 **    *  The estimated number of rows that will be retrieved.  (The
   97980 **       fewer the better.)
   97981 **
   97982 **    *  Whether or not sorting must occur.
   97983 **
   97984 **    *  Whether or not there must be separate lookups in the
   97985 **       index and in the main table.
   97986 **
   97987 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
   97988 ** the SQL statement, then this function only considers plans using the
   97989 ** named index. If no such plan is found, then the returned cost is
   97990 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
   97991 ** then the cost is calculated in the usual way.
   97992 **
   97993 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
   97994 ** in the SELECT statement, then no indexes are considered. However, the
   97995 ** selected plan may still take advantage of the tables built-in rowid
   97996 ** index.
   97997 */
   97998 static void bestBtreeIndex(
   97999   Parse *pParse,              /* The parsing context */
   98000   WhereClause *pWC,           /* The WHERE clause */
   98001   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   98002   Bitmask notReady,           /* Mask of cursors not available for indexing */
   98003   Bitmask notValid,           /* Cursors not available for any purpose */
   98004   ExprList *pOrderBy,         /* The ORDER BY clause */
   98005   WhereCost *pCost            /* Lowest cost query plan */
   98006 ){
   98007   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
   98008   Index *pProbe;              /* An index we are evaluating */
   98009   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
   98010   int eqTermMask;             /* Current mask of valid equality operators */
   98011   int idxEqTermMask;          /* Index mask of valid equality operators */
   98012   Index sPk;                  /* A fake index object for the primary key */
   98013   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
   98014   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
   98015   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
   98016 
   98017   /* Initialize the cost to a worst-case value */
   98018   memset(pCost, 0, sizeof(*pCost));
   98019   pCost->rCost = SQLITE_BIG_DBL;
   98020 
   98021   /* If the pSrc table is the right table of a LEFT JOIN then we may not
   98022   ** use an index to satisfy IS NULL constraints on that table.  This is
   98023   ** because columns might end up being NULL if the table does not match -
   98024   ** a circumstance which the index cannot help us discover.  Ticket #2177.
   98025   */
   98026   if( pSrc->jointype & JT_LEFT ){
   98027     idxEqTermMask = WO_EQ|WO_IN;
   98028   }else{
   98029     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
   98030   }
   98031 
   98032   if( pSrc->pIndex ){
   98033     /* An INDEXED BY clause specifies a particular index to use */
   98034     pIdx = pProbe = pSrc->pIndex;
   98035     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   98036     eqTermMask = idxEqTermMask;
   98037   }else{
   98038     /* There is no INDEXED BY clause.  Create a fake Index object to
   98039     ** represent the primary key */
   98040     Index *pFirst;                /* Any other index on the table */
   98041     memset(&sPk, 0, sizeof(Index));
   98042     sPk.nColumn = 1;
   98043     sPk.aiColumn = &aiColumnPk;
   98044     sPk.aiRowEst = aiRowEstPk;
   98045     sPk.onError = OE_Replace;
   98046     sPk.pTable = pSrc->pTab;
   98047     aiRowEstPk[0] = pSrc->pTab->nRowEst;
   98048     aiRowEstPk[1] = 1;
   98049     pFirst = pSrc->pTab->pIndex;
   98050     if( pSrc->notIndexed==0 ){
   98051       sPk.pNext = pFirst;
   98052     }
   98053     pProbe = &sPk;
   98054     wsFlagMask = ~(
   98055         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
   98056     );
   98057     eqTermMask = WO_EQ|WO_IN;
   98058     pIdx = 0;
   98059   }
   98060 
   98061   /* Loop over all indices looking for the best one to use
   98062   */
   98063   for(; pProbe; pIdx=pProbe=pProbe->pNext){
   98064     const unsigned int * const aiRowEst = pProbe->aiRowEst;
   98065     double cost;                /* Cost of using pProbe */
   98066     double nRow;                /* Estimated number of rows in result set */
   98067     int rev;                    /* True to scan in reverse order */
   98068     int wsFlags = 0;
   98069     Bitmask used = 0;
   98070 
   98071     /* The following variables are populated based on the properties of
   98072     ** scan being evaluated. They are then used to determine the expected
   98073     ** cost and number of rows returned.
   98074     **
   98075     **  nEq:
   98076     **    Number of equality terms that can be implemented using the index.
   98077     **
   98078     **  nInMul:
   98079     **    The "in-multiplier". This is an estimate of how many seek operations
   98080     **    SQLite must perform on the index in question. For example, if the
   98081     **    WHERE clause is:
   98082     **
   98083     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
   98084     **
   98085     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
   98086     **    set to 9. Given the same schema and either of the following WHERE
   98087     **    clauses:
   98088     **
   98089     **      WHERE a =  1
   98090     **      WHERE a >= 2
   98091     **
   98092     **    nInMul is set to 1.
   98093     **
   98094     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
   98095     **    the sub-select is assumed to return 25 rows for the purposes of
   98096     **    determining nInMul.
   98097     **
   98098     **  bInEst:
   98099     **    Set to true if there was at least one "x IN (SELECT ...)" term used
   98100     **    in determining the value of nInMul.
   98101     **
   98102     **  estBound:
   98103     **    An estimate on the amount of the table that must be searched.  A
   98104     **    value of 100 means the entire table is searched.  Range constraints
   98105     **    might reduce this to a value less than 100 to indicate that only
   98106     **    a fraction of the table needs searching.  In the absence of
   98107     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
   98108     **    space to 1/3rd its original size.  So an x>? constraint reduces
   98109     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
   98110     **
   98111     **  bSort:
   98112     **    Boolean. True if there is an ORDER BY clause that will require an
   98113     **    external sort (i.e. scanning the index being evaluated will not
   98114     **    correctly order records).
   98115     **
   98116     **  bLookup:
   98117     **    Boolean. True if for each index entry visited a lookup on the
   98118     **    corresponding table b-tree is required. This is always false
   98119     **    for the rowid index. For other indexes, it is true unless all the
   98120     **    columns of the table used by the SELECT statement are present in
   98121     **    the index (such an index is sometimes described as a covering index).
   98122     **    For example, given the index on (a, b), the second of the following
   98123     **    two queries requires table b-tree lookups, but the first does not.
   98124     **
   98125     **             SELECT a, b    FROM tbl WHERE a = 1;
   98126     **             SELECT a, b, c FROM tbl WHERE a = 1;
   98127     */
   98128     int nEq;
   98129     int bInEst = 0;
   98130     int nInMul = 1;
   98131     int estBound = 100;
   98132     int nBound = 0;             /* Number of range constraints seen */
   98133     int bSort = 0;
   98134     int bLookup = 0;
   98135     WhereTerm *pTerm;           /* A single term of the WHERE clause */
   98136 
   98137     /* Determine the values of nEq and nInMul */
   98138     for(nEq=0; nEq<pProbe->nColumn; nEq++){
   98139       int j = pProbe->aiColumn[nEq];
   98140       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
   98141       if( pTerm==0 ) break;
   98142       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
   98143       if( pTerm->eOperator & WO_IN ){
   98144         Expr *pExpr = pTerm->pExpr;
   98145         wsFlags |= WHERE_COLUMN_IN;
   98146         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   98147           nInMul *= 25;
   98148           bInEst = 1;
   98149         }else if( ALWAYS(pExpr->x.pList) ){
   98150           nInMul *= pExpr->x.pList->nExpr + 1;
   98151         }
   98152       }else if( pTerm->eOperator & WO_ISNULL ){
   98153         wsFlags |= WHERE_COLUMN_NULL;
   98154       }
   98155       used |= pTerm->prereqRight;
   98156     }
   98157 
   98158     /* Determine the value of estBound. */
   98159     if( nEq<pProbe->nColumn ){
   98160       int j = pProbe->aiColumn[nEq];
   98161       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
   98162         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
   98163         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
   98164         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
   98165         if( pTop ){
   98166           nBound = 1;
   98167           wsFlags |= WHERE_TOP_LIMIT;
   98168           used |= pTop->prereqRight;
   98169         }
   98170         if( pBtm ){
   98171           nBound++;
   98172           wsFlags |= WHERE_BTM_LIMIT;
   98173           used |= pBtm->prereqRight;
   98174         }
   98175         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
   98176       }
   98177     }else if( pProbe->onError!=OE_None ){
   98178       testcase( wsFlags & WHERE_COLUMN_IN );
   98179       testcase( wsFlags & WHERE_COLUMN_NULL );
   98180       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
   98181         wsFlags |= WHERE_UNIQUE;
   98182       }
   98183     }
   98184 
   98185     /* If there is an ORDER BY clause and the index being considered will
   98186     ** naturally scan rows in the required order, set the appropriate flags
   98187     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
   98188     ** will scan rows in a different order, set the bSort variable.  */
   98189     if( pOrderBy ){
   98190       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
   98191         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
   98192       ){
   98193         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
   98194         wsFlags |= (rev ? WHERE_REVERSE : 0);
   98195       }else{
   98196         bSort = 1;
   98197       }
   98198     }
   98199 
   98200     /* If currently calculating the cost of using an index (not the IPK
   98201     ** index), determine if all required column data may be obtained without
   98202     ** using the main table (i.e. if the index is a covering
   98203     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
   98204     ** wsFlags. Otherwise, set the bLookup variable to true.  */
   98205     if( pIdx && wsFlags ){
   98206       Bitmask m = pSrc->colUsed;
   98207       int j;
   98208       for(j=0; j<pIdx->nColumn; j++){
   98209         int x = pIdx->aiColumn[j];
   98210         if( x<BMS-1 ){
   98211           m &= ~(((Bitmask)1)<<x);
   98212         }
   98213       }
   98214       if( m==0 ){
   98215         wsFlags |= WHERE_IDX_ONLY;
   98216       }else{
   98217         bLookup = 1;
   98218       }
   98219     }
   98220 
   98221     /*
   98222     ** Estimate the number of rows of output.  For an IN operator,
   98223     ** do not let the estimate exceed half the rows in the table.
   98224     */
   98225     nRow = (double)(aiRowEst[nEq] * nInMul);
   98226     if( bInEst && nRow*2>aiRowEst[0] ){
   98227       nRow = aiRowEst[0]/2;
   98228       nInMul = (int)(nRow / aiRowEst[nEq]);
   98229     }
   98230 
   98231     /* Assume constant cost to access a row and logarithmic cost to
   98232     ** do a binary search.  Hence, the initial cost is the number of output
   98233     ** rows plus log2(table-size) times the number of binary searches.
   98234     */
   98235     cost = nRow + nInMul*estLog(aiRowEst[0]);
   98236 
   98237     /* Adjust the number of rows and the cost downward to reflect rows
   98238     ** that are excluded by range constraints.
   98239     */
   98240     nRow = (nRow * (double)estBound) / (double)100;
   98241     cost = (cost * (double)estBound) / (double)100;
   98242 
   98243     /* Add in the estimated cost of sorting the result
   98244     */
   98245     if( bSort ){
   98246       cost += cost*estLog(cost);
   98247     }
   98248 
   98249     /* If all information can be taken directly from the index, we avoid
   98250     ** doing table lookups.  This reduces the cost by half.  (Not really -
   98251     ** this needs to be fixed.)
   98252     */
   98253     if( pIdx && bLookup==0 ){
   98254       cost /= (double)2;
   98255     }
   98256     /**** Cost of using this index has now been computed ****/
   98257 
   98258     /* If there are additional constraints on this table that cannot
   98259     ** be used with the current index, but which might lower the number
   98260     ** of output rows, adjust the nRow value accordingly.  This only
   98261     ** matters if the current index is the least costly, so do not bother
   98262     ** with this step if we already know this index will not be chosen.
   98263     ** Also, never reduce the output row count below 2 using this step.
   98264     **
   98265     ** It is critical that the notValid mask be used here instead of
   98266     ** the notReady mask.  When computing an "optimal" index, the notReady
   98267     ** mask will only have one bit set - the bit for the current table.
   98268     ** The notValid mask, on the other hand, always has all bits set for
   98269     ** tables that are not in outer loops.  If notReady is used here instead
   98270     ** of notValid, then a optimal index that depends on inner joins loops
   98271     ** might be selected even when there exists an optimal index that has
   98272     ** no such dependency.
   98273     */
   98274     if( nRow>2 && cost<=pCost->rCost ){
   98275       int k;                       /* Loop counter */
   98276       int nSkipEq = nEq;           /* Number of == constraints to skip */
   98277       int nSkipRange = nBound;     /* Number of < constraints to skip */
   98278       Bitmask thisTab;             /* Bitmap for pSrc */
   98279 
   98280       thisTab = getMask(pWC->pMaskSet, iCur);
   98281       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
   98282         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
   98283         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
   98284         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
   98285           if( nSkipEq ){
   98286             /* Ignore the first nEq equality matches since the index
   98287             ** has already accounted for these */
   98288             nSkipEq--;
   98289           }else{
   98290             /* Assume each additional equality match reduces the result
   98291             ** set size by a factor of 10 */
   98292             nRow /= 10;
   98293           }
   98294         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
   98295           if( nSkipRange ){
   98296             /* Ignore the first nBound range constraints since the index
   98297             ** has already accounted for these */
   98298             nSkipRange--;
   98299           }else{
   98300             /* Assume each additional range constraint reduces the result
   98301             ** set size by a factor of 3 */
   98302             nRow /= 3;
   98303           }
   98304         }else{
   98305           /* Any other expression lowers the output row count by half */
   98306           nRow /= 2;
   98307         }
   98308       }
   98309       if( nRow<2 ) nRow = 2;
   98310     }
   98311 
   98312 
   98313     WHERETRACE((
   98314       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
   98315       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
   98316       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
   98317       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
   98318       notReady, nRow, cost, used
   98319     ));
   98320 
   98321     /* If this index is the best we have seen so far, then record this
   98322     ** index and its cost in the pCost structure.
   98323     */
   98324     if( (!pIdx || wsFlags)
   98325      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
   98326     ){
   98327       pCost->rCost = cost;
   98328       pCost->used = used;
   98329       pCost->plan.nRow = nRow;
   98330       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
   98331       pCost->plan.nEq = nEq;
   98332       pCost->plan.u.pIdx = pIdx;
   98333     }
   98334 
   98335     /* If there was an INDEXED BY clause, then only that one index is
   98336     ** considered. */
   98337     if( pSrc->pIndex ) break;
   98338 
   98339     /* Reset masks for the next index in the loop */
   98340     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
   98341     eqTermMask = idxEqTermMask;
   98342   }
   98343 
   98344   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
   98345   ** is set, then reverse the order that the index will be scanned
   98346   ** in. This is used for application testing, to help find cases
   98347   ** where application behaviour depends on the (undefined) order that
   98348   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
   98349   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
   98350     pCost->plan.wsFlags |= WHERE_REVERSE;
   98351   }
   98352 
   98353   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
   98354   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
   98355   assert( pSrc->pIndex==0
   98356        || pCost->plan.u.pIdx==0
   98357        || pCost->plan.u.pIdx==pSrc->pIndex
   98358   );
   98359 
   98360   WHERETRACE(("best index is: %s\n",
   98361     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
   98362          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
   98363   ));
   98364 
   98365   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   98366   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
   98367   pCost->plan.wsFlags |= eqTermMask;
   98368 }
   98369 
   98370 /*
   98371 ** Find the query plan for accessing table pSrc->pTab. Write the
   98372 ** best query plan and its cost into the WhereCost object supplied
   98373 ** as the last parameter. This function may calculate the cost of
   98374 ** both real and virtual table scans.
   98375 */
   98376 static void bestIndex(
   98377   Parse *pParse,              /* The parsing context */
   98378   WhereClause *pWC,           /* The WHERE clause */
   98379   struct SrcList_item *pSrc,  /* The FROM clause term to search */
   98380   Bitmask notReady,           /* Mask of cursors not available for indexing */
   98381   Bitmask notValid,           /* Cursors not available for any purpose */
   98382   ExprList *pOrderBy,         /* The ORDER BY clause */
   98383   WhereCost *pCost            /* Lowest cost query plan */
   98384 ){
   98385 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98386   if( IsVirtual(pSrc->pTab) ){
   98387     sqlite3_index_info *p = 0;
   98388     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
   98389     if( p->needToFreeIdxStr ){
   98390       sqlite3_free(p->idxStr);
   98391     }
   98392     sqlite3DbFree(pParse->db, p);
   98393   }else
   98394 #endif
   98395   {
   98396     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
   98397   }
   98398 }
   98399 
   98400 /*
   98401 ** Disable a term in the WHERE clause.  Except, do not disable the term
   98402 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
   98403 ** or USING clause of that join.
   98404 **
   98405 ** Consider the term t2.z='ok' in the following queries:
   98406 **
   98407 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
   98408 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
   98409 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
   98410 **
   98411 ** The t2.z='ok' is disabled in the in (2) because it originates
   98412 ** in the ON clause.  The term is disabled in (3) because it is not part
   98413 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
   98414 **
   98415 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
   98416 ** completely satisfied by indices.
   98417 **
   98418 ** Disabling a term causes that term to not be tested in the inner loop
   98419 ** of the join.  Disabling is an optimization.  When terms are satisfied
   98420 ** by indices, we disable them to prevent redundant tests in the inner
   98421 ** loop.  We would get the correct results if nothing were ever disabled,
   98422 ** but joins might run a little slower.  The trick is to disable as much
   98423 ** as we can without disabling too much.  If we disabled in (1), we'd get
   98424 ** the wrong answer.  See ticket #813.
   98425 */
   98426 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
   98427   if( pTerm
   98428       && (pTerm->wtFlags & TERM_CODED)==0
   98429       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
   98430   ){
   98431     pTerm->wtFlags |= TERM_CODED;
   98432     if( pTerm->iParent>=0 ){
   98433       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
   98434       if( (--pOther->nChild)==0 ){
   98435         disableTerm(pLevel, pOther);
   98436       }
   98437     }
   98438   }
   98439 }
   98440 
   98441 /*
   98442 ** Code an OP_Affinity opcode to apply the column affinity string zAff
   98443 ** to the n registers starting at base.
   98444 **
   98445 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
   98446 ** beginning and end of zAff are ignored.  If all entries in zAff are
   98447 ** SQLITE_AFF_NONE, then no code gets generated.
   98448 **
   98449 ** This routine makes its own copy of zAff so that the caller is free
   98450 ** to modify zAff after this routine returns.
   98451 */
   98452 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
   98453   Vdbe *v = pParse->pVdbe;
   98454   if( zAff==0 ){
   98455     assert( pParse->db->mallocFailed );
   98456     return;
   98457   }
   98458   assert( v!=0 );
   98459 
   98460   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
   98461   ** and end of the affinity string.
   98462   */
   98463   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
   98464     n--;
   98465     base++;
   98466     zAff++;
   98467   }
   98468   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
   98469     n--;
   98470   }
   98471 
   98472   /* Code the OP_Affinity opcode if there is anything left to do. */
   98473   if( n>0 ){
   98474     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
   98475     sqlite3VdbeChangeP4(v, -1, zAff, n);
   98476     sqlite3ExprCacheAffinityChange(pParse, base, n);
   98477   }
   98478 }
   98479 
   98480 
   98481 /*
   98482 ** Generate code for a single equality term of the WHERE clause.  An equality
   98483 ** term can be either X=expr or X IN (...).   pTerm is the term to be
   98484 ** coded.
   98485 **
   98486 ** The current value for the constraint is left in register iReg.
   98487 **
   98488 ** For a constraint of the form X=expr, the expression is evaluated and its
   98489 ** result is left on the stack.  For constraints of the form X IN (...)
   98490 ** this routine sets up a loop that will iterate over all values of X.
   98491 */
   98492 static int codeEqualityTerm(
   98493   Parse *pParse,      /* The parsing context */
   98494   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
   98495   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
   98496   int iTarget         /* Attempt to leave results in this register */
   98497 ){
   98498   Expr *pX = pTerm->pExpr;
   98499   Vdbe *v = pParse->pVdbe;
   98500   int iReg;                  /* Register holding results */
   98501 
   98502   assert( iTarget>0 );
   98503   if( pX->op==TK_EQ ){
   98504     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
   98505   }else if( pX->op==TK_ISNULL ){
   98506     iReg = iTarget;
   98507     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
   98508 #ifndef SQLITE_OMIT_SUBQUERY
   98509   }else{
   98510     int eType;
   98511     int iTab;
   98512     struct InLoop *pIn;
   98513 
   98514     assert( pX->op==TK_IN );
   98515     iReg = iTarget;
   98516     eType = sqlite3FindInIndex(pParse, pX, 0);
   98517     iTab = pX->iTable;
   98518     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
   98519     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
   98520     if( pLevel->u.in.nIn==0 ){
   98521       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   98522     }
   98523     pLevel->u.in.nIn++;
   98524     pLevel->u.in.aInLoop =
   98525        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
   98526                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
   98527     pIn = pLevel->u.in.aInLoop;
   98528     if( pIn ){
   98529       pIn += pLevel->u.in.nIn - 1;
   98530       pIn->iCur = iTab;
   98531       if( eType==IN_INDEX_ROWID ){
   98532         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
   98533       }else{
   98534         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
   98535       }
   98536       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
   98537     }else{
   98538       pLevel->u.in.nIn = 0;
   98539     }
   98540 #endif
   98541   }
   98542   disableTerm(pLevel, pTerm);
   98543   return iReg;
   98544 }
   98545 
   98546 /*
   98547 ** Generate code that will evaluate all == and IN constraints for an
   98548 ** index.
   98549 **
   98550 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
   98551 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
   98552 ** The index has as many as three equality constraints, but in this
   98553 ** example, the third "c" value is an inequality.  So only two
   98554 ** constraints are coded.  This routine will generate code to evaluate
   98555 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
   98556 ** in consecutive registers and the index of the first register is returned.
   98557 **
   98558 ** In the example above nEq==2.  But this subroutine works for any value
   98559 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
   98560 ** The only thing it does is allocate the pLevel->iMem memory cell and
   98561 ** compute the affinity string.
   98562 **
   98563 ** This routine always allocates at least one memory cell and returns
   98564 ** the index of that memory cell. The code that
   98565 ** calls this routine will use that memory cell to store the termination
   98566 ** key value of the loop.  If one or more IN operators appear, then
   98567 ** this routine allocates an additional nEq memory cells for internal
   98568 ** use.
   98569 **
   98570 ** Before returning, *pzAff is set to point to a buffer containing a
   98571 ** copy of the column affinity string of the index allocated using
   98572 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
   98573 ** with equality constraints that use NONE affinity are set to
   98574 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
   98575 **
   98576 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
   98577 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
   98578 **
   98579 ** In the example above, the index on t1(a) has TEXT affinity. But since
   98580 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
   98581 ** no conversion should be attempted before using a t2.b value as part of
   98582 ** a key to search the index. Hence the first byte in the returned affinity
   98583 ** string in this example would be set to SQLITE_AFF_NONE.
   98584 */
   98585 static int codeAllEqualityTerms(
   98586   Parse *pParse,        /* Parsing context */
   98587   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
   98588   WhereClause *pWC,     /* The WHERE clause */
   98589   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
   98590   int nExtraReg,        /* Number of extra registers to allocate */
   98591   char **pzAff          /* OUT: Set to point to affinity string */
   98592 ){
   98593   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
   98594   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
   98595   Index *pIdx;                  /* The index being used for this loop */
   98596   int iCur = pLevel->iTabCur;   /* The cursor of the table */
   98597   WhereTerm *pTerm;             /* A single constraint term */
   98598   int j;                        /* Loop counter */
   98599   int regBase;                  /* Base register */
   98600   int nReg;                     /* Number of registers to allocate */
   98601   char *zAff;                   /* Affinity string to return */
   98602 
   98603   /* This module is only called on query plans that use an index. */
   98604   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
   98605   pIdx = pLevel->plan.u.pIdx;
   98606 
   98607   /* Figure out how many memory cells we will need then allocate them.
   98608   */
   98609   regBase = pParse->nMem + 1;
   98610   nReg = pLevel->plan.nEq + nExtraReg;
   98611   pParse->nMem += nReg;
   98612 
   98613   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
   98614   if( !zAff ){
   98615     pParse->db->mallocFailed = 1;
   98616   }
   98617 
   98618   /* Evaluate the equality constraints
   98619   */
   98620   assert( pIdx->nColumn>=nEq );
   98621   for(j=0; j<nEq; j++){
   98622     int r1;
   98623     int k = pIdx->aiColumn[j];
   98624     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
   98625     if( NEVER(pTerm==0) ) break;
   98626     /* The following true for indices with redundant columns.
   98627     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
   98628     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
   98629     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   98630     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
   98631     if( r1!=regBase+j ){
   98632       if( nReg==1 ){
   98633         sqlite3ReleaseTempReg(pParse, regBase);
   98634         regBase = r1;
   98635       }else{
   98636         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
   98637       }
   98638     }
   98639     testcase( pTerm->eOperator & WO_ISNULL );
   98640     testcase( pTerm->eOperator & WO_IN );
   98641     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
   98642       Expr *pRight = pTerm->pExpr->pRight;
   98643       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
   98644       if( zAff ){
   98645         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
   98646           zAff[j] = SQLITE_AFF_NONE;
   98647         }
   98648         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
   98649           zAff[j] = SQLITE_AFF_NONE;
   98650         }
   98651       }
   98652     }
   98653   }
   98654   *pzAff = zAff;
   98655   return regBase;
   98656 }
   98657 
   98658 #ifndef SQLITE_OMIT_EXPLAIN
   98659 /*
   98660 ** This routine is a helper for explainIndexRange() below
   98661 **
   98662 ** pStr holds the text of an expression that we are building up one term
   98663 ** at a time.  This routine adds a new term to the end of the expression.
   98664 ** Terms are separated by AND so add the "AND" text for second and subsequent
   98665 ** terms only.
   98666 */
   98667 static void explainAppendTerm(
   98668   StrAccum *pStr,             /* The text expression being built */
   98669   int iTerm,                  /* Index of this term.  First is zero */
   98670   const char *zColumn,        /* Name of the column */
   98671   const char *zOp             /* Name of the operator */
   98672 ){
   98673   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
   98674   sqlite3StrAccumAppend(pStr, zColumn, -1);
   98675   sqlite3StrAccumAppend(pStr, zOp, 1);
   98676   sqlite3StrAccumAppend(pStr, "?", 1);
   98677 }
   98678 
   98679 /*
   98680 ** Argument pLevel describes a strategy for scanning table pTab. This
   98681 ** function returns a pointer to a string buffer containing a description
   98682 ** of the subset of table rows scanned by the strategy in the form of an
   98683 ** SQL expression. Or, if all rows are scanned, NULL is returned.
   98684 **
   98685 ** For example, if the query:
   98686 **
   98687 **   SELECT * FROM t1 WHERE a=1 AND b>2;
   98688 **
   98689 ** is run and there is an index on (a, b), then this function returns a
   98690 ** string similar to:
   98691 **
   98692 **   "a=? AND b>?"
   98693 **
   98694 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
   98695 ** It is the responsibility of the caller to free the buffer when it is
   98696 ** no longer required.
   98697 */
   98698 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
   98699   WherePlan *pPlan = &pLevel->plan;
   98700   Index *pIndex = pPlan->u.pIdx;
   98701   int nEq = pPlan->nEq;
   98702   int i, j;
   98703   Column *aCol = pTab->aCol;
   98704   int *aiColumn = pIndex->aiColumn;
   98705   StrAccum txt;
   98706 
   98707   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
   98708     return 0;
   98709   }
   98710   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
   98711   txt.db = db;
   98712   sqlite3StrAccumAppend(&txt, " (", 2);
   98713   for(i=0; i<nEq; i++){
   98714     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
   98715   }
   98716 
   98717   j = i;
   98718   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
   98719     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
   98720   }
   98721   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
   98722     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
   98723   }
   98724   sqlite3StrAccumAppend(&txt, ")", 1);
   98725   return sqlite3StrAccumFinish(&txt);
   98726 }
   98727 
   98728 /*
   98729 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
   98730 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
   98731 ** record is added to the output to describe the table scan strategy in
   98732 ** pLevel.
   98733 */
   98734 static void explainOneScan(
   98735   Parse *pParse,                  /* Parse context */
   98736   SrcList *pTabList,              /* Table list this loop refers to */
   98737   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
   98738   int iLevel,                     /* Value for "level" column of output */
   98739   int iFrom,                      /* Value for "from" column of output */
   98740   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
   98741 ){
   98742   if( pParse->explain==2 ){
   98743     u32 flags = pLevel->plan.wsFlags;
   98744     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
   98745     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
   98746     sqlite3 *db = pParse->db;     /* Database handle */
   98747     char *zMsg;                   /* Text to add to EQP output */
   98748     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
   98749     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
   98750     int isSearch;                 /* True for a SEARCH. False for SCAN. */
   98751 
   98752     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
   98753 
   98754     isSearch = (pLevel->plan.nEq>0)
   98755              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
   98756              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
   98757 
   98758     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
   98759     if( pItem->pSelect ){
   98760       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
   98761     }else{
   98762       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
   98763     }
   98764 
   98765     if( pItem->zAlias ){
   98766       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
   98767     }
   98768     if( (flags & WHERE_INDEXED)!=0 ){
   98769       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
   98770       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
   98771           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
   98772           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
   98773           ((flags & WHERE_TEMP_INDEX)?"":" "),
   98774           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
   98775           zWhere
   98776       );
   98777       sqlite3DbFree(db, zWhere);
   98778     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   98779       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
   98780 
   98781       if( flags&WHERE_ROWID_EQ ){
   98782         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
   98783       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
   98784         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
   98785       }else if( flags&WHERE_BTM_LIMIT ){
   98786         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
   98787       }else if( flags&WHERE_TOP_LIMIT ){
   98788         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
   98789       }
   98790     }
   98791 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98792     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
   98793       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   98794       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
   98795                   pVtabIdx->idxNum, pVtabIdx->idxStr);
   98796     }
   98797 #endif
   98798     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
   98799       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
   98800       nRow = 1;
   98801     }else{
   98802       nRow = (sqlite3_int64)pLevel->plan.nRow;
   98803     }
   98804     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
   98805     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
   98806   }
   98807 }
   98808 #else
   98809 # define explainOneScan(u,v,w,x,y,z)
   98810 #endif /* SQLITE_OMIT_EXPLAIN */
   98811 
   98812 
   98813 /*
   98814 ** Generate code for the start of the iLevel-th loop in the WHERE clause
   98815 ** implementation described by pWInfo.
   98816 */
   98817 static Bitmask codeOneLoopStart(
   98818   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
   98819   int iLevel,          /* Which level of pWInfo->a[] should be coded */
   98820   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
   98821   Bitmask notReady     /* Which tables are currently available */
   98822 ){
   98823   int j, k;            /* Loop counters */
   98824   int iCur;            /* The VDBE cursor for the table */
   98825   int addrNxt;         /* Where to jump to continue with the next IN case */
   98826   int omitTable;       /* True if we use the index only */
   98827   int bRev;            /* True if we need to scan in reverse order */
   98828   WhereLevel *pLevel;  /* The where level to be coded */
   98829   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
   98830   WhereTerm *pTerm;               /* A WHERE clause term */
   98831   Parse *pParse;                  /* Parsing context */
   98832   Vdbe *v;                        /* The prepared stmt under constructions */
   98833   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
   98834   int addrBrk;                    /* Jump here to break out of the loop */
   98835   int addrCont;                   /* Jump here to continue with next cycle */
   98836   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
   98837   int iReleaseReg = 0;      /* Temp register to free before returning */
   98838 
   98839   pParse = pWInfo->pParse;
   98840   v = pParse->pVdbe;
   98841   pWC = pWInfo->pWC;
   98842   pLevel = &pWInfo->a[iLevel];
   98843   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
   98844   iCur = pTabItem->iCursor;
   98845   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
   98846   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
   98847            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
   98848 
   98849   /* Create labels for the "break" and "continue" instructions
   98850   ** for the current loop.  Jump to addrBrk to break out of a loop.
   98851   ** Jump to cont to go immediately to the next iteration of the
   98852   ** loop.
   98853   **
   98854   ** When there is an IN operator, we also have a "addrNxt" label that
   98855   ** means to continue with the next IN value combination.  When
   98856   ** there are no IN operators in the constraints, the "addrNxt" label
   98857   ** is the same as "addrBrk".
   98858   */
   98859   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
   98860   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
   98861 
   98862   /* If this is the right table of a LEFT OUTER JOIN, allocate and
   98863   ** initialize a memory cell that records if this table matches any
   98864   ** row of the left table of the join.
   98865   */
   98866   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
   98867     pLevel->iLeftJoin = ++pParse->nMem;
   98868     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
   98869     VdbeComment((v, "init LEFT JOIN no-match flag"));
   98870   }
   98871 
   98872 #ifndef SQLITE_OMIT_VIRTUALTABLE
   98873   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   98874     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
   98875     **          to access the data.
   98876     */
   98877     int iReg;   /* P3 Value for OP_VFilter */
   98878     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
   98879     int nConstraint = pVtabIdx->nConstraint;
   98880     struct sqlite3_index_constraint_usage *aUsage =
   98881                                                 pVtabIdx->aConstraintUsage;
   98882     const struct sqlite3_index_constraint *aConstraint =
   98883                                                 pVtabIdx->aConstraint;
   98884 
   98885     sqlite3ExprCachePush(pParse);
   98886     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
   98887     for(j=1; j<=nConstraint; j++){
   98888       for(k=0; k<nConstraint; k++){
   98889         if( aUsage[k].argvIndex==j ){
   98890           int iTerm = aConstraint[k].iTermOffset;
   98891           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
   98892           break;
   98893         }
   98894       }
   98895       if( k==nConstraint ) break;
   98896     }
   98897     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
   98898     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
   98899     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
   98900                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
   98901     pVtabIdx->needToFreeIdxStr = 0;
   98902     for(j=0; j<nConstraint; j++){
   98903       if( aUsage[j].omit ){
   98904         int iTerm = aConstraint[j].iTermOffset;
   98905         disableTerm(pLevel, &pWC->a[iTerm]);
   98906       }
   98907     }
   98908     pLevel->op = OP_VNext;
   98909     pLevel->p1 = iCur;
   98910     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   98911     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
   98912     sqlite3ExprCachePop(pParse, 1);
   98913   }else
   98914 #endif /* SQLITE_OMIT_VIRTUALTABLE */
   98915 
   98916   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
   98917     /* Case 1:  We can directly reference a single row using an
   98918     **          equality comparison against the ROWID field.  Or
   98919     **          we reference multiple rows using a "rowid IN (...)"
   98920     **          construct.
   98921     */
   98922     iReleaseReg = sqlite3GetTempReg(pParse);
   98923     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
   98924     assert( pTerm!=0 );
   98925     assert( pTerm->pExpr!=0 );
   98926     assert( pTerm->leftCursor==iCur );
   98927     assert( omitTable==0 );
   98928     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   98929     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
   98930     addrNxt = pLevel->addrNxt;
   98931     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
   98932     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
   98933     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   98934     VdbeComment((v, "pk"));
   98935     pLevel->op = OP_Noop;
   98936   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
   98937     /* Case 2:  We have an inequality comparison against the ROWID field.
   98938     */
   98939     int testOp = OP_Noop;
   98940     int start;
   98941     int memEndValue = 0;
   98942     WhereTerm *pStart, *pEnd;
   98943 
   98944     assert( omitTable==0 );
   98945     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
   98946     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
   98947     if( bRev ){
   98948       pTerm = pStart;
   98949       pStart = pEnd;
   98950       pEnd = pTerm;
   98951     }
   98952     if( pStart ){
   98953       Expr *pX;             /* The expression that defines the start bound */
   98954       int r1, rTemp;        /* Registers for holding the start boundary */
   98955 
   98956       /* The following constant maps TK_xx codes into corresponding
   98957       ** seek opcodes.  It depends on a particular ordering of TK_xx
   98958       */
   98959       const u8 aMoveOp[] = {
   98960            /* TK_GT */  OP_SeekGt,
   98961            /* TK_LE */  OP_SeekLe,
   98962            /* TK_LT */  OP_SeekLt,
   98963            /* TK_GE */  OP_SeekGe
   98964       };
   98965       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
   98966       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
   98967       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
   98968 
   98969       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   98970       pX = pStart->pExpr;
   98971       assert( pX!=0 );
   98972       assert( pStart->leftCursor==iCur );
   98973       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
   98974       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
   98975       VdbeComment((v, "pk"));
   98976       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
   98977       sqlite3ReleaseTempReg(pParse, rTemp);
   98978       disableTerm(pLevel, pStart);
   98979     }else{
   98980       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
   98981     }
   98982     if( pEnd ){
   98983       Expr *pX;
   98984       pX = pEnd->pExpr;
   98985       assert( pX!=0 );
   98986       assert( pEnd->leftCursor==iCur );
   98987       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   98988       memEndValue = ++pParse->nMem;
   98989       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
   98990       if( pX->op==TK_LT || pX->op==TK_GT ){
   98991         testOp = bRev ? OP_Le : OP_Ge;
   98992       }else{
   98993         testOp = bRev ? OP_Lt : OP_Gt;
   98994       }
   98995       disableTerm(pLevel, pEnd);
   98996     }
   98997     start = sqlite3VdbeCurrentAddr(v);
   98998     pLevel->op = bRev ? OP_Prev : OP_Next;
   98999     pLevel->p1 = iCur;
   99000     pLevel->p2 = start;
   99001     if( pStart==0 && pEnd==0 ){
   99002       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   99003     }else{
   99004       assert( pLevel->p5==0 );
   99005     }
   99006     if( testOp!=OP_Noop ){
   99007       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   99008       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
   99009       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   99010       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
   99011       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
   99012     }
   99013   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
   99014     /* Case 3: A scan using an index.
   99015     **
   99016     **         The WHERE clause may contain zero or more equality
   99017     **         terms ("==" or "IN" operators) that refer to the N
   99018     **         left-most columns of the index. It may also contain
   99019     **         inequality constraints (>, <, >= or <=) on the indexed
   99020     **         column that immediately follows the N equalities. Only
   99021     **         the right-most column can be an inequality - the rest must
   99022     **         use the "==" and "IN" operators. For example, if the
   99023     **         index is on (x,y,z), then the following clauses are all
   99024     **         optimized:
   99025     **
   99026     **            x=5
   99027     **            x=5 AND y=10
   99028     **            x=5 AND y<10
   99029     **            x=5 AND y>5 AND y<10
   99030     **            x=5 AND y=5 AND z<=10
   99031     **
   99032     **         The z<10 term of the following cannot be used, only
   99033     **         the x=5 term:
   99034     **
   99035     **            x=5 AND z<10
   99036     **
   99037     **         N may be zero if there are inequality constraints.
   99038     **         If there are no inequality constraints, then N is at
   99039     **         least one.
   99040     **
   99041     **         This case is also used when there are no WHERE clause
   99042     **         constraints but an index is selected anyway, in order
   99043     **         to force the output order to conform to an ORDER BY.
   99044     */
   99045     static const u8 aStartOp[] = {
   99046       0,
   99047       0,
   99048       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
   99049       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
   99050       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
   99051       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
   99052       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
   99053       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
   99054     };
   99055     static const u8 aEndOp[] = {
   99056       OP_Noop,             /* 0: (!end_constraints) */
   99057       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
   99058       OP_IdxLT             /* 2: (end_constraints && bRev) */
   99059     };
   99060     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
   99061     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
   99062     int regBase;                 /* Base register holding constraint values */
   99063     int r1;                      /* Temp register */
   99064     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
   99065     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
   99066     int startEq;                 /* True if range start uses ==, >= or <= */
   99067     int endEq;                   /* True if range end uses ==, >= or <= */
   99068     int start_constraints;       /* Start of range is constrained */
   99069     int nConstraint;             /* Number of constraint terms */
   99070     Index *pIdx;                 /* The index we will be using */
   99071     int iIdxCur;                 /* The VDBE cursor for the index */
   99072     int nExtraReg = 0;           /* Number of extra registers needed */
   99073     int op;                      /* Instruction opcode */
   99074     char *zStartAff;             /* Affinity for start of range constraint */
   99075     char *zEndAff;               /* Affinity for end of range constraint */
   99076 
   99077     pIdx = pLevel->plan.u.pIdx;
   99078     iIdxCur = pLevel->iIdxCur;
   99079     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
   99080 
   99081     /* If this loop satisfies a sort order (pOrderBy) request that
   99082     ** was passed to this function to implement a "SELECT min(x) ..."
   99083     ** query, then the caller will only allow the loop to run for
   99084     ** a single iteration. This means that the first row returned
   99085     ** should not have a NULL value stored in 'x'. If column 'x' is
   99086     ** the first one after the nEq equality constraints in the index,
   99087     ** this requires some special handling.
   99088     */
   99089     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
   99090      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
   99091      && (pIdx->nColumn>nEq)
   99092     ){
   99093       /* assert( pOrderBy->nExpr==1 ); */
   99094       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
   99095       isMinQuery = 1;
   99096       nExtraReg = 1;
   99097     }
   99098 
   99099     /* Find any inequality constraint terms for the start and end
   99100     ** of the range.
   99101     */
   99102     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
   99103       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
   99104       nExtraReg = 1;
   99105     }
   99106     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
   99107       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
   99108       nExtraReg = 1;
   99109     }
   99110 
   99111     /* Generate code to evaluate all constraint terms using == or IN
   99112     ** and store the values of those terms in an array of registers
   99113     ** starting at regBase.
   99114     */
   99115     regBase = codeAllEqualityTerms(
   99116         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
   99117     );
   99118     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
   99119     addrNxt = pLevel->addrNxt;
   99120 
   99121     /* If we are doing a reverse order scan on an ascending index, or
   99122     ** a forward order scan on a descending index, interchange the
   99123     ** start and end terms (pRangeStart and pRangeEnd).
   99124     */
   99125     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
   99126       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
   99127     }
   99128 
   99129     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
   99130     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
   99131     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
   99132     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
   99133     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
   99134     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
   99135     start_constraints = pRangeStart || nEq>0;
   99136 
   99137     /* Seek the index cursor to the start of the range. */
   99138     nConstraint = nEq;
   99139     if( pRangeStart ){
   99140       Expr *pRight = pRangeStart->pExpr->pRight;
   99141       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   99142       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   99143       if( zStartAff ){
   99144         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
   99145           /* Since the comparison is to be performed with no conversions
   99146           ** applied to the operands, set the affinity to apply to pRight to
   99147           ** SQLITE_AFF_NONE.  */
   99148           zStartAff[nEq] = SQLITE_AFF_NONE;
   99149         }
   99150         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
   99151           zStartAff[nEq] = SQLITE_AFF_NONE;
   99152         }
   99153       }
   99154       nConstraint++;
   99155       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   99156     }else if( isMinQuery ){
   99157       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
   99158       nConstraint++;
   99159       startEq = 0;
   99160       start_constraints = 1;
   99161     }
   99162     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
   99163     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
   99164     assert( op!=0 );
   99165     testcase( op==OP_Rewind );
   99166     testcase( op==OP_Last );
   99167     testcase( op==OP_SeekGt );
   99168     testcase( op==OP_SeekGe );
   99169     testcase( op==OP_SeekLe );
   99170     testcase( op==OP_SeekLt );
   99171     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   99172 
   99173     /* Load the value for the inequality constraint at the end of the
   99174     ** range (if any).
   99175     */
   99176     nConstraint = nEq;
   99177     if( pRangeEnd ){
   99178       Expr *pRight = pRangeEnd->pExpr->pRight;
   99179       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
   99180       sqlite3ExprCode(pParse, pRight, regBase+nEq);
   99181       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
   99182       if( zEndAff ){
   99183         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
   99184           /* Since the comparison is to be performed with no conversions
   99185           ** applied to the operands, set the affinity to apply to pRight to
   99186           ** SQLITE_AFF_NONE.  */
   99187           zEndAff[nEq] = SQLITE_AFF_NONE;
   99188         }
   99189         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
   99190           zEndAff[nEq] = SQLITE_AFF_NONE;
   99191         }
   99192       }
   99193       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
   99194       nConstraint++;
   99195       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
   99196     }
   99197     sqlite3DbFree(pParse->db, zStartAff);
   99198     sqlite3DbFree(pParse->db, zEndAff);
   99199 
   99200     /* Top of the loop body */
   99201     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
   99202 
   99203     /* Check if the index cursor is past the end of the range. */
   99204     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
   99205     testcase( op==OP_Noop );
   99206     testcase( op==OP_IdxGE );
   99207     testcase( op==OP_IdxLT );
   99208     if( op!=OP_Noop ){
   99209       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
   99210       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
   99211     }
   99212 
   99213     /* If there are inequality constraints, check that the value
   99214     ** of the table column that the inequality contrains is not NULL.
   99215     ** If it is, jump to the next iteration of the loop.
   99216     */
   99217     r1 = sqlite3GetTempReg(pParse);
   99218     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
   99219     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
   99220     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
   99221       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
   99222       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
   99223     }
   99224     sqlite3ReleaseTempReg(pParse, r1);
   99225 
   99226     /* Seek the table cursor, if required */
   99227     disableTerm(pLevel, pRangeStart);
   99228     disableTerm(pLevel, pRangeEnd);
   99229     if( !omitTable ){
   99230       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
   99231       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
   99232       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
   99233       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
   99234     }
   99235 
   99236     /* Record the instruction used to terminate the loop. Disable
   99237     ** WHERE clause terms made redundant by the index range scan.
   99238     */
   99239     pLevel->op = bRev ? OP_Prev : OP_Next;
   99240     pLevel->p1 = iIdxCur;
   99241   }else
   99242 
   99243 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
   99244   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
   99245     /* Case 4:  Two or more separately indexed terms connected by OR
   99246     **
   99247     ** Example:
   99248     **
   99249     **   CREATE TABLE t1(a,b,c,d);
   99250     **   CREATE INDEX i1 ON t1(a);
   99251     **   CREATE INDEX i2 ON t1(b);
   99252     **   CREATE INDEX i3 ON t1(c);
   99253     **
   99254     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
   99255     **
   99256     ** In the example, there are three indexed terms connected by OR.
   99257     ** The top of the loop looks like this:
   99258     **
   99259     **          Null       1                # Zero the rowset in reg 1
   99260     **
   99261     ** Then, for each indexed term, the following. The arguments to
   99262     ** RowSetTest are such that the rowid of the current row is inserted
   99263     ** into the RowSet. If it is already present, control skips the
   99264     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
   99265     **
   99266     **        sqlite3WhereBegin(<term>)
   99267     **          RowSetTest                  # Insert rowid into rowset
   99268     **          Gosub      2 A
   99269     **        sqlite3WhereEnd()
   99270     **
   99271     ** Following the above, code to terminate the loop. Label A, the target
   99272     ** of the Gosub above, jumps to the instruction right after the Goto.
   99273     **
   99274     **          Null       1                # Zero the rowset in reg 1
   99275     **          Goto       B                # The loop is finished.
   99276     **
   99277     **       A: <loop body>                 # Return data, whatever.
   99278     **
   99279     **          Return     2                # Jump back to the Gosub
   99280     **
   99281     **       B: <after the loop>
   99282     **
   99283     */
   99284     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
   99285     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
   99286     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
   99287 
   99288     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
   99289     int regRowset = 0;                        /* Register for RowSet object */
   99290     int regRowid = 0;                         /* Register holding rowid */
   99291     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
   99292     int iRetInit;                             /* Address of regReturn init */
   99293     int untestedTerms = 0;             /* Some terms not completely tested */
   99294     int ii;
   99295 
   99296     pTerm = pLevel->plan.u.pTerm;
   99297     assert( pTerm!=0 );
   99298     assert( pTerm->eOperator==WO_OR );
   99299     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
   99300     pOrWc = &pTerm->u.pOrInfo->wc;
   99301     pFinal = &pOrWc->a[pOrWc->nTerm-1];
   99302     pLevel->op = OP_Return;
   99303     pLevel->p1 = regReturn;
   99304 
   99305     /* Set up a new SrcList ni pOrTab containing the table being scanned
   99306     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
   99307     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
   99308     */
   99309     if( pWInfo->nLevel>1 ){
   99310       int nNotReady;                 /* The number of notReady tables */
   99311       struct SrcList_item *origSrc;     /* Original list of tables */
   99312       nNotReady = pWInfo->nLevel - iLevel - 1;
   99313       pOrTab = sqlite3StackAllocRaw(pParse->db,
   99314                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
   99315       if( pOrTab==0 ) return notReady;
   99316       pOrTab->nAlloc = (i16)(nNotReady + 1);
   99317       pOrTab->nSrc = pOrTab->nAlloc;
   99318       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
   99319       origSrc = pWInfo->pTabList->a;
   99320       for(k=1; k<=nNotReady; k++){
   99321         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
   99322       }
   99323     }else{
   99324       pOrTab = pWInfo->pTabList;
   99325     }
   99326 
   99327     /* Initialize the rowset register to contain NULL. An SQL NULL is
   99328     ** equivalent to an empty rowset.
   99329     **
   99330     ** Also initialize regReturn to contain the address of the instruction
   99331     ** immediately following the OP_Return at the bottom of the loop. This
   99332     ** is required in a few obscure LEFT JOIN cases where control jumps
   99333     ** over the top of the loop into the body of it. In this case the
   99334     ** correct response for the end-of-loop code (the OP_Return) is to
   99335     ** fall through to the next instruction, just as an OP_Next does if
   99336     ** called on an uninitialized cursor.
   99337     */
   99338     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   99339       regRowset = ++pParse->nMem;
   99340       regRowid = ++pParse->nMem;
   99341       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
   99342     }
   99343     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
   99344 
   99345     for(ii=0; ii<pOrWc->nTerm; ii++){
   99346       WhereTerm *pOrTerm = &pOrWc->a[ii];
   99347       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
   99348         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
   99349         /* Loop through table entries that match term pOrTerm. */
   99350         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
   99351                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
   99352                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
   99353         if( pSubWInfo ){
   99354           explainOneScan(
   99355               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
   99356           );
   99357           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
   99358             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
   99359             int r;
   99360             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
   99361                                          regRowid);
   99362             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
   99363                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
   99364           }
   99365           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
   99366 
   99367           /* The pSubWInfo->untestedTerms flag means that this OR term
   99368           ** contained one or more AND term from a notReady table.  The
   99369           ** terms from the notReady table could not be tested and will
   99370           ** need to be tested later.
   99371           */
   99372           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
   99373 
   99374           /* Finish the loop through table entries that match term pOrTerm. */
   99375           sqlite3WhereEnd(pSubWInfo);
   99376         }
   99377       }
   99378     }
   99379     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
   99380     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
   99381     sqlite3VdbeResolveLabel(v, iLoopBody);
   99382 
   99383     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
   99384     if( !untestedTerms ) disableTerm(pLevel, pTerm);
   99385   }else
   99386 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
   99387 
   99388   {
   99389     /* Case 5:  There is no usable index.  We must do a complete
   99390     **          scan of the entire table.
   99391     */
   99392     static const u8 aStep[] = { OP_Next, OP_Prev };
   99393     static const u8 aStart[] = { OP_Rewind, OP_Last };
   99394     assert( bRev==0 || bRev==1 );
   99395     assert( omitTable==0 );
   99396     pLevel->op = aStep[bRev];
   99397     pLevel->p1 = iCur;
   99398     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
   99399     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
   99400   }
   99401   notReady &= ~getMask(pWC->pMaskSet, iCur);
   99402 
   99403   /* Insert code to test every subexpression that can be completely
   99404   ** computed using the current set of tables.
   99405   **
   99406   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
   99407   ** the use of indices become tests that are evaluated against each row of
   99408   ** the relevant input tables.
   99409   */
   99410   k = 0;
   99411   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
   99412     Expr *pE;
   99413     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
   99414     testcase( pTerm->wtFlags & TERM_CODED );
   99415     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   99416     if( (pTerm->prereqAll & notReady)!=0 ){
   99417       testcase( pWInfo->untestedTerms==0
   99418                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
   99419       pWInfo->untestedTerms = 1;
   99420       continue;
   99421     }
   99422     pE = pTerm->pExpr;
   99423     assert( pE!=0 );
   99424     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
   99425       continue;
   99426     }
   99427     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
   99428     k = 1;
   99429     pTerm->wtFlags |= TERM_CODED;
   99430   }
   99431 
   99432   /* For a LEFT OUTER JOIN, generate code that will record the fact that
   99433   ** at least one row of the right table has matched the left table.
   99434   */
   99435   if( pLevel->iLeftJoin ){
   99436     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
   99437     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
   99438     VdbeComment((v, "record LEFT JOIN hit"));
   99439     sqlite3ExprCacheClear(pParse);
   99440     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
   99441       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
   99442       testcase( pTerm->wtFlags & TERM_CODED );
   99443       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
   99444       if( (pTerm->prereqAll & notReady)!=0 ){
   99445         assert( pWInfo->untestedTerms );
   99446         continue;
   99447       }
   99448       assert( pTerm->pExpr );
   99449       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
   99450       pTerm->wtFlags |= TERM_CODED;
   99451     }
   99452   }
   99453   sqlite3ReleaseTempReg(pParse, iReleaseReg);
   99454 
   99455   return notReady;
   99456 }
   99457 
   99458 #if defined(SQLITE_TEST)
   99459 /*
   99460 ** The following variable holds a text description of query plan generated
   99461 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
   99462 ** overwrites the previous.  This information is used for testing and
   99463 ** analysis only.
   99464 */
   99465 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
   99466 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
   99467 
   99468 #endif /* SQLITE_TEST */
   99469 
   99470 
   99471 /*
   99472 ** Free a WhereInfo structure
   99473 */
   99474 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
   99475   if( ALWAYS(pWInfo) ){
   99476     int i;
   99477     for(i=0; i<pWInfo->nLevel; i++){
   99478       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
   99479       if( pInfo ){
   99480         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
   99481         if( pInfo->needToFreeIdxStr ){
   99482           sqlite3_free(pInfo->idxStr);
   99483         }
   99484         sqlite3DbFree(db, pInfo);
   99485       }
   99486       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
   99487         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
   99488         if( pIdx ){
   99489           sqlite3DbFree(db, pIdx->zColAff);
   99490           sqlite3DbFree(db, pIdx);
   99491         }
   99492       }
   99493     }
   99494     whereClauseClear(pWInfo->pWC);
   99495     sqlite3DbFree(db, pWInfo);
   99496   }
   99497 }
   99498 
   99499 
   99500 /*
   99501 ** Generate the beginning of the loop used for WHERE clause processing.
   99502 ** The return value is a pointer to an opaque structure that contains
   99503 ** information needed to terminate the loop.  Later, the calling routine
   99504 ** should invoke sqlite3WhereEnd() with the return value of this function
   99505 ** in order to complete the WHERE clause processing.
   99506 **
   99507 ** If an error occurs, this routine returns NULL.
   99508 **
   99509 ** The basic idea is to do a nested loop, one loop for each table in
   99510 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
   99511 ** same as a SELECT with only a single table in the FROM clause.)  For
   99512 ** example, if the SQL is this:
   99513 **
   99514 **       SELECT * FROM t1, t2, t3 WHERE ...;
   99515 **
   99516 ** Then the code generated is conceptually like the following:
   99517 **
   99518 **      foreach row1 in t1 do       \    Code generated
   99519 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
   99520 **          foreach row3 in t3 do   /
   99521 **            ...
   99522 **          end                     \    Code generated
   99523 **        end                        |-- by sqlite3WhereEnd()
   99524 **      end                         /
   99525 **
   99526 ** Note that the loops might not be nested in the order in which they
   99527 ** appear in the FROM clause if a different order is better able to make
   99528 ** use of indices.  Note also that when the IN operator appears in
   99529 ** the WHERE clause, it might result in additional nested loops for
   99530 ** scanning through all values on the right-hand side of the IN.
   99531 **
   99532 ** There are Btree cursors associated with each table.  t1 uses cursor
   99533 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
   99534 ** And so forth.  This routine generates code to open those VDBE cursors
   99535 ** and sqlite3WhereEnd() generates the code to close them.
   99536 **
   99537 ** The code that sqlite3WhereBegin() generates leaves the cursors named
   99538 ** in pTabList pointing at their appropriate entries.  The [...] code
   99539 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
   99540 ** data from the various tables of the loop.
   99541 **
   99542 ** If the WHERE clause is empty, the foreach loops must each scan their
   99543 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
   99544 ** the tables have indices and there are terms in the WHERE clause that
   99545 ** refer to those indices, a complete table scan can be avoided and the
   99546 ** code will run much faster.  Most of the work of this routine is checking
   99547 ** to see if there are indices that can be used to speed up the loop.
   99548 **
   99549 ** Terms of the WHERE clause are also used to limit which rows actually
   99550 ** make it to the "..." in the middle of the loop.  After each "foreach",
   99551 ** terms of the WHERE clause that use only terms in that loop and outer
   99552 ** loops are evaluated and if false a jump is made around all subsequent
   99553 ** inner loops (or around the "..." if the test occurs within the inner-
   99554 ** most loop)
   99555 **
   99556 ** OUTER JOINS
   99557 **
   99558 ** An outer join of tables t1 and t2 is conceptally coded as follows:
   99559 **
   99560 **    foreach row1 in t1 do
   99561 **      flag = 0
   99562 **      foreach row2 in t2 do
   99563 **        start:
   99564 **          ...
   99565 **          flag = 1
   99566 **      end
   99567 **      if flag==0 then
   99568 **        move the row2 cursor to a null row
   99569 **        goto start
   99570 **      fi
   99571 **    end
   99572 **
   99573 ** ORDER BY CLAUSE PROCESSING
   99574 **
   99575 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
   99576 ** if there is one.  If there is no ORDER BY clause or if this routine
   99577 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
   99578 **
   99579 ** If an index can be used so that the natural output order of the table
   99580 ** scan is correct for the ORDER BY clause, then that index is used and
   99581 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
   99582 ** unnecessary sort of the result set if an index appropriate for the
   99583 ** ORDER BY clause already exists.
   99584 **
   99585 ** If the where clause loops cannot be arranged to provide the correct
   99586 ** output order, then the *ppOrderBy is unchanged.
   99587 */
   99588 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   99589   Parse *pParse,        /* The parser context */
   99590   SrcList *pTabList,    /* A list of all tables to be scanned */
   99591   Expr *pWhere,         /* The WHERE clause */
   99592   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
   99593   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
   99594 ){
   99595   int i;                     /* Loop counter */
   99596   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
   99597   int nTabList;              /* Number of elements in pTabList */
   99598   WhereInfo *pWInfo;         /* Will become the return value of this function */
   99599   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
   99600   Bitmask notReady;          /* Cursors that are not yet positioned */
   99601   WhereMaskSet *pMaskSet;    /* The expression mask set */
   99602   WhereClause *pWC;               /* Decomposition of the WHERE clause */
   99603   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
   99604   WhereLevel *pLevel;             /* A single level in the pWInfo list */
   99605   int iFrom;                      /* First unused FROM clause element */
   99606   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
   99607   sqlite3 *db;               /* Database connection */
   99608 
   99609   /* The number of tables in the FROM clause is limited by the number of
   99610   ** bits in a Bitmask
   99611   */
   99612   testcase( pTabList->nSrc==BMS );
   99613   if( pTabList->nSrc>BMS ){
   99614     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
   99615     return 0;
   99616   }
   99617 
   99618   /* This function normally generates a nested loop for all tables in
   99619   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
   99620   ** only generate code for the first table in pTabList and assume that
   99621   ** any cursors associated with subsequent tables are uninitialized.
   99622   */
   99623   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
   99624 
   99625   /* Allocate and initialize the WhereInfo structure that will become the
   99626   ** return value. A single allocation is used to store the WhereInfo
   99627   ** struct, the contents of WhereInfo.a[], the WhereClause structure
   99628   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
   99629   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
   99630   ** some architectures. Hence the ROUND8() below.
   99631   */
   99632   db = pParse->db;
   99633   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
   99634   pWInfo = sqlite3DbMallocZero(db,
   99635       nByteWInfo +
   99636       sizeof(WhereClause) +
   99637       sizeof(WhereMaskSet)
   99638   );
   99639   if( db->mallocFailed ){
   99640     sqlite3DbFree(db, pWInfo);
   99641     pWInfo = 0;
   99642     goto whereBeginError;
   99643   }
   99644   pWInfo->nLevel = nTabList;
   99645   pWInfo->pParse = pParse;
   99646   pWInfo->pTabList = pTabList;
   99647   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
   99648   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
   99649   pWInfo->wctrlFlags = wctrlFlags;
   99650   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
   99651   pMaskSet = (WhereMaskSet*)&pWC[1];
   99652 
   99653   /* Split the WHERE clause into separate subexpressions where each
   99654   ** subexpression is separated by an AND operator.
   99655   */
   99656   initMaskSet(pMaskSet);
   99657   whereClauseInit(pWC, pParse, pMaskSet);
   99658   sqlite3ExprCodeConstants(pParse, pWhere);
   99659   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
   99660 
   99661   /* Special case: a WHERE clause that is constant.  Evaluate the
   99662   ** expression and either jump over all of the code or fall thru.
   99663   */
   99664   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
   99665     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
   99666     pWhere = 0;
   99667   }
   99668 
   99669   /* Assign a bit from the bitmask to every term in the FROM clause.
   99670   **
   99671   ** When assigning bitmask values to FROM clause cursors, it must be
   99672   ** the case that if X is the bitmask for the N-th FROM clause term then
   99673   ** the bitmask for all FROM clause terms to the left of the N-th term
   99674   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
   99675   ** its Expr.iRightJoinTable value to find the bitmask of the right table
   99676   ** of the join.  Subtracting one from the right table bitmask gives a
   99677   ** bitmask for all tables to the left of the join.  Knowing the bitmask
   99678   ** for all tables to the left of a left join is important.  Ticket #3015.
   99679   **
   99680   ** Configure the WhereClause.vmask variable so that bits that correspond
   99681   ** to virtual table cursors are set. This is used to selectively disable
   99682   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
   99683   ** with virtual tables.
   99684   **
   99685   ** Note that bitmasks are created for all pTabList->nSrc tables in
   99686   ** pTabList, not just the first nTabList tables.  nTabList is normally
   99687   ** equal to pTabList->nSrc but might be shortened to 1 if the
   99688   ** WHERE_ONETABLE_ONLY flag is set.
   99689   */
   99690   assert( pWC->vmask==0 && pMaskSet->n==0 );
   99691   for(i=0; i<pTabList->nSrc; i++){
   99692     createMask(pMaskSet, pTabList->a[i].iCursor);
   99693 #ifndef SQLITE_OMIT_VIRTUALTABLE
   99694     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
   99695       pWC->vmask |= ((Bitmask)1 << i);
   99696     }
   99697 #endif
   99698   }
   99699 #ifndef NDEBUG
   99700   {
   99701     Bitmask toTheLeft = 0;
   99702     for(i=0; i<pTabList->nSrc; i++){
   99703       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
   99704       assert( (m-1)==toTheLeft );
   99705       toTheLeft |= m;
   99706     }
   99707   }
   99708 #endif
   99709 
   99710   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
   99711   ** add new virtual terms onto the end of the WHERE clause.  We do not
   99712   ** want to analyze these virtual terms, so start analyzing at the end
   99713   ** and work forward so that the added virtual terms are never processed.
   99714   */
   99715   exprAnalyzeAll(pTabList, pWC);
   99716   if( db->mallocFailed ){
   99717     goto whereBeginError;
   99718   }
   99719 
   99720   /* Chose the best index to use for each table in the FROM clause.
   99721   **
   99722   ** This loop fills in the following fields:
   99723   **
   99724   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
   99725   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
   99726   **   pWInfo->a[].nEq       The number of == and IN constraints
   99727   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
   99728   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
   99729   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
   99730   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
   99731   **
   99732   ** This loop also figures out the nesting order of tables in the FROM
   99733   ** clause.
   99734   */
   99735   notReady = ~(Bitmask)0;
   99736   pTabItem = pTabList->a;
   99737   pLevel = pWInfo->a;
   99738   andFlags = ~0;
   99739   WHERETRACE(("*** Optimizer Start ***\n"));
   99740   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   99741     WhereCost bestPlan;         /* Most efficient plan seen so far */
   99742     Index *pIdx;                /* Index for FROM table at pTabItem */
   99743     int j;                      /* For looping over FROM tables */
   99744     int bestJ = -1;             /* The value of j */
   99745     Bitmask m;                  /* Bitmask value for j or bestJ */
   99746     int isOptimal;              /* Iterator for optimal/non-optimal search */
   99747     int nUnconstrained;         /* Number tables without INDEXED BY */
   99748     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
   99749 
   99750     memset(&bestPlan, 0, sizeof(bestPlan));
   99751     bestPlan.rCost = SQLITE_BIG_DBL;
   99752     WHERETRACE(("*** Begin search for loop %d ***\n", i));
   99753 
   99754     /* Loop through the remaining entries in the FROM clause to find the
   99755     ** next nested loop. The loop tests all FROM clause entries
   99756     ** either once or twice.
   99757     **
   99758     ** The first test is always performed if there are two or more entries
   99759     ** remaining and never performed if there is only one FROM clause entry
   99760     ** to choose from.  The first test looks for an "optimal" scan.  In
   99761     ** this context an optimal scan is one that uses the same strategy
   99762     ** for the given FROM clause entry as would be selected if the entry
   99763     ** were used as the innermost nested loop.  In other words, a table
   99764     ** is chosen such that the cost of running that table cannot be reduced
   99765     ** by waiting for other tables to run first.  This "optimal" test works
   99766     ** by first assuming that the FROM clause is on the inner loop and finding
   99767     ** its query plan, then checking to see if that query plan uses any
   99768     ** other FROM clause terms that are notReady.  If no notReady terms are
   99769     ** used then the "optimal" query plan works.
   99770     **
   99771     ** Note that the WhereCost.nRow parameter for an optimal scan might
   99772     ** not be as small as it would be if the table really were the innermost
   99773     ** join.  The nRow value can be reduced by WHERE clause constraints
   99774     ** that do not use indices.  But this nRow reduction only happens if the
   99775     ** table really is the innermost join.
   99776     **
   99777     ** The second loop iteration is only performed if no optimal scan
   99778     ** strategies were found by the first iteration. This second iteration
   99779     ** is used to search for the lowest cost scan overall.
   99780     **
   99781     ** Previous versions of SQLite performed only the second iteration -
   99782     ** the next outermost loop was always that with the lowest overall
   99783     ** cost. However, this meant that SQLite could select the wrong plan
   99784     ** for scripts such as the following:
   99785     **
   99786     **   CREATE TABLE t1(a, b);
   99787     **   CREATE TABLE t2(c, d);
   99788     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
   99789     **
   99790     ** The best strategy is to iterate through table t1 first. However it
   99791     ** is not possible to determine this with a simple greedy algorithm.
   99792     ** Since the cost of a linear scan through table t2 is the same
   99793     ** as the cost of a linear scan through table t1, a simple greedy
   99794     ** algorithm may choose to use t2 for the outer loop, which is a much
   99795     ** costlier approach.
   99796     */
   99797     nUnconstrained = 0;
   99798     notIndexed = 0;
   99799     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
   99800       Bitmask mask;             /* Mask of tables not yet ready */
   99801       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
   99802         int doNotReorder;    /* True if this table should not be reordered */
   99803         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
   99804         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
   99805 
   99806         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
   99807         if( j!=iFrom && doNotReorder ) break;
   99808         m = getMask(pMaskSet, pTabItem->iCursor);
   99809         if( (m & notReady)==0 ){
   99810           if( j==iFrom ) iFrom++;
   99811           continue;
   99812         }
   99813         mask = (isOptimal ? m : notReady);
   99814         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
   99815         if( pTabItem->pIndex==0 ) nUnconstrained++;
   99816 
   99817         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
   99818                     j, isOptimal));
   99819         assert( pTabItem->pTab );
   99820 #ifndef SQLITE_OMIT_VIRTUALTABLE
   99821         if( IsVirtual(pTabItem->pTab) ){
   99822           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
   99823           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   99824                            &sCost, pp);
   99825         }else
   99826 #endif
   99827         {
   99828           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
   99829                          &sCost);
   99830         }
   99831         assert( isOptimal || (sCost.used&notReady)==0 );
   99832 
   99833         /* If an INDEXED BY clause is present, then the plan must use that
   99834         ** index if it uses any index at all */
   99835         assert( pTabItem->pIndex==0
   99836                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
   99837                   || sCost.plan.u.pIdx==pTabItem->pIndex );
   99838 
   99839         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
   99840           notIndexed |= m;
   99841         }
   99842 
   99843         /* Conditions under which this table becomes the best so far:
   99844         **
   99845         **   (1) The table must not depend on other tables that have not
   99846         **       yet run.
   99847         **
   99848         **   (2) A full-table-scan plan cannot supercede another plan unless
   99849         **       it is an "optimal" plan as defined above.
   99850         **
   99851         **   (3) All tables have an INDEXED BY clause or this table lacks an
   99852         **       INDEXED BY clause or this table uses the specific
   99853         **       index specified by its INDEXED BY clause.  This rule ensures
   99854         **       that a best-so-far is always selected even if an impossible
   99855         **       combination of INDEXED BY clauses are given.  The error
   99856         **       will be detected and relayed back to the application later.
   99857         **       The NEVER() comes about because rule (2) above prevents
   99858         **       An indexable full-table-scan from reaching rule (3).
   99859         **
   99860         **   (4) The plan cost must be lower than prior plans or else the
   99861         **       cost must be the same and the number of rows must be lower.
   99862         */
   99863         if( (sCost.used&notReady)==0                       /* (1) */
   99864             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
   99865                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
   99866             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
   99867                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
   99868             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
   99869                 || (sCost.rCost<=bestPlan.rCost
   99870                  && sCost.plan.nRow<bestPlan.plan.nRow))
   99871         ){
   99872           WHERETRACE(("=== table %d is best so far"
   99873                       " with cost=%g and nRow=%g\n",
   99874                       j, sCost.rCost, sCost.plan.nRow));
   99875           bestPlan = sCost;
   99876           bestJ = j;
   99877         }
   99878         if( doNotReorder ) break;
   99879       }
   99880     }
   99881     assert( bestJ>=0 );
   99882     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
   99883     WHERETRACE(("*** Optimizer selects table %d for loop %d"
   99884                 " with cost=%g and nRow=%g\n",
   99885                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
   99886     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
   99887       *ppOrderBy = 0;
   99888     }
   99889     andFlags &= bestPlan.plan.wsFlags;
   99890     pLevel->plan = bestPlan.plan;
   99891     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
   99892     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
   99893     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
   99894       pLevel->iIdxCur = pParse->nTab++;
   99895     }else{
   99896       pLevel->iIdxCur = -1;
   99897     }
   99898     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
   99899     pLevel->iFrom = (u8)bestJ;
   99900     if( bestPlan.plan.nRow>=(double)1 ){
   99901       pParse->nQueryLoop *= bestPlan.plan.nRow;
   99902     }
   99903 
   99904     /* Check that if the table scanned by this loop iteration had an
   99905     ** INDEXED BY clause attached to it, that the named index is being
   99906     ** used for the scan. If not, then query compilation has failed.
   99907     ** Return an error.
   99908     */
   99909     pIdx = pTabList->a[bestJ].pIndex;
   99910     if( pIdx ){
   99911       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
   99912         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
   99913         goto whereBeginError;
   99914       }else{
   99915         /* If an INDEXED BY clause is used, the bestIndex() function is
   99916         ** guaranteed to find the index specified in the INDEXED BY clause
   99917         ** if it find an index at all. */
   99918         assert( bestPlan.plan.u.pIdx==pIdx );
   99919       }
   99920     }
   99921   }
   99922   WHERETRACE(("*** Optimizer Finished ***\n"));
   99923   if( pParse->nErr || db->mallocFailed ){
   99924     goto whereBeginError;
   99925   }
   99926 
   99927   /* If the total query only selects a single row, then the ORDER BY
   99928   ** clause is irrelevant.
   99929   */
   99930   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
   99931     *ppOrderBy = 0;
   99932   }
   99933 
   99934   /* If the caller is an UPDATE or DELETE statement that is requesting
   99935   ** to use a one-pass algorithm, determine if this is appropriate.
   99936   ** The one-pass algorithm only works if the WHERE clause constraints
   99937   ** the statement to update a single row.
   99938   */
   99939   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
   99940   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
   99941     pWInfo->okOnePass = 1;
   99942     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
   99943   }
   99944 
   99945   /* Open all tables in the pTabList and any indices selected for
   99946   ** searching those tables.
   99947   */
   99948   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
   99949   notReady = ~(Bitmask)0;
   99950   pWInfo->nRowOut = (double)1;
   99951   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
   99952     Table *pTab;     /* Table to open */
   99953     int iDb;         /* Index of database containing table/index */
   99954 
   99955     pTabItem = &pTabList->a[pLevel->iFrom];
   99956     pTab = pTabItem->pTab;
   99957     pLevel->iTabCur = pTabItem->iCursor;
   99958     pWInfo->nRowOut *= pLevel->plan.nRow;
   99959     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   99960     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
   99961       /* Do nothing */
   99962     }else
   99963 #ifndef SQLITE_OMIT_VIRTUALTABLE
   99964     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
   99965       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
   99966       int iCur = pTabItem->iCursor;
   99967       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
   99968     }else
   99969 #endif
   99970     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   99971          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
   99972       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
   99973       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
   99974       testcase( pTab->nCol==BMS-1 );
   99975       testcase( pTab->nCol==BMS );
   99976       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
   99977         Bitmask b = pTabItem->colUsed;
   99978         int n = 0;
   99979         for(; b; b=b>>1, n++){}
   99980         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
   99981                             SQLITE_INT_TO_PTR(n), P4_INT32);
   99982         assert( n<=pTab->nCol );
   99983       }
   99984     }else{
   99985       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
   99986     }
   99987 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
   99988     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
   99989       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
   99990     }else
   99991 #endif
   99992     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   99993       Index *pIx = pLevel->plan.u.pIdx;
   99994       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
   99995       int iIdxCur = pLevel->iIdxCur;
   99996       assert( pIx->pSchema==pTab->pSchema );
   99997       assert( iIdxCur>=0 );
   99998       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
   99999                         (char*)pKey, P4_KEYINFO_HANDOFF);
   100000       VdbeComment((v, "%s", pIx->zName));
   100001     }
   100002     sqlite3CodeVerifySchema(pParse, iDb);
   100003     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
   100004   }
   100005   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
   100006   if( db->mallocFailed ) goto whereBeginError;
   100007 
   100008   /* Generate the code to do the search.  Each iteration of the for
   100009   ** loop below generates code for a single nested loop of the VM
   100010   ** program.
   100011   */
   100012   notReady = ~(Bitmask)0;
   100013   for(i=0; i<nTabList; i++){
   100014     pLevel = &pWInfo->a[i];
   100015     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
   100016     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
   100017     pWInfo->iContinue = pLevel->addrCont;
   100018   }
   100019 
   100020 #ifdef SQLITE_TEST  /* For testing and debugging use only */
   100021   /* Record in the query plan information about the current table
   100022   ** and the index used to access it (if any).  If the table itself
   100023   ** is not used, its name is just '{}'.  If no index is used
   100024   ** the index is listed as "{}".  If the primary key is used the
   100025   ** index name is '*'.
   100026   */
   100027   for(i=0; i<nTabList; i++){
   100028     char *z;
   100029     int n;
   100030     pLevel = &pWInfo->a[i];
   100031     pTabItem = &pTabList->a[pLevel->iFrom];
   100032     z = pTabItem->zAlias;
   100033     if( z==0 ) z = pTabItem->pTab->zName;
   100034     n = sqlite3Strlen30(z);
   100035     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
   100036       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
   100037         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
   100038         nQPlan += 2;
   100039       }else{
   100040         memcpy(&sqlite3_query_plan[nQPlan], z, n);
   100041         nQPlan += n;
   100042       }
   100043       sqlite3_query_plan[nQPlan++] = ' ';
   100044     }
   100045     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
   100046     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
   100047     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
   100048       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
   100049       nQPlan += 2;
   100050     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
   100051       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
   100052       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
   100053         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
   100054         nQPlan += n;
   100055         sqlite3_query_plan[nQPlan++] = ' ';
   100056       }
   100057     }else{
   100058       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
   100059       nQPlan += 3;
   100060     }
   100061   }
   100062   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
   100063     sqlite3_query_plan[--nQPlan] = 0;
   100064   }
   100065   sqlite3_query_plan[nQPlan] = 0;
   100066   nQPlan = 0;
   100067 #endif /* SQLITE_TEST // Testing and debugging use only */
   100068 
   100069   /* Record the continuation address in the WhereInfo structure.  Then
   100070   ** clean up and return.
   100071   */
   100072   return pWInfo;
   100073 
   100074   /* Jump here if malloc fails */
   100075 whereBeginError:
   100076   if( pWInfo ){
   100077     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   100078     whereInfoFree(db, pWInfo);
   100079   }
   100080   return 0;
   100081 }
   100082 
   100083 /*
   100084 ** Generate the end of the WHERE loop.  See comments on
   100085 ** sqlite3WhereBegin() for additional information.
   100086 */
   100087 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   100088   Parse *pParse = pWInfo->pParse;
   100089   Vdbe *v = pParse->pVdbe;
   100090   int i;
   100091   WhereLevel *pLevel;
   100092   SrcList *pTabList = pWInfo->pTabList;
   100093   sqlite3 *db = pParse->db;
   100094 
   100095   /* Generate loop termination code.
   100096   */
   100097   sqlite3ExprCacheClear(pParse);
   100098   for(i=pWInfo->nLevel-1; i>=0; i--){
   100099     pLevel = &pWInfo->a[i];
   100100     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
   100101     if( pLevel->op!=OP_Noop ){
   100102       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
   100103       sqlite3VdbeChangeP5(v, pLevel->p5);
   100104     }
   100105     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
   100106       struct InLoop *pIn;
   100107       int j;
   100108       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
   100109       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
   100110         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
   100111         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
   100112         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
   100113       }
   100114       sqlite3DbFree(db, pLevel->u.in.aInLoop);
   100115     }
   100116     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
   100117     if( pLevel->iLeftJoin ){
   100118       int addr;
   100119       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
   100120       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   100121            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
   100122       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
   100123         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
   100124       }
   100125       if( pLevel->iIdxCur>=0 ){
   100126         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
   100127       }
   100128       if( pLevel->op==OP_Return ){
   100129         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
   100130       }else{
   100131         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
   100132       }
   100133       sqlite3VdbeJumpHere(v, addr);
   100134     }
   100135   }
   100136 
   100137   /* The "break" point is here, just past the end of the outer loop.
   100138   ** Set it.
   100139   */
   100140   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
   100141 
   100142   /* Close all of the cursors that were opened by sqlite3WhereBegin.
   100143   */
   100144   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
   100145   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
   100146     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
   100147     Table *pTab = pTabItem->pTab;
   100148     assert( pTab!=0 );
   100149     if( (pTab->tabFlags & TF_Ephemeral)==0
   100150      && pTab->pSelect==0
   100151      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
   100152     ){
   100153       int ws = pLevel->plan.wsFlags;
   100154       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
   100155         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
   100156       }
   100157       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
   100158         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
   100159       }
   100160     }
   100161 
   100162     /* If this scan uses an index, make code substitutions to read data
   100163     ** from the index in preference to the table. Sometimes, this means
   100164     ** the table need never be read from. This is a performance boost,
   100165     ** as the vdbe level waits until the table is read before actually
   100166     ** seeking the table cursor to the record corresponding to the current
   100167     ** position in the index.
   100168     **
   100169     ** Calls to the code generator in between sqlite3WhereBegin and
   100170     ** sqlite3WhereEnd will have created code that references the table
   100171     ** directly.  This loop scans all that code looking for opcodes
   100172     ** that reference the table and converts them into opcodes that
   100173     ** reference the index.
   100174     */
   100175     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
   100176       int k, j, last;
   100177       VdbeOp *pOp;
   100178       Index *pIdx = pLevel->plan.u.pIdx;
   100179 
   100180       assert( pIdx!=0 );
   100181       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
   100182       last = sqlite3VdbeCurrentAddr(v);
   100183       for(k=pWInfo->iTop; k<last; k++, pOp++){
   100184         if( pOp->p1!=pLevel->iTabCur ) continue;
   100185         if( pOp->opcode==OP_Column ){
   100186           for(j=0; j<pIdx->nColumn; j++){
   100187             if( pOp->p2==pIdx->aiColumn[j] ){
   100188               pOp->p2 = j;
   100189               pOp->p1 = pLevel->iIdxCur;
   100190               break;
   100191             }
   100192           }
   100193           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
   100194                || j<pIdx->nColumn );
   100195         }else if( pOp->opcode==OP_Rowid ){
   100196           pOp->p1 = pLevel->iIdxCur;
   100197           pOp->opcode = OP_IdxRowid;
   100198         }
   100199       }
   100200     }
   100201   }
   100202 
   100203   /* Final cleanup
   100204   */
   100205   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
   100206   whereInfoFree(db, pWInfo);
   100207   return;
   100208 }
   100209 
   100210 /************** End of where.c ***********************************************/
   100211 /************** Begin file parse.c *******************************************/
   100212 /* Driver template for the LEMON parser generator.
   100213 ** The author disclaims copyright to this source code.
   100214 **
   100215 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
   100216 ** The only modifications are the addition of a couple of NEVER()
   100217 ** macros to disable tests that are needed in the case of a general
   100218 ** LALR(1) grammar but which are always false in the
   100219 ** specific grammar used by SQLite.
   100220 */
   100221 /* First off, code is included that follows the "include" declaration
   100222 ** in the input grammar file. */
   100223 
   100224 
   100225 /*
   100226 ** Disable all error recovery processing in the parser push-down
   100227 ** automaton.
   100228 */
   100229 #define YYNOERRORRECOVERY 1
   100230 
   100231 /*
   100232 ** Make yytestcase() the same as testcase()
   100233 */
   100234 #define yytestcase(X) testcase(X)
   100235 
   100236 /*
   100237 ** An instance of this structure holds information about the
   100238 ** LIMIT clause of a SELECT statement.
   100239 */
   100240 struct LimitVal {
   100241   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
   100242   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
   100243 };
   100244 
   100245 /*
   100246 ** An instance of this structure is used to store the LIKE,
   100247 ** GLOB, NOT LIKE, and NOT GLOB operators.
   100248 */
   100249 struct LikeOp {
   100250   Token eOperator;  /* "like" or "glob" or "regexp" */
   100251   int not;         /* True if the NOT keyword is present */
   100252 };
   100253 
   100254 /*
   100255 ** An instance of the following structure describes the event of a
   100256 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
   100257 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
   100258 **
   100259 **      UPDATE ON (a,b,c)
   100260 **
   100261 ** Then the "b" IdList records the list "a,b,c".
   100262 */
   100263 struct TrigEvent { int a; IdList * b; };
   100264 
   100265 /*
   100266 ** An instance of this structure holds the ATTACH key and the key type.
   100267 */
   100268 struct AttachKey { int type;  Token key; };
   100269 
   100270 
   100271   /* This is a utility routine used to set the ExprSpan.zStart and
   100272   ** ExprSpan.zEnd values of pOut so that the span covers the complete
   100273   ** range of text beginning with pStart and going to the end of pEnd.
   100274   */
   100275   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
   100276     pOut->zStart = pStart->z;
   100277     pOut->zEnd = &pEnd->z[pEnd->n];
   100278   }
   100279 
   100280   /* Construct a new Expr object from a single identifier.  Use the
   100281   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
   100282   ** that created the expression.
   100283   */
   100284   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
   100285     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
   100286     pOut->zStart = pValue->z;
   100287     pOut->zEnd = &pValue->z[pValue->n];
   100288   }
   100289 
   100290   /* This routine constructs a binary expression node out of two ExprSpan
   100291   ** objects and uses the result to populate a new ExprSpan object.
   100292   */
   100293   static void spanBinaryExpr(
   100294     ExprSpan *pOut,     /* Write the result here */
   100295     Parse *pParse,      /* The parsing context.  Errors accumulate here */
   100296     int op,             /* The binary operation */
   100297     ExprSpan *pLeft,    /* The left operand */
   100298     ExprSpan *pRight    /* The right operand */
   100299   ){
   100300     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
   100301     pOut->zStart = pLeft->zStart;
   100302     pOut->zEnd = pRight->zEnd;
   100303   }
   100304 
   100305   /* Construct an expression node for a unary postfix operator
   100306   */
   100307   static void spanUnaryPostfix(
   100308     ExprSpan *pOut,        /* Write the new expression node here */
   100309     Parse *pParse,         /* Parsing context to record errors */
   100310     int op,                /* The operator */
   100311     ExprSpan *pOperand,    /* The operand */
   100312     Token *pPostOp         /* The operand token for setting the span */
   100313   ){
   100314     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   100315     pOut->zStart = pOperand->zStart;
   100316     pOut->zEnd = &pPostOp->z[pPostOp->n];
   100317   }
   100318 
   100319   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
   100320   ** unary TK_ISNULL or TK_NOTNULL expression. */
   100321   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
   100322     sqlite3 *db = pParse->db;
   100323     if( db->mallocFailed==0 && pY->op==TK_NULL ){
   100324       pA->op = (u8)op;
   100325       sqlite3ExprDelete(db, pA->pRight);
   100326       pA->pRight = 0;
   100327     }
   100328   }
   100329 
   100330   /* Construct an expression node for a unary prefix operator
   100331   */
   100332   static void spanUnaryPrefix(
   100333     ExprSpan *pOut,        /* Write the new expression node here */
   100334     Parse *pParse,         /* Parsing context to record errors */
   100335     int op,                /* The operator */
   100336     ExprSpan *pOperand,    /* The operand */
   100337     Token *pPreOp         /* The operand token for setting the span */
   100338   ){
   100339     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
   100340     pOut->zStart = pPreOp->z;
   100341     pOut->zEnd = pOperand->zEnd;
   100342   }
   100343 /* Next is all token values, in a form suitable for use by makeheaders.
   100344 ** This section will be null unless lemon is run with the -m switch.
   100345 */
   100346 /*
   100347 ** These constants (all generated automatically by the parser generator)
   100348 ** specify the various kinds of tokens (terminals) that the parser
   100349 ** understands.
   100350 **
   100351 ** Each symbol here is a terminal symbol in the grammar.
   100352 */
   100353 /* Make sure the INTERFACE macro is defined.
   100354 */
   100355 #ifndef INTERFACE
   100356 # define INTERFACE 1
   100357 #endif
   100358 /* The next thing included is series of defines which control
   100359 ** various aspects of the generated parser.
   100360 **    YYCODETYPE         is the data type used for storing terminal
   100361 **                       and nonterminal numbers.  "unsigned char" is
   100362 **                       used if there are fewer than 250 terminals
   100363 **                       and nonterminals.  "int" is used otherwise.
   100364 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
   100365 **                       to no legal terminal or nonterminal number.  This
   100366 **                       number is used to fill in empty slots of the hash
   100367 **                       table.
   100368 **    YYFALLBACK         If defined, this indicates that one or more tokens
   100369 **                       have fall-back values which should be used if the
   100370 **                       original value of the token will not parse.
   100371 **    YYACTIONTYPE       is the data type used for storing terminal
   100372 **                       and nonterminal numbers.  "unsigned char" is
   100373 **                       used if there are fewer than 250 rules and
   100374 **                       states combined.  "int" is used otherwise.
   100375 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
   100376 **                       directly to the parser from the tokenizer.
   100377 **    YYMINORTYPE        is the data type used for all minor tokens.
   100378 **                       This is typically a union of many types, one of
   100379 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
   100380 **                       for base tokens is called "yy0".
   100381 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
   100382 **                       zero the stack is dynamically sized using realloc()
   100383 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
   100384 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
   100385 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
   100386 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
   100387 **    YYNSTATE           the combined number of states.
   100388 **    YYNRULE            the number of rules in the grammar
   100389 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
   100390 **                       defined, then do no error processing.
   100391 */
   100392 #define YYCODETYPE unsigned char
   100393 #define YYNOCODE 253
   100394 #define YYACTIONTYPE unsigned short int
   100395 #define YYWILDCARD 67
   100396 #define sqlite3ParserTOKENTYPE Token
   100397 typedef union {
   100398   int yyinit;
   100399   sqlite3ParserTOKENTYPE yy0;
   100400   int yy4;
   100401   struct TrigEvent yy90;
   100402   ExprSpan yy118;
   100403   TriggerStep* yy203;
   100404   u8 yy210;
   100405   struct {int value; int mask;} yy215;
   100406   SrcList* yy259;
   100407   struct LimitVal yy292;
   100408   Expr* yy314;
   100409   ExprList* yy322;
   100410   struct LikeOp yy342;
   100411   IdList* yy384;
   100412   Select* yy387;
   100413 } YYMINORTYPE;
   100414 #ifndef YYSTACKDEPTH
   100415 #define YYSTACKDEPTH 100
   100416 #endif
   100417 #define sqlite3ParserARG_SDECL Parse *pParse;
   100418 #define sqlite3ParserARG_PDECL ,Parse *pParse
   100419 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
   100420 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
   100421 #define YYNSTATE 630
   100422 #define YYNRULE 329
   100423 #define YYFALLBACK 1
   100424 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
   100425 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
   100426 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
   100427 
   100428 /* The yyzerominor constant is used to initialize instances of
   100429 ** YYMINORTYPE objects to zero. */
   100430 static const YYMINORTYPE yyzerominor = { 0 };
   100431 
   100432 /* Define the yytestcase() macro to be a no-op if is not already defined
   100433 ** otherwise.
   100434 **
   100435 ** Applications can choose to define yytestcase() in the %include section
   100436 ** to a macro that can assist in verifying code coverage.  For production
   100437 ** code the yytestcase() macro should be turned off.  But it is useful
   100438 ** for testing.
   100439 */
   100440 #ifndef yytestcase
   100441 # define yytestcase(X)
   100442 #endif
   100443 
   100444 
   100445 /* Next are the tables used to determine what action to take based on the
   100446 ** current state and lookahead token.  These tables are used to implement
   100447 ** functions that take a state number and lookahead value and return an
   100448 ** action integer.
   100449 **
   100450 ** Suppose the action integer is N.  Then the action is determined as
   100451 ** follows
   100452 **
   100453 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
   100454 **                                      token onto the stack and goto state N.
   100455 **
   100456 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
   100457 **
   100458 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
   100459 **
   100460 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
   100461 **
   100462 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
   100463 **                                      slots in the yy_action[] table.
   100464 **
   100465 ** The action table is constructed as a single large table named yy_action[].
   100466 ** Given state S and lookahead X, the action is computed as
   100467 **
   100468 **      yy_action[ yy_shift_ofst[S] + X ]
   100469 **
   100470 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
   100471 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
   100472 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
   100473 ** and that yy_default[S] should be used instead.
   100474 **
   100475 ** The formula above is for computing the action when the lookahead is
   100476 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
   100477 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
   100478 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
   100479 ** YY_SHIFT_USE_DFLT.
   100480 **
   100481 ** The following are the tables generated in this section:
   100482 **
   100483 **  yy_action[]        A single table containing all actions.
   100484 **  yy_lookahead[]     A table containing the lookahead for each entry in
   100485 **                     yy_action.  Used to detect hash collisions.
   100486 **  yy_shift_ofst[]    For each state, the offset into yy_action for
   100487 **                     shifting terminals.
   100488 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
   100489 **                     shifting non-terminals after a reduce.
   100490 **  yy_default[]       Default action for each state.
   100491 */
   100492 #define YY_ACTTAB_COUNT (1557)
   100493 static const YYACTIONTYPE yy_action[] = {
   100494  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
   100495  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
   100496  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
   100497  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
   100498  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
   100499  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
   100500  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
   100501  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
   100502  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   100503  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
   100504  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
   100505  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
   100506  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
   100507  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
   100508  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
   100509  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
   100510  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
   100511  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
   100512  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
   100513  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
   100514  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
   100515  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   100516  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
   100517  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
   100518  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
   100519  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
   100520  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
   100521  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
   100522  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
   100523  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
   100524  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
   100525  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
   100526  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
   100527  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
   100528  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
   100529  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
   100530  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   100531  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
   100532  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
   100533  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
   100534  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
   100535  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
   100536  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
   100537  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
   100538  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
   100539  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
   100540  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
   100541  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
   100542  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
   100543  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
   100544  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
   100545  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
   100546  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
   100547  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
   100548  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
   100549  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
   100550  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
   100551  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
   100552  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   100553  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
   100554  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
   100555  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
   100556  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
   100557  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
   100558  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
   100559  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
   100560  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
   100561  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
   100562  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
   100563  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
   100564  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
   100565  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
   100566  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
   100567  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   100568  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
   100569  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
   100570  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
   100571  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
   100572  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
   100573  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
   100574  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
   100575  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
   100576  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
   100577  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
   100578  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
   100579  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
   100580  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
   100581  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
   100582  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
   100583  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
   100584  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
   100585  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
   100586  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
   100587  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
   100588  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
   100589  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
   100590  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
   100591  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
   100592  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
   100593  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
   100594  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
   100595  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
   100596  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
   100597  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
   100598  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
   100599  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
   100600  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
   100601  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
   100602  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
   100603  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
   100604  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
   100605  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
   100606  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
   100607  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
   100608  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
   100609  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
   100610  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
   100611  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
   100612  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
   100613  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
   100614  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
   100615  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
   100616  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
   100617  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
   100618  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
   100619  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
   100620  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
   100621  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
   100622  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
   100623  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
   100624  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
   100625  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
   100626  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
   100627  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
   100628  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
   100629  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
   100630  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
   100631  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
   100632  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
   100633  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
   100634  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
   100635  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
   100636  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
   100637  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
   100638  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
   100639  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
   100640  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
   100641  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
   100642  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
   100643  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
   100644  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
   100645  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
   100646  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
   100647  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
   100648  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
   100649  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
   100650 };
   100651 static const YYCODETYPE yy_lookahead[] = {
   100652  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
   100653  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
   100654  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
   100655  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
   100656  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
   100657  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   100658  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
   100659  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
   100660  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   100661  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
   100662  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
   100663  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
   100664  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
   100665  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
   100666  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
   100667  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
   100668  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
   100669  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
   100670  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
   100671  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
   100672  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   100673  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   100674  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
   100675  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
   100676  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
   100677  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
   100678  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
   100679  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   100680  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
   100681  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
   100682  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
   100683  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
   100684  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
   100685  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
   100686  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
   100687  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
   100688  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   100689  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
   100690  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
   100691  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
   100692  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
   100693  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
   100694  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   100695  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
   100696  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
   100697  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
   100698  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
   100699  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
   100700  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
   100701  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
   100702  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
   100703  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
   100704  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
   100705  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
   100706  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
   100707  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
   100708  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
   100709  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   100710  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   100711  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
   100712  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
   100713  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
   100714  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
   100715  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
   100716  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
   100717  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
   100718  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
   100719  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
   100720  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
   100721  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
   100722  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
   100723  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
   100724  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
   100725  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   100726  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
   100727  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
   100728  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
   100729  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
   100730  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
   100731  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
   100732  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
   100733  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
   100734  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
   100735  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
   100736  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
   100737  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
   100738  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
   100739  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
   100740  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
   100741  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
   100742  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
   100743  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
   100744  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
   100745  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
   100746  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
   100747  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
   100748  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
   100749  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
   100750  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
   100751  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
   100752  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
   100753  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
   100754  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
   100755  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
   100756  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
   100757  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
   100758  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
   100759  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
   100760  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
   100761  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
   100762  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
   100763  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
   100764  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
   100765  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
   100766  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
   100767  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
   100768  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
   100769  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
   100770  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
   100771  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
   100772  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
   100773  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
   100774  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
   100775  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
   100776  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
   100777  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
   100778  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
   100779  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
   100780  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
   100781  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
   100782  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
   100783  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
   100784  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
   100785  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
   100786  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
   100787  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
   100788  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
   100789  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
   100790  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
   100791  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
   100792  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
   100793  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
   100794  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
   100795  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
   100796  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
   100797  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
   100798  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
   100799  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
   100800  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
   100801  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
   100802  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
   100803  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
   100804  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
   100805  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
   100806  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
   100807  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
   100808 };
   100809 #define YY_SHIFT_USE_DFLT (-74)
   100810 #define YY_SHIFT_COUNT (418)
   100811 #define YY_SHIFT_MIN   (-73)
   100812 #define YY_SHIFT_MAX   (1468)
   100813 static const short yy_shift_ofst[] = {
   100814  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
   100815  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
   100816  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   100817  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   100818  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
   100819  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
   100820  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
   100821  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
   100822  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
   100823  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
   100824  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
   100825  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
   100826  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
   100827  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
   100828  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
   100829  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
   100830  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
   100831  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
   100832  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
   100833  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
   100834  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
   100835  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
   100836  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
   100837  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
   100838  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
   100839  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
   100840  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
   100841  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
   100842  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
   100843  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
   100844  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
   100845  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
   100846  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
   100847  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
   100848  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
   100849  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
   100850  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
   100851  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
   100852  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
   100853  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
   100854  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
   100855  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
   100856 };
   100857 #define YY_REDUCE_USE_DFLT (-142)
   100858 #define YY_REDUCE_COUNT (312)
   100859 #define YY_REDUCE_MIN   (-141)
   100860 #define YY_REDUCE_MAX   (1369)
   100861 static const short yy_reduce_ofst[] = {
   100862  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
   100863  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
   100864  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
   100865  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
   100866  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
   100867  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
   100868  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
   100869  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
   100870  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
   100871  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
   100872  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
   100873  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
   100874  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
   100875  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
   100876  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
   100877  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
   100878  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
   100879  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
   100880  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
   100881  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
   100882  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
   100883  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
   100884  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
   100885  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
   100886  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
   100887  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
   100888  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
   100889  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
   100890  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
   100891  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
   100892  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
   100893  /*   310 */  1031, 1023, 1030,
   100894 };
   100895 static const YYACTIONTYPE yy_default[] = {
   100896  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
   100897  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
   100898  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100899  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100900  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100901  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100902  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
   100903  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
   100904  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
   100905  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
   100906  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
   100907  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100908  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
   100909  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
   100910  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100911  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
   100912  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100913  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100914  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
   100915  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
   100916  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
   100917  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
   100918  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
   100919  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
   100920  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
   100921  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
   100922  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
   100923  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
   100924  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
   100925  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
   100926  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
   100927  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
   100928  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100929  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
   100930  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100931  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
   100932  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
   100933  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100934  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
   100935  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
   100936  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
   100937  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
   100938  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
   100939  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
   100940  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
   100941  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
   100942  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
   100943  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
   100944  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
   100945  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
   100946  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
   100947  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
   100948  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
   100949  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
   100950  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
   100951  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
   100952  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
   100953  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
   100954  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
   100955  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
   100956  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
   100957  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
   100958  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
   100959 };
   100960 
   100961 /* The next table maps tokens into fallback tokens.  If a construct
   100962 ** like the following:
   100963 **
   100964 **      %fallback ID X Y Z.
   100965 **
   100966 ** appears in the grammar, then ID becomes a fallback token for X, Y,
   100967 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
   100968 ** but it does not parse, the type of the token is changed to ID and
   100969 ** the parse is retried before an error is thrown.
   100970 */
   100971 #ifdef YYFALLBACK
   100972 static const YYCODETYPE yyFallback[] = {
   100973     0,  /*          $ => nothing */
   100974     0,  /*       SEMI => nothing */
   100975    26,  /*    EXPLAIN => ID */
   100976    26,  /*      QUERY => ID */
   100977    26,  /*       PLAN => ID */
   100978    26,  /*      BEGIN => ID */
   100979     0,  /* TRANSACTION => nothing */
   100980    26,  /*   DEFERRED => ID */
   100981    26,  /*  IMMEDIATE => ID */
   100982    26,  /*  EXCLUSIVE => ID */
   100983     0,  /*     COMMIT => nothing */
   100984    26,  /*        END => ID */
   100985    26,  /*   ROLLBACK => ID */
   100986    26,  /*  SAVEPOINT => ID */
   100987    26,  /*    RELEASE => ID */
   100988     0,  /*         TO => nothing */
   100989     0,  /*      TABLE => nothing */
   100990     0,  /*     CREATE => nothing */
   100991    26,  /*         IF => ID */
   100992     0,  /*        NOT => nothing */
   100993     0,  /*     EXISTS => nothing */
   100994    26,  /*       TEMP => ID */
   100995     0,  /*         LP => nothing */
   100996     0,  /*         RP => nothing */
   100997     0,  /*         AS => nothing */
   100998     0,  /*      COMMA => nothing */
   100999     0,  /*         ID => nothing */
   101000     0,  /*    INDEXED => nothing */
   101001    26,  /*      ABORT => ID */
   101002    26,  /*     ACTION => ID */
   101003    26,  /*      AFTER => ID */
   101004    26,  /*    ANALYZE => ID */
   101005    26,  /*        ASC => ID */
   101006    26,  /*     ATTACH => ID */
   101007    26,  /*     BEFORE => ID */
   101008    26,  /*         BY => ID */
   101009    26,  /*    CASCADE => ID */
   101010    26,  /*       CAST => ID */
   101011    26,  /*   COLUMNKW => ID */
   101012    26,  /*   CONFLICT => ID */
   101013    26,  /*   DATABASE => ID */
   101014    26,  /*       DESC => ID */
   101015    26,  /*     DETACH => ID */
   101016    26,  /*       EACH => ID */
   101017    26,  /*       FAIL => ID */
   101018    26,  /*        FOR => ID */
   101019    26,  /*     IGNORE => ID */
   101020    26,  /*  INITIALLY => ID */
   101021    26,  /*    INSTEAD => ID */
   101022    26,  /*    LIKE_KW => ID */
   101023    26,  /*      MATCH => ID */
   101024    26,  /*         NO => ID */
   101025    26,  /*        KEY => ID */
   101026    26,  /*         OF => ID */
   101027    26,  /*     OFFSET => ID */
   101028    26,  /*     PRAGMA => ID */
   101029    26,  /*      RAISE => ID */
   101030    26,  /*    REPLACE => ID */
   101031    26,  /*   RESTRICT => ID */
   101032    26,  /*        ROW => ID */
   101033    26,  /*    TRIGGER => ID */
   101034    26,  /*     VACUUM => ID */
   101035    26,  /*       VIEW => ID */
   101036    26,  /*    VIRTUAL => ID */
   101037    26,  /*    REINDEX => ID */
   101038    26,  /*     RENAME => ID */
   101039    26,  /*   CTIME_KW => ID */
   101040 };
   101041 #endif /* YYFALLBACK */
   101042 
   101043 /* The following structure represents a single element of the
   101044 ** parser's stack.  Information stored includes:
   101045 **
   101046 **   +  The state number for the parser at this level of the stack.
   101047 **
   101048 **   +  The value of the token stored at this level of the stack.
   101049 **      (In other words, the "major" token.)
   101050 **
   101051 **   +  The semantic value stored at this level of the stack.  This is
   101052 **      the information used by the action routines in the grammar.
   101053 **      It is sometimes called the "minor" token.
   101054 */
   101055 struct yyStackEntry {
   101056   YYACTIONTYPE stateno;  /* The state-number */
   101057   YYCODETYPE major;      /* The major token value.  This is the code
   101058                          ** number for the token at this stack level */
   101059   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
   101060                          ** is the value of the token  */
   101061 };
   101062 typedef struct yyStackEntry yyStackEntry;
   101063 
   101064 /* The state of the parser is completely contained in an instance of
   101065 ** the following structure */
   101066 struct yyParser {
   101067   int yyidx;                    /* Index of top element in stack */
   101068 #ifdef YYTRACKMAXSTACKDEPTH
   101069   int yyidxMax;                 /* Maximum value of yyidx */
   101070 #endif
   101071   int yyerrcnt;                 /* Shifts left before out of the error */
   101072   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
   101073 #if YYSTACKDEPTH<=0
   101074   int yystksz;                  /* Current side of the stack */
   101075   yyStackEntry *yystack;        /* The parser's stack */
   101076 #else
   101077   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
   101078 #endif
   101079 };
   101080 typedef struct yyParser yyParser;
   101081 
   101082 #ifndef NDEBUG
   101083 static FILE *yyTraceFILE = 0;
   101084 static char *yyTracePrompt = 0;
   101085 #endif /* NDEBUG */
   101086 
   101087 #ifndef NDEBUG
   101088 /*
   101089 ** Turn parser tracing on by giving a stream to which to write the trace
   101090 ** and a prompt to preface each trace message.  Tracing is turned off
   101091 ** by making either argument NULL
   101092 **
   101093 ** Inputs:
   101094 ** <ul>
   101095 ** <li> A FILE* to which trace output should be written.
   101096 **      If NULL, then tracing is turned off.
   101097 ** <li> A prefix string written at the beginning of every
   101098 **      line of trace output.  If NULL, then tracing is
   101099 **      turned off.
   101100 ** </ul>
   101101 **
   101102 ** Outputs:
   101103 ** None.
   101104 */
   101105 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
   101106   yyTraceFILE = TraceFILE;
   101107   yyTracePrompt = zTracePrompt;
   101108   if( yyTraceFILE==0 ) yyTracePrompt = 0;
   101109   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
   101110 }
   101111 #endif /* NDEBUG */
   101112 
   101113 #ifndef NDEBUG
   101114 /* For tracing shifts, the names of all terminals and nonterminals
   101115 ** are required.  The following table supplies these names */
   101116 static const char *const yyTokenName[] = {
   101117   "$",             "SEMI",          "EXPLAIN",       "QUERY",
   101118   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
   101119   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
   101120   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
   101121   "TABLE",         "CREATE",        "IF",            "NOT",
   101122   "EXISTS",        "TEMP",          "LP",            "RP",
   101123   "AS",            "COMMA",         "ID",            "INDEXED",
   101124   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
   101125   "ASC",           "ATTACH",        "BEFORE",        "BY",
   101126   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
   101127   "DATABASE",      "DESC",          "DETACH",        "EACH",
   101128   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
   101129   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
   101130   "KEY",           "OF",            "OFFSET",        "PRAGMA",
   101131   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
   101132   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
   101133   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
   101134   "OR",            "AND",           "IS",            "BETWEEN",
   101135   "IN",            "ISNULL",        "NOTNULL",       "NE",
   101136   "EQ",            "GT",            "LE",            "LT",
   101137   "GE",            "ESCAPE",        "BITAND",        "BITOR",
   101138   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
   101139   "STAR",          "SLASH",         "REM",           "CONCAT",
   101140   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
   101141   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
   101142   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
   101143   "ON",            "INSERT",        "DELETE",        "UPDATE",
   101144   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
   101145   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
   101146   "SELECT",        "DISTINCT",      "DOT",           "FROM",
   101147   "JOIN",          "USING",         "ORDER",         "GROUP",
   101148   "HAVING",        "LIMIT",         "WHERE",         "INTO",
   101149   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
   101150   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
   101151   "THEN",          "ELSE",          "INDEX",         "ALTER",
   101152   "ADD",           "error",         "input",         "cmdlist",
   101153   "ecmd",          "explain",       "cmdx",          "cmd",
   101154   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
   101155   "create_table",  "create_table_args",  "createkw",      "temp",
   101156   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
   101157   "select",        "column",        "columnid",      "type",
   101158   "carglist",      "id",            "ids",           "typetoken",
   101159   "typename",      "signed",        "plus_num",      "minus_num",
   101160   "carg",          "ccons",         "term",          "expr",
   101161   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
   101162   "refargs",       "defer_subclause",  "refarg",        "refact",
   101163   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
   101164   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
   101165   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
   101166   "distinct",      "selcollist",    "from",          "where_opt",
   101167   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
   101168   "sclp",          "as",            "seltablist",    "stl_prefix",
   101169   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
   101170   "joinop2",       "inscollist",    "sortlist",      "sortitem",
   101171   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
   101172   "itemlist",      "exprlist",      "likeop",        "between_op",
   101173   "in_op",         "case_operand",  "case_exprlist",  "case_else",
   101174   "uniqueflag",    "collate",       "nmnum",         "plus_opt",
   101175   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
   101176   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
   101177   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
   101178   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
   101179   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
   101180 };
   101181 #endif /* NDEBUG */
   101182 
   101183 #ifndef NDEBUG
   101184 /* For tracing reduce actions, the names of all rules are required.
   101185 */
   101186 static const char *const yyRuleName[] = {
   101187  /*   0 */ "input ::= cmdlist",
   101188  /*   1 */ "cmdlist ::= cmdlist ecmd",
   101189  /*   2 */ "cmdlist ::= ecmd",
   101190  /*   3 */ "ecmd ::= SEMI",
   101191  /*   4 */ "ecmd ::= explain cmdx SEMI",
   101192  /*   5 */ "explain ::=",
   101193  /*   6 */ "explain ::= EXPLAIN",
   101194  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
   101195  /*   8 */ "cmdx ::= cmd",
   101196  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
   101197  /*  10 */ "trans_opt ::=",
   101198  /*  11 */ "trans_opt ::= TRANSACTION",
   101199  /*  12 */ "trans_opt ::= TRANSACTION nm",
   101200  /*  13 */ "transtype ::=",
   101201  /*  14 */ "transtype ::= DEFERRED",
   101202  /*  15 */ "transtype ::= IMMEDIATE",
   101203  /*  16 */ "transtype ::= EXCLUSIVE",
   101204  /*  17 */ "cmd ::= COMMIT trans_opt",
   101205  /*  18 */ "cmd ::= END trans_opt",
   101206  /*  19 */ "cmd ::= ROLLBACK trans_opt",
   101207  /*  20 */ "savepoint_opt ::= SAVEPOINT",
   101208  /*  21 */ "savepoint_opt ::=",
   101209  /*  22 */ "cmd ::= SAVEPOINT nm",
   101210  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
   101211  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
   101212  /*  25 */ "cmd ::= create_table create_table_args",
   101213  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
   101214  /*  27 */ "createkw ::= CREATE",
   101215  /*  28 */ "ifnotexists ::=",
   101216  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
   101217  /*  30 */ "temp ::= TEMP",
   101218  /*  31 */ "temp ::=",
   101219  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
   101220  /*  33 */ "create_table_args ::= AS select",
   101221  /*  34 */ "columnlist ::= columnlist COMMA column",
   101222  /*  35 */ "columnlist ::= column",
   101223  /*  36 */ "column ::= columnid type carglist",
   101224  /*  37 */ "columnid ::= nm",
   101225  /*  38 */ "id ::= ID",
   101226  /*  39 */ "id ::= INDEXED",
   101227  /*  40 */ "ids ::= ID|STRING",
   101228  /*  41 */ "nm ::= id",
   101229  /*  42 */ "nm ::= STRING",
   101230  /*  43 */ "nm ::= JOIN_KW",
   101231  /*  44 */ "type ::=",
   101232  /*  45 */ "type ::= typetoken",
   101233  /*  46 */ "typetoken ::= typename",
   101234  /*  47 */ "typetoken ::= typename LP signed RP",
   101235  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
   101236  /*  49 */ "typename ::= ids",
   101237  /*  50 */ "typename ::= typename ids",
   101238  /*  51 */ "signed ::= plus_num",
   101239  /*  52 */ "signed ::= minus_num",
   101240  /*  53 */ "carglist ::= carglist carg",
   101241  /*  54 */ "carglist ::=",
   101242  /*  55 */ "carg ::= CONSTRAINT nm ccons",
   101243  /*  56 */ "carg ::= ccons",
   101244  /*  57 */ "ccons ::= DEFAULT term",
   101245  /*  58 */ "ccons ::= DEFAULT LP expr RP",
   101246  /*  59 */ "ccons ::= DEFAULT PLUS term",
   101247  /*  60 */ "ccons ::= DEFAULT MINUS term",
   101248  /*  61 */ "ccons ::= DEFAULT id",
   101249  /*  62 */ "ccons ::= NULL onconf",
   101250  /*  63 */ "ccons ::= NOT NULL onconf",
   101251  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
   101252  /*  65 */ "ccons ::= UNIQUE onconf",
   101253  /*  66 */ "ccons ::= CHECK LP expr RP",
   101254  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
   101255  /*  68 */ "ccons ::= defer_subclause",
   101256  /*  69 */ "ccons ::= COLLATE ids",
   101257  /*  70 */ "autoinc ::=",
   101258  /*  71 */ "autoinc ::= AUTOINCR",
   101259  /*  72 */ "refargs ::=",
   101260  /*  73 */ "refargs ::= refargs refarg",
   101261  /*  74 */ "refarg ::= MATCH nm",
   101262  /*  75 */ "refarg ::= ON INSERT refact",
   101263  /*  76 */ "refarg ::= ON DELETE refact",
   101264  /*  77 */ "refarg ::= ON UPDATE refact",
   101265  /*  78 */ "refact ::= SET NULL",
   101266  /*  79 */ "refact ::= SET DEFAULT",
   101267  /*  80 */ "refact ::= CASCADE",
   101268  /*  81 */ "refact ::= RESTRICT",
   101269  /*  82 */ "refact ::= NO ACTION",
   101270  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
   101271  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
   101272  /*  85 */ "init_deferred_pred_opt ::=",
   101273  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
   101274  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
   101275  /*  88 */ "conslist_opt ::=",
   101276  /*  89 */ "conslist_opt ::= COMMA conslist",
   101277  /*  90 */ "conslist ::= conslist COMMA tcons",
   101278  /*  91 */ "conslist ::= conslist tcons",
   101279  /*  92 */ "conslist ::= tcons",
   101280  /*  93 */ "tcons ::= CONSTRAINT nm",
   101281  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
   101282  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
   101283  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
   101284  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
   101285  /*  98 */ "defer_subclause_opt ::=",
   101286  /*  99 */ "defer_subclause_opt ::= defer_subclause",
   101287  /* 100 */ "onconf ::=",
   101288  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
   101289  /* 102 */ "orconf ::=",
   101290  /* 103 */ "orconf ::= OR resolvetype",
   101291  /* 104 */ "resolvetype ::= raisetype",
   101292  /* 105 */ "resolvetype ::= IGNORE",
   101293  /* 106 */ "resolvetype ::= REPLACE",
   101294  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
   101295  /* 108 */ "ifexists ::= IF EXISTS",
   101296  /* 109 */ "ifexists ::=",
   101297  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
   101298  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
   101299  /* 112 */ "cmd ::= select",
   101300  /* 113 */ "select ::= oneselect",
   101301  /* 114 */ "select ::= select multiselect_op oneselect",
   101302  /* 115 */ "multiselect_op ::= UNION",
   101303  /* 116 */ "multiselect_op ::= UNION ALL",
   101304  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
   101305  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
   101306  /* 119 */ "distinct ::= DISTINCT",
   101307  /* 120 */ "distinct ::= ALL",
   101308  /* 121 */ "distinct ::=",
   101309  /* 122 */ "sclp ::= selcollist COMMA",
   101310  /* 123 */ "sclp ::=",
   101311  /* 124 */ "selcollist ::= sclp expr as",
   101312  /* 125 */ "selcollist ::= sclp STAR",
   101313  /* 126 */ "selcollist ::= sclp nm DOT STAR",
   101314  /* 127 */ "as ::= AS nm",
   101315  /* 128 */ "as ::= ids",
   101316  /* 129 */ "as ::=",
   101317  /* 130 */ "from ::=",
   101318  /* 131 */ "from ::= FROM seltablist",
   101319  /* 132 */ "stl_prefix ::= seltablist joinop",
   101320  /* 133 */ "stl_prefix ::=",
   101321  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
   101322  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
   101323  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
   101324  /* 137 */ "dbnm ::=",
   101325  /* 138 */ "dbnm ::= DOT nm",
   101326  /* 139 */ "fullname ::= nm dbnm",
   101327  /* 140 */ "joinop ::= COMMA|JOIN",
   101328  /* 141 */ "joinop ::= JOIN_KW JOIN",
   101329  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
   101330  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
   101331  /* 144 */ "on_opt ::= ON expr",
   101332  /* 145 */ "on_opt ::=",
   101333  /* 146 */ "indexed_opt ::=",
   101334  /* 147 */ "indexed_opt ::= INDEXED BY nm",
   101335  /* 148 */ "indexed_opt ::= NOT INDEXED",
   101336  /* 149 */ "using_opt ::= USING LP inscollist RP",
   101337  /* 150 */ "using_opt ::=",
   101338  /* 151 */ "orderby_opt ::=",
   101339  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
   101340  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
   101341  /* 154 */ "sortlist ::= sortitem sortorder",
   101342  /* 155 */ "sortitem ::= expr",
   101343  /* 156 */ "sortorder ::= ASC",
   101344  /* 157 */ "sortorder ::= DESC",
   101345  /* 158 */ "sortorder ::=",
   101346  /* 159 */ "groupby_opt ::=",
   101347  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
   101348  /* 161 */ "having_opt ::=",
   101349  /* 162 */ "having_opt ::= HAVING expr",
   101350  /* 163 */ "limit_opt ::=",
   101351  /* 164 */ "limit_opt ::= LIMIT expr",
   101352  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
   101353  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
   101354  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
   101355  /* 168 */ "where_opt ::=",
   101356  /* 169 */ "where_opt ::= WHERE expr",
   101357  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
   101358  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
   101359  /* 172 */ "setlist ::= nm EQ expr",
   101360  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
   101361  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
   101362  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
   101363  /* 176 */ "insert_cmd ::= INSERT orconf",
   101364  /* 177 */ "insert_cmd ::= REPLACE",
   101365  /* 178 */ "itemlist ::= itemlist COMMA expr",
   101366  /* 179 */ "itemlist ::= expr",
   101367  /* 180 */ "inscollist_opt ::=",
   101368  /* 181 */ "inscollist_opt ::= LP inscollist RP",
   101369  /* 182 */ "inscollist ::= inscollist COMMA nm",
   101370  /* 183 */ "inscollist ::= nm",
   101371  /* 184 */ "expr ::= term",
   101372  /* 185 */ "expr ::= LP expr RP",
   101373  /* 186 */ "term ::= NULL",
   101374  /* 187 */ "expr ::= id",
   101375  /* 188 */ "expr ::= JOIN_KW",
   101376  /* 189 */ "expr ::= nm DOT nm",
   101377  /* 190 */ "expr ::= nm DOT nm DOT nm",
   101378  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
   101379  /* 192 */ "term ::= STRING",
   101380  /* 193 */ "expr ::= REGISTER",
   101381  /* 194 */ "expr ::= VARIABLE",
   101382  /* 195 */ "expr ::= expr COLLATE ids",
   101383  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
   101384  /* 197 */ "expr ::= ID LP distinct exprlist RP",
   101385  /* 198 */ "expr ::= ID LP STAR RP",
   101386  /* 199 */ "term ::= CTIME_KW",
   101387  /* 200 */ "expr ::= expr AND expr",
   101388  /* 201 */ "expr ::= expr OR expr",
   101389  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
   101390  /* 203 */ "expr ::= expr EQ|NE expr",
   101391  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
   101392  /* 205 */ "expr ::= expr PLUS|MINUS expr",
   101393  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
   101394  /* 207 */ "expr ::= expr CONCAT expr",
   101395  /* 208 */ "likeop ::= LIKE_KW",
   101396  /* 209 */ "likeop ::= NOT LIKE_KW",
   101397  /* 210 */ "likeop ::= MATCH",
   101398  /* 211 */ "likeop ::= NOT MATCH",
   101399  /* 212 */ "expr ::= expr likeop expr",
   101400  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
   101401  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
   101402  /* 215 */ "expr ::= expr NOT NULL",
   101403  /* 216 */ "expr ::= expr IS expr",
   101404  /* 217 */ "expr ::= expr IS NOT expr",
   101405  /* 218 */ "expr ::= NOT expr",
   101406  /* 219 */ "expr ::= BITNOT expr",
   101407  /* 220 */ "expr ::= MINUS expr",
   101408  /* 221 */ "expr ::= PLUS expr",
   101409  /* 222 */ "between_op ::= BETWEEN",
   101410  /* 223 */ "between_op ::= NOT BETWEEN",
   101411  /* 224 */ "expr ::= expr between_op expr AND expr",
   101412  /* 225 */ "in_op ::= IN",
   101413  /* 226 */ "in_op ::= NOT IN",
   101414  /* 227 */ "expr ::= expr in_op LP exprlist RP",
   101415  /* 228 */ "expr ::= LP select RP",
   101416  /* 229 */ "expr ::= expr in_op LP select RP",
   101417  /* 230 */ "expr ::= expr in_op nm dbnm",
   101418  /* 231 */ "expr ::= EXISTS LP select RP",
   101419  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
   101420  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
   101421  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
   101422  /* 235 */ "case_else ::= ELSE expr",
   101423  /* 236 */ "case_else ::=",
   101424  /* 237 */ "case_operand ::= expr",
   101425  /* 238 */ "case_operand ::=",
   101426  /* 239 */ "exprlist ::= nexprlist",
   101427  /* 240 */ "exprlist ::=",
   101428  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
   101429  /* 242 */ "nexprlist ::= expr",
   101430  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
   101431  /* 244 */ "uniqueflag ::= UNIQUE",
   101432  /* 245 */ "uniqueflag ::=",
   101433  /* 246 */ "idxlist_opt ::=",
   101434  /* 247 */ "idxlist_opt ::= LP idxlist RP",
   101435  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
   101436  /* 249 */ "idxlist ::= nm collate sortorder",
   101437  /* 250 */ "collate ::=",
   101438  /* 251 */ "collate ::= COLLATE ids",
   101439  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
   101440  /* 253 */ "cmd ::= VACUUM",
   101441  /* 254 */ "cmd ::= VACUUM nm",
   101442  /* 255 */ "cmd ::= PRAGMA nm dbnm",
   101443  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
   101444  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
   101445  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
   101446  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
   101447  /* 260 */ "nmnum ::= plus_num",
   101448  /* 261 */ "nmnum ::= nm",
   101449  /* 262 */ "nmnum ::= ON",
   101450  /* 263 */ "nmnum ::= DELETE",
   101451  /* 264 */ "nmnum ::= DEFAULT",
   101452  /* 265 */ "plus_num ::= plus_opt number",
   101453  /* 266 */ "minus_num ::= MINUS number",
   101454  /* 267 */ "number ::= INTEGER|FLOAT",
   101455  /* 268 */ "plus_opt ::= PLUS",
   101456  /* 269 */ "plus_opt ::=",
   101457  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
   101458  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
   101459  /* 272 */ "trigger_time ::= BEFORE",
   101460  /* 273 */ "trigger_time ::= AFTER",
   101461  /* 274 */ "trigger_time ::= INSTEAD OF",
   101462  /* 275 */ "trigger_time ::=",
   101463  /* 276 */ "trigger_event ::= DELETE|INSERT",
   101464  /* 277 */ "trigger_event ::= UPDATE",
   101465  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
   101466  /* 279 */ "foreach_clause ::=",
   101467  /* 280 */ "foreach_clause ::= FOR EACH ROW",
   101468  /* 281 */ "when_clause ::=",
   101469  /* 282 */ "when_clause ::= WHEN expr",
   101470  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
   101471  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
   101472  /* 285 */ "trnm ::= nm",
   101473  /* 286 */ "trnm ::= nm DOT nm",
   101474  /* 287 */ "tridxby ::=",
   101475  /* 288 */ "tridxby ::= INDEXED BY nm",
   101476  /* 289 */ "tridxby ::= NOT INDEXED",
   101477  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
   101478  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
   101479  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
   101480  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
   101481  /* 294 */ "trigger_cmd ::= select",
   101482  /* 295 */ "expr ::= RAISE LP IGNORE RP",
   101483  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
   101484  /* 297 */ "raisetype ::= ROLLBACK",
   101485  /* 298 */ "raisetype ::= ABORT",
   101486  /* 299 */ "raisetype ::= FAIL",
   101487  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
   101488  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
   101489  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
   101490  /* 303 */ "key_opt ::=",
   101491  /* 304 */ "key_opt ::= KEY expr",
   101492  /* 305 */ "database_kw_opt ::= DATABASE",
   101493  /* 306 */ "database_kw_opt ::=",
   101494  /* 307 */ "cmd ::= REINDEX",
   101495  /* 308 */ "cmd ::= REINDEX nm dbnm",
   101496  /* 309 */ "cmd ::= ANALYZE",
   101497  /* 310 */ "cmd ::= ANALYZE nm dbnm",
   101498  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
   101499  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
   101500  /* 313 */ "add_column_fullname ::= fullname",
   101501  /* 314 */ "kwcolumn_opt ::=",
   101502  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
   101503  /* 316 */ "cmd ::= create_vtab",
   101504  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
   101505  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
   101506  /* 319 */ "vtabarglist ::= vtabarg",
   101507  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
   101508  /* 321 */ "vtabarg ::=",
   101509  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
   101510  /* 323 */ "vtabargtoken ::= ANY",
   101511  /* 324 */ "vtabargtoken ::= lp anylist RP",
   101512  /* 325 */ "lp ::= LP",
   101513  /* 326 */ "anylist ::=",
   101514  /* 327 */ "anylist ::= anylist LP anylist RP",
   101515  /* 328 */ "anylist ::= anylist ANY",
   101516 };
   101517 #endif /* NDEBUG */
   101518 
   101519 
   101520 #if YYSTACKDEPTH<=0
   101521 /*
   101522 ** Try to increase the size of the parser stack.
   101523 */
   101524 static void yyGrowStack(yyParser *p){
   101525   int newSize;
   101526   yyStackEntry *pNew;
   101527 
   101528   newSize = p->yystksz*2 + 100;
   101529   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
   101530   if( pNew ){
   101531     p->yystack = pNew;
   101532     p->yystksz = newSize;
   101533 #ifndef NDEBUG
   101534     if( yyTraceFILE ){
   101535       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
   101536               yyTracePrompt, p->yystksz);
   101537     }
   101538 #endif
   101539   }
   101540 }
   101541 #endif
   101542 
   101543 /*
   101544 ** This function allocates a new parser.
   101545 ** The only argument is a pointer to a function which works like
   101546 ** malloc.
   101547 **
   101548 ** Inputs:
   101549 ** A pointer to the function used to allocate memory.
   101550 **
   101551 ** Outputs:
   101552 ** A pointer to a parser.  This pointer is used in subsequent calls
   101553 ** to sqlite3Parser and sqlite3ParserFree.
   101554 */
   101555 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
   101556   yyParser *pParser;
   101557   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
   101558   if( pParser ){
   101559     pParser->yyidx = -1;
   101560 #ifdef YYTRACKMAXSTACKDEPTH
   101561     pParser->yyidxMax = 0;
   101562 #endif
   101563 #if YYSTACKDEPTH<=0
   101564     pParser->yystack = NULL;
   101565     pParser->yystksz = 0;
   101566     yyGrowStack(pParser);
   101567 #endif
   101568   }
   101569   return pParser;
   101570 }
   101571 
   101572 /* The following function deletes the value associated with a
   101573 ** symbol.  The symbol can be either a terminal or nonterminal.
   101574 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
   101575 ** the value.
   101576 */
   101577 static void yy_destructor(
   101578   yyParser *yypParser,    /* The parser */
   101579   YYCODETYPE yymajor,     /* Type code for object to destroy */
   101580   YYMINORTYPE *yypminor   /* The object to be destroyed */
   101581 ){
   101582   sqlite3ParserARG_FETCH;
   101583   switch( yymajor ){
   101584     /* Here is inserted the actions which take place when a
   101585     ** terminal or non-terminal is destroyed.  This can happen
   101586     ** when the symbol is popped from the stack during a
   101587     ** reduce or during error processing or when a parser is
   101588     ** being destroyed before it is finished parsing.
   101589     **
   101590     ** Note: during a reduce, the only symbols destroyed are those
   101591     ** which appear on the RHS of the rule, but which are not used
   101592     ** inside the C code.
   101593     */
   101594     case 160: /* select */
   101595     case 194: /* oneselect */
   101596 {
   101597 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
   101598 }
   101599       break;
   101600     case 174: /* term */
   101601     case 175: /* expr */
   101602 {
   101603 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
   101604 }
   101605       break;
   101606     case 179: /* idxlist_opt */
   101607     case 187: /* idxlist */
   101608     case 197: /* selcollist */
   101609     case 200: /* groupby_opt */
   101610     case 202: /* orderby_opt */
   101611     case 204: /* sclp */
   101612     case 214: /* sortlist */
   101613     case 216: /* nexprlist */
   101614     case 217: /* setlist */
   101615     case 220: /* itemlist */
   101616     case 221: /* exprlist */
   101617     case 226: /* case_exprlist */
   101618 {
   101619 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
   101620 }
   101621       break;
   101622     case 193: /* fullname */
   101623     case 198: /* from */
   101624     case 206: /* seltablist */
   101625     case 207: /* stl_prefix */
   101626 {
   101627 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
   101628 }
   101629       break;
   101630     case 199: /* where_opt */
   101631     case 201: /* having_opt */
   101632     case 210: /* on_opt */
   101633     case 215: /* sortitem */
   101634     case 225: /* case_operand */
   101635     case 227: /* case_else */
   101636     case 238: /* when_clause */
   101637     case 243: /* key_opt */
   101638 {
   101639 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
   101640 }
   101641       break;
   101642     case 211: /* using_opt */
   101643     case 213: /* inscollist */
   101644     case 219: /* inscollist_opt */
   101645 {
   101646 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
   101647 }
   101648       break;
   101649     case 234: /* trigger_cmd_list */
   101650     case 239: /* trigger_cmd */
   101651 {
   101652 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
   101653 }
   101654       break;
   101655     case 236: /* trigger_event */
   101656 {
   101657 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
   101658 }
   101659       break;
   101660     default:  break;   /* If no destructor action specified: do nothing */
   101661   }
   101662 }
   101663 
   101664 /*
   101665 ** Pop the parser's stack once.
   101666 **
   101667 ** If there is a destructor routine associated with the token which
   101668 ** is popped from the stack, then call it.
   101669 **
   101670 ** Return the major token number for the symbol popped.
   101671 */
   101672 static int yy_pop_parser_stack(yyParser *pParser){
   101673   YYCODETYPE yymajor;
   101674   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
   101675 
   101676   /* There is no mechanism by which the parser stack can be popped below
   101677   ** empty in SQLite.  */
   101678   if( NEVER(pParser->yyidx<0) ) return 0;
   101679 #ifndef NDEBUG
   101680   if( yyTraceFILE && pParser->yyidx>=0 ){
   101681     fprintf(yyTraceFILE,"%sPopping %s\n",
   101682       yyTracePrompt,
   101683       yyTokenName[yytos->major]);
   101684   }
   101685 #endif
   101686   yymajor = yytos->major;
   101687   yy_destructor(pParser, yymajor, &yytos->minor);
   101688   pParser->yyidx--;
   101689   return yymajor;
   101690 }
   101691 
   101692 /*
   101693 ** Deallocate and destroy a parser.  Destructors are all called for
   101694 ** all stack elements before shutting the parser down.
   101695 **
   101696 ** Inputs:
   101697 ** <ul>
   101698 ** <li>  A pointer to the parser.  This should be a pointer
   101699 **       obtained from sqlite3ParserAlloc.
   101700 ** <li>  A pointer to a function used to reclaim memory obtained
   101701 **       from malloc.
   101702 ** </ul>
   101703 */
   101704 SQLITE_PRIVATE void sqlite3ParserFree(
   101705   void *p,                    /* The parser to be deleted */
   101706   void (*freeProc)(void*)     /* Function used to reclaim memory */
   101707 ){
   101708   yyParser *pParser = (yyParser*)p;
   101709   /* In SQLite, we never try to destroy a parser that was not successfully
   101710   ** created in the first place. */
   101711   if( NEVER(pParser==0) ) return;
   101712   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
   101713 #if YYSTACKDEPTH<=0
   101714   free(pParser->yystack);
   101715 #endif
   101716   (*freeProc)((void*)pParser);
   101717 }
   101718 
   101719 /*
   101720 ** Return the peak depth of the stack for a parser.
   101721 */
   101722 #ifdef YYTRACKMAXSTACKDEPTH
   101723 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
   101724   yyParser *pParser = (yyParser*)p;
   101725   return pParser->yyidxMax;
   101726 }
   101727 #endif
   101728 
   101729 /*
   101730 ** Find the appropriate action for a parser given the terminal
   101731 ** look-ahead token iLookAhead.
   101732 **
   101733 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   101734 ** independent of the look-ahead.  If it is, return the action, otherwise
   101735 ** return YY_NO_ACTION.
   101736 */
   101737 static int yy_find_shift_action(
   101738   yyParser *pParser,        /* The parser */
   101739   YYCODETYPE iLookAhead     /* The look-ahead token */
   101740 ){
   101741   int i;
   101742   int stateno = pParser->yystack[pParser->yyidx].stateno;
   101743 
   101744   if( stateno>YY_SHIFT_COUNT
   101745    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
   101746     return yy_default[stateno];
   101747   }
   101748   assert( iLookAhead!=YYNOCODE );
   101749   i += iLookAhead;
   101750   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   101751     if( iLookAhead>0 ){
   101752 #ifdef YYFALLBACK
   101753       YYCODETYPE iFallback;            /* Fallback token */
   101754       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
   101755              && (iFallback = yyFallback[iLookAhead])!=0 ){
   101756 #ifndef NDEBUG
   101757         if( yyTraceFILE ){
   101758           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
   101759              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
   101760         }
   101761 #endif
   101762         return yy_find_shift_action(pParser, iFallback);
   101763       }
   101764 #endif
   101765 #ifdef YYWILDCARD
   101766       {
   101767         int j = i - iLookAhead + YYWILDCARD;
   101768         if(
   101769 #if YY_SHIFT_MIN+YYWILDCARD<0
   101770           j>=0 &&
   101771 #endif
   101772 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
   101773           j<YY_ACTTAB_COUNT &&
   101774 #endif
   101775           yy_lookahead[j]==YYWILDCARD
   101776         ){
   101777 #ifndef NDEBUG
   101778           if( yyTraceFILE ){
   101779             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
   101780                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
   101781           }
   101782 #endif /* NDEBUG */
   101783           return yy_action[j];
   101784         }
   101785       }
   101786 #endif /* YYWILDCARD */
   101787     }
   101788     return yy_default[stateno];
   101789   }else{
   101790     return yy_action[i];
   101791   }
   101792 }
   101793 
   101794 /*
   101795 ** Find the appropriate action for a parser given the non-terminal
   101796 ** look-ahead token iLookAhead.
   101797 **
   101798 ** If the look-ahead token is YYNOCODE, then check to see if the action is
   101799 ** independent of the look-ahead.  If it is, return the action, otherwise
   101800 ** return YY_NO_ACTION.
   101801 */
   101802 static int yy_find_reduce_action(
   101803   int stateno,              /* Current state number */
   101804   YYCODETYPE iLookAhead     /* The look-ahead token */
   101805 ){
   101806   int i;
   101807 #ifdef YYERRORSYMBOL
   101808   if( stateno>YY_REDUCE_COUNT ){
   101809     return yy_default[stateno];
   101810   }
   101811 #else
   101812   assert( stateno<=YY_REDUCE_COUNT );
   101813 #endif
   101814   i = yy_reduce_ofst[stateno];
   101815   assert( i!=YY_REDUCE_USE_DFLT );
   101816   assert( iLookAhead!=YYNOCODE );
   101817   i += iLookAhead;
   101818 #ifdef YYERRORSYMBOL
   101819   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
   101820     return yy_default[stateno];
   101821   }
   101822 #else
   101823   assert( i>=0 && i<YY_ACTTAB_COUNT );
   101824   assert( yy_lookahead[i]==iLookAhead );
   101825 #endif
   101826   return yy_action[i];
   101827 }
   101828 
   101829 /*
   101830 ** The following routine is called if the stack overflows.
   101831 */
   101832 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
   101833    sqlite3ParserARG_FETCH;
   101834    yypParser->yyidx--;
   101835 #ifndef NDEBUG
   101836    if( yyTraceFILE ){
   101837      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
   101838    }
   101839 #endif
   101840    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   101841    /* Here code is inserted which will execute if the parser
   101842    ** stack every overflows */
   101843 
   101844   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
   101845   sqlite3ErrorMsg(pParse, "parser stack overflow");
   101846   pParse->parseError = 1;
   101847    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
   101848 }
   101849 
   101850 /*
   101851 ** Perform a shift action.
   101852 */
   101853 static void yy_shift(
   101854   yyParser *yypParser,          /* The parser to be shifted */
   101855   int yyNewState,               /* The new state to shift in */
   101856   int yyMajor,                  /* The major token to shift in */
   101857   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
   101858 ){
   101859   yyStackEntry *yytos;
   101860   yypParser->yyidx++;
   101861 #ifdef YYTRACKMAXSTACKDEPTH
   101862   if( yypParser->yyidx>yypParser->yyidxMax ){
   101863     yypParser->yyidxMax = yypParser->yyidx;
   101864   }
   101865 #endif
   101866 #if YYSTACKDEPTH>0
   101867   if( yypParser->yyidx>=YYSTACKDEPTH ){
   101868     yyStackOverflow(yypParser, yypMinor);
   101869     return;
   101870   }
   101871 #else
   101872   if( yypParser->yyidx>=yypParser->yystksz ){
   101873     yyGrowStack(yypParser);
   101874     if( yypParser->yyidx>=yypParser->yystksz ){
   101875       yyStackOverflow(yypParser, yypMinor);
   101876       return;
   101877     }
   101878   }
   101879 #endif
   101880   yytos = &yypParser->yystack[yypParser->yyidx];
   101881   yytos->stateno = (YYACTIONTYPE)yyNewState;
   101882   yytos->major = (YYCODETYPE)yyMajor;
   101883   yytos->minor = *yypMinor;
   101884 #ifndef NDEBUG
   101885   if( yyTraceFILE && yypParser->yyidx>0 ){
   101886     int i;
   101887     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
   101888     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
   101889     for(i=1; i<=yypParser->yyidx; i++)
   101890       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
   101891     fprintf(yyTraceFILE,"\n");
   101892   }
   101893 #endif
   101894 }
   101895 
   101896 /* The following table contains information about every rule that
   101897 ** is used during the reduce.
   101898 */
   101899 static const struct {
   101900   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
   101901   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
   101902 } yyRuleInfo[] = {
   101903   { 142, 1 },
   101904   { 143, 2 },
   101905   { 143, 1 },
   101906   { 144, 1 },
   101907   { 144, 3 },
   101908   { 145, 0 },
   101909   { 145, 1 },
   101910   { 145, 3 },
   101911   { 146, 1 },
   101912   { 147, 3 },
   101913   { 149, 0 },
   101914   { 149, 1 },
   101915   { 149, 2 },
   101916   { 148, 0 },
   101917   { 148, 1 },
   101918   { 148, 1 },
   101919   { 148, 1 },
   101920   { 147, 2 },
   101921   { 147, 2 },
   101922   { 147, 2 },
   101923   { 151, 1 },
   101924   { 151, 0 },
   101925   { 147, 2 },
   101926   { 147, 3 },
   101927   { 147, 5 },
   101928   { 147, 2 },
   101929   { 152, 6 },
   101930   { 154, 1 },
   101931   { 156, 0 },
   101932   { 156, 3 },
   101933   { 155, 1 },
   101934   { 155, 0 },
   101935   { 153, 4 },
   101936   { 153, 2 },
   101937   { 158, 3 },
   101938   { 158, 1 },
   101939   { 161, 3 },
   101940   { 162, 1 },
   101941   { 165, 1 },
   101942   { 165, 1 },
   101943   { 166, 1 },
   101944   { 150, 1 },
   101945   { 150, 1 },
   101946   { 150, 1 },
   101947   { 163, 0 },
   101948   { 163, 1 },
   101949   { 167, 1 },
   101950   { 167, 4 },
   101951   { 167, 6 },
   101952   { 168, 1 },
   101953   { 168, 2 },
   101954   { 169, 1 },
   101955   { 169, 1 },
   101956   { 164, 2 },
   101957   { 164, 0 },
   101958   { 172, 3 },
   101959   { 172, 1 },
   101960   { 173, 2 },
   101961   { 173, 4 },
   101962   { 173, 3 },
   101963   { 173, 3 },
   101964   { 173, 2 },
   101965   { 173, 2 },
   101966   { 173, 3 },
   101967   { 173, 5 },
   101968   { 173, 2 },
   101969   { 173, 4 },
   101970   { 173, 4 },
   101971   { 173, 1 },
   101972   { 173, 2 },
   101973   { 178, 0 },
   101974   { 178, 1 },
   101975   { 180, 0 },
   101976   { 180, 2 },
   101977   { 182, 2 },
   101978   { 182, 3 },
   101979   { 182, 3 },
   101980   { 182, 3 },
   101981   { 183, 2 },
   101982   { 183, 2 },
   101983   { 183, 1 },
   101984   { 183, 1 },
   101985   { 183, 2 },
   101986   { 181, 3 },
   101987   { 181, 2 },
   101988   { 184, 0 },
   101989   { 184, 2 },
   101990   { 184, 2 },
   101991   { 159, 0 },
   101992   { 159, 2 },
   101993   { 185, 3 },
   101994   { 185, 2 },
   101995   { 185, 1 },
   101996   { 186, 2 },
   101997   { 186, 7 },
   101998   { 186, 5 },
   101999   { 186, 5 },
   102000   { 186, 10 },
   102001   { 188, 0 },
   102002   { 188, 1 },
   102003   { 176, 0 },
   102004   { 176, 3 },
   102005   { 189, 0 },
   102006   { 189, 2 },
   102007   { 190, 1 },
   102008   { 190, 1 },
   102009   { 190, 1 },
   102010   { 147, 4 },
   102011   { 192, 2 },
   102012   { 192, 0 },
   102013   { 147, 8 },
   102014   { 147, 4 },
   102015   { 147, 1 },
   102016   { 160, 1 },
   102017   { 160, 3 },
   102018   { 195, 1 },
   102019   { 195, 2 },
   102020   { 195, 1 },
   102021   { 194, 9 },
   102022   { 196, 1 },
   102023   { 196, 1 },
   102024   { 196, 0 },
   102025   { 204, 2 },
   102026   { 204, 0 },
   102027   { 197, 3 },
   102028   { 197, 2 },
   102029   { 197, 4 },
   102030   { 205, 2 },
   102031   { 205, 1 },
   102032   { 205, 0 },
   102033   { 198, 0 },
   102034   { 198, 2 },
   102035   { 207, 2 },
   102036   { 207, 0 },
   102037   { 206, 7 },
   102038   { 206, 7 },
   102039   { 206, 7 },
   102040   { 157, 0 },
   102041   { 157, 2 },
   102042   { 193, 2 },
   102043   { 208, 1 },
   102044   { 208, 2 },
   102045   { 208, 3 },
   102046   { 208, 4 },
   102047   { 210, 2 },
   102048   { 210, 0 },
   102049   { 209, 0 },
   102050   { 209, 3 },
   102051   { 209, 2 },
   102052   { 211, 4 },
   102053   { 211, 0 },
   102054   { 202, 0 },
   102055   { 202, 3 },
   102056   { 214, 4 },
   102057   { 214, 2 },
   102058   { 215, 1 },
   102059   { 177, 1 },
   102060   { 177, 1 },
   102061   { 177, 0 },
   102062   { 200, 0 },
   102063   { 200, 3 },
   102064   { 201, 0 },
   102065   { 201, 2 },
   102066   { 203, 0 },
   102067   { 203, 2 },
   102068   { 203, 4 },
   102069   { 203, 4 },
   102070   { 147, 5 },
   102071   { 199, 0 },
   102072   { 199, 2 },
   102073   { 147, 7 },
   102074   { 217, 5 },
   102075   { 217, 3 },
   102076   { 147, 8 },
   102077   { 147, 5 },
   102078   { 147, 6 },
   102079   { 218, 2 },
   102080   { 218, 1 },
   102081   { 220, 3 },
   102082   { 220, 1 },
   102083   { 219, 0 },
   102084   { 219, 3 },
   102085   { 213, 3 },
   102086   { 213, 1 },
   102087   { 175, 1 },
   102088   { 175, 3 },
   102089   { 174, 1 },
   102090   { 175, 1 },
   102091   { 175, 1 },
   102092   { 175, 3 },
   102093   { 175, 5 },
   102094   { 174, 1 },
   102095   { 174, 1 },
   102096   { 175, 1 },
   102097   { 175, 1 },
   102098   { 175, 3 },
   102099   { 175, 6 },
   102100   { 175, 5 },
   102101   { 175, 4 },
   102102   { 174, 1 },
   102103   { 175, 3 },
   102104   { 175, 3 },
   102105   { 175, 3 },
   102106   { 175, 3 },
   102107   { 175, 3 },
   102108   { 175, 3 },
   102109   { 175, 3 },
   102110   { 175, 3 },
   102111   { 222, 1 },
   102112   { 222, 2 },
   102113   { 222, 1 },
   102114   { 222, 2 },
   102115   { 175, 3 },
   102116   { 175, 5 },
   102117   { 175, 2 },
   102118   { 175, 3 },
   102119   { 175, 3 },
   102120   { 175, 4 },
   102121   { 175, 2 },
   102122   { 175, 2 },
   102123   { 175, 2 },
   102124   { 175, 2 },
   102125   { 223, 1 },
   102126   { 223, 2 },
   102127   { 175, 5 },
   102128   { 224, 1 },
   102129   { 224, 2 },
   102130   { 175, 5 },
   102131   { 175, 3 },
   102132   { 175, 5 },
   102133   { 175, 4 },
   102134   { 175, 4 },
   102135   { 175, 5 },
   102136   { 226, 5 },
   102137   { 226, 4 },
   102138   { 227, 2 },
   102139   { 227, 0 },
   102140   { 225, 1 },
   102141   { 225, 0 },
   102142   { 221, 1 },
   102143   { 221, 0 },
   102144   { 216, 3 },
   102145   { 216, 1 },
   102146   { 147, 11 },
   102147   { 228, 1 },
   102148   { 228, 0 },
   102149   { 179, 0 },
   102150   { 179, 3 },
   102151   { 187, 5 },
   102152   { 187, 3 },
   102153   { 229, 0 },
   102154   { 229, 2 },
   102155   { 147, 4 },
   102156   { 147, 1 },
   102157   { 147, 2 },
   102158   { 147, 3 },
   102159   { 147, 5 },
   102160   { 147, 6 },
   102161   { 147, 5 },
   102162   { 147, 6 },
   102163   { 230, 1 },
   102164   { 230, 1 },
   102165   { 230, 1 },
   102166   { 230, 1 },
   102167   { 230, 1 },
   102168   { 170, 2 },
   102169   { 171, 2 },
   102170   { 232, 1 },
   102171   { 231, 1 },
   102172   { 231, 0 },
   102173   { 147, 5 },
   102174   { 233, 11 },
   102175   { 235, 1 },
   102176   { 235, 1 },
   102177   { 235, 2 },
   102178   { 235, 0 },
   102179   { 236, 1 },
   102180   { 236, 1 },
   102181   { 236, 3 },
   102182   { 237, 0 },
   102183   { 237, 3 },
   102184   { 238, 0 },
   102185   { 238, 2 },
   102186   { 234, 3 },
   102187   { 234, 2 },
   102188   { 240, 1 },
   102189   { 240, 3 },
   102190   { 241, 0 },
   102191   { 241, 3 },
   102192   { 241, 2 },
   102193   { 239, 7 },
   102194   { 239, 8 },
   102195   { 239, 5 },
   102196   { 239, 5 },
   102197   { 239, 1 },
   102198   { 175, 4 },
   102199   { 175, 6 },
   102200   { 191, 1 },
   102201   { 191, 1 },
   102202   { 191, 1 },
   102203   { 147, 4 },
   102204   { 147, 6 },
   102205   { 147, 3 },
   102206   { 243, 0 },
   102207   { 243, 2 },
   102208   { 242, 1 },
   102209   { 242, 0 },
   102210   { 147, 1 },
   102211   { 147, 3 },
   102212   { 147, 1 },
   102213   { 147, 3 },
   102214   { 147, 6 },
   102215   { 147, 6 },
   102216   { 244, 1 },
   102217   { 245, 0 },
   102218   { 245, 1 },
   102219   { 147, 1 },
   102220   { 147, 4 },
   102221   { 246, 7 },
   102222   { 247, 1 },
   102223   { 247, 3 },
   102224   { 248, 0 },
   102225   { 248, 2 },
   102226   { 249, 1 },
   102227   { 249, 3 },
   102228   { 250, 1 },
   102229   { 251, 0 },
   102230   { 251, 4 },
   102231   { 251, 2 },
   102232 };
   102233 
   102234 static void yy_accept(yyParser*);  /* Forward Declaration */
   102235 
   102236 /*
   102237 ** Perform a reduce action and the shift that must immediately
   102238 ** follow the reduce.
   102239 */
   102240 static void yy_reduce(
   102241   yyParser *yypParser,         /* The parser */
   102242   int yyruleno                 /* Number of the rule by which to reduce */
   102243 ){
   102244   int yygoto;                     /* The next state */
   102245   int yyact;                      /* The next action */
   102246   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
   102247   yyStackEntry *yymsp;            /* The top of the parser's stack */
   102248   int yysize;                     /* Amount to pop the stack */
   102249   sqlite3ParserARG_FETCH;
   102250   yymsp = &yypParser->yystack[yypParser->yyidx];
   102251 #ifndef NDEBUG
   102252   if( yyTraceFILE && yyruleno>=0
   102253         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
   102254     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
   102255       yyRuleName[yyruleno]);
   102256   }
   102257 #endif /* NDEBUG */
   102258 
   102259   /* Silence complaints from purify about yygotominor being uninitialized
   102260   ** in some cases when it is copied into the stack after the following
   102261   ** switch.  yygotominor is uninitialized when a rule reduces that does
   102262   ** not set the value of its left-hand side nonterminal.  Leaving the
   102263   ** value of the nonterminal uninitialized is utterly harmless as long
   102264   ** as the value is never used.  So really the only thing this code
   102265   ** accomplishes is to quieten purify.
   102266   **
   102267   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
   102268   ** without this code, their parser segfaults.  I'm not sure what there
   102269   ** parser is doing to make this happen.  This is the second bug report
   102270   ** from wireshark this week.  Clearly they are stressing Lemon in ways
   102271   ** that it has not been previously stressed...  (SQLite ticket #2172)
   102272   */
   102273   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
   102274   yygotominor = yyzerominor;
   102275 
   102276 
   102277   switch( yyruleno ){
   102278   /* Beginning here are the reduction cases.  A typical example
   102279   ** follows:
   102280   **   case 0:
   102281   **  #line <lineno> <grammarfile>
   102282   **     { ... }           // User supplied code
   102283   **  #line <lineno> <thisfile>
   102284   **     break;
   102285   */
   102286       case 5: /* explain ::= */
   102287 { sqlite3BeginParse(pParse, 0); }
   102288         break;
   102289       case 6: /* explain ::= EXPLAIN */
   102290 { sqlite3BeginParse(pParse, 1); }
   102291         break;
   102292       case 7: /* explain ::= EXPLAIN QUERY PLAN */
   102293 { sqlite3BeginParse(pParse, 2); }
   102294         break;
   102295       case 8: /* cmdx ::= cmd */
   102296 { sqlite3FinishCoding(pParse); }
   102297         break;
   102298       case 9: /* cmd ::= BEGIN transtype trans_opt */
   102299 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
   102300         break;
   102301       case 13: /* transtype ::= */
   102302 {yygotominor.yy4 = TK_DEFERRED;}
   102303         break;
   102304       case 14: /* transtype ::= DEFERRED */
   102305       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
   102306       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
   102307       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
   102308       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
   102309 {yygotominor.yy4 = yymsp[0].major;}
   102310         break;
   102311       case 17: /* cmd ::= COMMIT trans_opt */
   102312       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
   102313 {sqlite3CommitTransaction(pParse);}
   102314         break;
   102315       case 19: /* cmd ::= ROLLBACK trans_opt */
   102316 {sqlite3RollbackTransaction(pParse);}
   102317         break;
   102318       case 22: /* cmd ::= SAVEPOINT nm */
   102319 {
   102320   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
   102321 }
   102322         break;
   102323       case 23: /* cmd ::= RELEASE savepoint_opt nm */
   102324 {
   102325   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
   102326 }
   102327         break;
   102328       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
   102329 {
   102330   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
   102331 }
   102332         break;
   102333       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
   102334 {
   102335    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
   102336 }
   102337         break;
   102338       case 27: /* createkw ::= CREATE */
   102339 {
   102340   pParse->db->lookaside.bEnabled = 0;
   102341   yygotominor.yy0 = yymsp[0].minor.yy0;
   102342 }
   102343         break;
   102344       case 28: /* ifnotexists ::= */
   102345       case 31: /* temp ::= */ yytestcase(yyruleno==31);
   102346       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
   102347       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
   102348       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
   102349       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
   102350       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
   102351       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
   102352       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
   102353       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
   102354       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
   102355       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
   102356 {yygotominor.yy4 = 0;}
   102357         break;
   102358       case 29: /* ifnotexists ::= IF NOT EXISTS */
   102359       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
   102360       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
   102361       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
   102362       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
   102363       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
   102364       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
   102365       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
   102366 {yygotominor.yy4 = 1;}
   102367         break;
   102368       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
   102369 {
   102370   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
   102371 }
   102372         break;
   102373       case 33: /* create_table_args ::= AS select */
   102374 {
   102375   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
   102376   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
   102377 }
   102378         break;
   102379       case 36: /* column ::= columnid type carglist */
   102380 {
   102381   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
   102382   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
   102383 }
   102384         break;
   102385       case 37: /* columnid ::= nm */
   102386 {
   102387   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
   102388   yygotominor.yy0 = yymsp[0].minor.yy0;
   102389 }
   102390         break;
   102391       case 38: /* id ::= ID */
   102392       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
   102393       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
   102394       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
   102395       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
   102396       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
   102397       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
   102398       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
   102399       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
   102400       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
   102401       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
   102402       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
   102403       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
   102404       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
   102405       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
   102406       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
   102407       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
   102408       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
   102409       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
   102410       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
   102411       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
   102412       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
   102413 {yygotominor.yy0 = yymsp[0].minor.yy0;}
   102414         break;
   102415       case 45: /* type ::= typetoken */
   102416 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
   102417         break;
   102418       case 47: /* typetoken ::= typename LP signed RP */
   102419 {
   102420   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
   102421   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
   102422 }
   102423         break;
   102424       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
   102425 {
   102426   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
   102427   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
   102428 }
   102429         break;
   102430       case 50: /* typename ::= typename ids */
   102431 {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);}
   102432         break;
   102433       case 57: /* ccons ::= DEFAULT term */
   102434       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
   102435 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
   102436         break;
   102437       case 58: /* ccons ::= DEFAULT LP expr RP */
   102438 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
   102439         break;
   102440       case 60: /* ccons ::= DEFAULT MINUS term */
   102441 {
   102442   ExprSpan v;
   102443   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
   102444   v.zStart = yymsp[-1].minor.yy0.z;
   102445   v.zEnd = yymsp[0].minor.yy118.zEnd;
   102446   sqlite3AddDefaultValue(pParse,&v);
   102447 }
   102448         break;
   102449       case 61: /* ccons ::= DEFAULT id */
   102450 {
   102451   ExprSpan v;
   102452   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
   102453   sqlite3AddDefaultValue(pParse,&v);
   102454 }
   102455         break;
   102456       case 63: /* ccons ::= NOT NULL onconf */
   102457 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
   102458         break;
   102459       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
   102460 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
   102461         break;
   102462       case 65: /* ccons ::= UNIQUE onconf */
   102463 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
   102464         break;
   102465       case 66: /* ccons ::= CHECK LP expr RP */
   102466 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
   102467         break;
   102468       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
   102469 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
   102470         break;
   102471       case 68: /* ccons ::= defer_subclause */
   102472 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
   102473         break;
   102474       case 69: /* ccons ::= COLLATE ids */
   102475 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
   102476         break;
   102477       case 72: /* refargs ::= */
   102478 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
   102479         break;
   102480       case 73: /* refargs ::= refargs refarg */
   102481 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
   102482         break;
   102483       case 74: /* refarg ::= MATCH nm */
   102484       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
   102485 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
   102486         break;
   102487       case 76: /* refarg ::= ON DELETE refact */
   102488 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
   102489         break;
   102490       case 77: /* refarg ::= ON UPDATE refact */
   102491 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
   102492         break;
   102493       case 78: /* refact ::= SET NULL */
   102494 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
   102495         break;
   102496       case 79: /* refact ::= SET DEFAULT */
   102497 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
   102498         break;
   102499       case 80: /* refact ::= CASCADE */
   102500 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
   102501         break;
   102502       case 81: /* refact ::= RESTRICT */
   102503 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
   102504         break;
   102505       case 82: /* refact ::= NO ACTION */
   102506 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
   102507         break;
   102508       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
   102509       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
   102510       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
   102511       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
   102512 {yygotominor.yy4 = yymsp[0].minor.yy4;}
   102513         break;
   102514       case 88: /* conslist_opt ::= */
   102515 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
   102516         break;
   102517       case 89: /* conslist_opt ::= COMMA conslist */
   102518 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
   102519         break;
   102520       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
   102521 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
   102522         break;
   102523       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
   102524 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
   102525         break;
   102526       case 96: /* tcons ::= CHECK LP expr RP onconf */
   102527 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
   102528         break;
   102529       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
   102530 {
   102531     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
   102532     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
   102533 }
   102534         break;
   102535       case 100: /* onconf ::= */
   102536 {yygotominor.yy4 = OE_Default;}
   102537         break;
   102538       case 102: /* orconf ::= */
   102539 {yygotominor.yy210 = OE_Default;}
   102540         break;
   102541       case 103: /* orconf ::= OR resolvetype */
   102542 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
   102543         break;
   102544       case 105: /* resolvetype ::= IGNORE */
   102545 {yygotominor.yy4 = OE_Ignore;}
   102546         break;
   102547       case 106: /* resolvetype ::= REPLACE */
   102548 {yygotominor.yy4 = OE_Replace;}
   102549         break;
   102550       case 107: /* cmd ::= DROP TABLE ifexists fullname */
   102551 {
   102552   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
   102553 }
   102554         break;
   102555       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
   102556 {
   102557   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
   102558 }
   102559         break;
   102560       case 111: /* cmd ::= DROP VIEW ifexists fullname */
   102561 {
   102562   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
   102563 }
   102564         break;
   102565       case 112: /* cmd ::= select */
   102566 {
   102567   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
   102568   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
   102569   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
   102570 }
   102571         break;
   102572       case 113: /* select ::= oneselect */
   102573 {yygotominor.yy387 = yymsp[0].minor.yy387;}
   102574         break;
   102575       case 114: /* select ::= select multiselect_op oneselect */
   102576 {
   102577   if( yymsp[0].minor.yy387 ){
   102578     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
   102579     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
   102580   }else{
   102581     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
   102582   }
   102583   yygotominor.yy387 = yymsp[0].minor.yy387;
   102584 }
   102585         break;
   102586       case 116: /* multiselect_op ::= UNION ALL */
   102587 {yygotominor.yy4 = TK_ALL;}
   102588         break;
   102589       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
   102590 {
   102591   yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
   102592 }
   102593         break;
   102594       case 122: /* sclp ::= selcollist COMMA */
   102595       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
   102596 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
   102597         break;
   102598       case 123: /* sclp ::= */
   102599       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
   102600       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
   102601       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
   102602       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
   102603 {yygotominor.yy322 = 0;}
   102604         break;
   102605       case 124: /* selcollist ::= sclp expr as */
   102606 {
   102607    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
   102608    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
   102609    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
   102610 }
   102611         break;
   102612       case 125: /* selcollist ::= sclp STAR */
   102613 {
   102614   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
   102615   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
   102616 }
   102617         break;
   102618       case 126: /* selcollist ::= sclp nm DOT STAR */
   102619 {
   102620   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
   102621   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   102622   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
   102623   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
   102624 }
   102625         break;
   102626       case 129: /* as ::= */
   102627 {yygotominor.yy0.n = 0;}
   102628         break;
   102629       case 130: /* from ::= */
   102630 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
   102631         break;
   102632       case 131: /* from ::= FROM seltablist */
   102633 {
   102634   yygotominor.yy259 = yymsp[0].minor.yy259;
   102635   sqlite3SrcListShiftJoinType(yygotominor.yy259);
   102636 }
   102637         break;
   102638       case 132: /* stl_prefix ::= seltablist joinop */
   102639 {
   102640    yygotominor.yy259 = yymsp[-1].minor.yy259;
   102641    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
   102642 }
   102643         break;
   102644       case 133: /* stl_prefix ::= */
   102645 {yygotominor.yy259 = 0;}
   102646         break;
   102647       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
   102648 {
   102649   yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   102650   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
   102651 }
   102652         break;
   102653       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
   102654 {
   102655     yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   102656   }
   102657         break;
   102658       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
   102659 {
   102660     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
   102661       yygotominor.yy259 = yymsp[-4].minor.yy259;
   102662     }else{
   102663       Select *pSubquery;
   102664       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
   102665       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
   102666       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
   102667     }
   102668   }
   102669         break;
   102670       case 137: /* dbnm ::= */
   102671       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
   102672 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
   102673         break;
   102674       case 139: /* fullname ::= nm dbnm */
   102675 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
   102676         break;
   102677       case 140: /* joinop ::= COMMA|JOIN */
   102678 { yygotominor.yy4 = JT_INNER; }
   102679         break;
   102680       case 141: /* joinop ::= JOIN_KW JOIN */
   102681 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
   102682         break;
   102683       case 142: /* joinop ::= JOIN_KW nm JOIN */
   102684 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
   102685         break;
   102686       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
   102687 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
   102688         break;
   102689       case 144: /* on_opt ::= ON expr */
   102690       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
   102691       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
   102692       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
   102693       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
   102694       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
   102695 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
   102696         break;
   102697       case 145: /* on_opt ::= */
   102698       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
   102699       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
   102700       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
   102701       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
   102702 {yygotominor.yy314 = 0;}
   102703         break;
   102704       case 148: /* indexed_opt ::= NOT INDEXED */
   102705 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
   102706         break;
   102707       case 149: /* using_opt ::= USING LP inscollist RP */
   102708       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
   102709 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
   102710         break;
   102711       case 150: /* using_opt ::= */
   102712       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
   102713 {yygotominor.yy384 = 0;}
   102714         break;
   102715       case 152: /* orderby_opt ::= ORDER BY sortlist */
   102716       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
   102717       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
   102718 {yygotominor.yy322 = yymsp[0].minor.yy322;}
   102719         break;
   102720       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
   102721 {
   102722   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
   102723   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
   102724 }
   102725         break;
   102726       case 154: /* sortlist ::= sortitem sortorder */
   102727 {
   102728   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
   102729   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
   102730 }
   102731         break;
   102732       case 156: /* sortorder ::= ASC */
   102733       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
   102734 {yygotominor.yy4 = SQLITE_SO_ASC;}
   102735         break;
   102736       case 157: /* sortorder ::= DESC */
   102737 {yygotominor.yy4 = SQLITE_SO_DESC;}
   102738         break;
   102739       case 163: /* limit_opt ::= */
   102740 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
   102741         break;
   102742       case 164: /* limit_opt ::= LIMIT expr */
   102743 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
   102744         break;
   102745       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
   102746 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
   102747         break;
   102748       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
   102749 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
   102750         break;
   102751       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
   102752 {
   102753   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
   102754   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
   102755 }
   102756         break;
   102757       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
   102758 {
   102759   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
   102760   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
   102761   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
   102762 }
   102763         break;
   102764       case 171: /* setlist ::= setlist COMMA nm EQ expr */
   102765 {
   102766   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
   102767   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
   102768 }
   102769         break;
   102770       case 172: /* setlist ::= nm EQ expr */
   102771 {
   102772   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
   102773   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
   102774 }
   102775         break;
   102776       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
   102777 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
   102778         break;
   102779       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
   102780 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
   102781         break;
   102782       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
   102783 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
   102784         break;
   102785       case 176: /* insert_cmd ::= INSERT orconf */
   102786 {yygotominor.yy210 = yymsp[0].minor.yy210;}
   102787         break;
   102788       case 177: /* insert_cmd ::= REPLACE */
   102789 {yygotominor.yy210 = OE_Replace;}
   102790         break;
   102791       case 178: /* itemlist ::= itemlist COMMA expr */
   102792       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
   102793 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
   102794         break;
   102795       case 179: /* itemlist ::= expr */
   102796       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
   102797 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
   102798         break;
   102799       case 182: /* inscollist ::= inscollist COMMA nm */
   102800 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
   102801         break;
   102802       case 183: /* inscollist ::= nm */
   102803 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
   102804         break;
   102805       case 184: /* expr ::= term */
   102806 {yygotominor.yy118 = yymsp[0].minor.yy118;}
   102807         break;
   102808       case 185: /* expr ::= LP expr RP */
   102809 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
   102810         break;
   102811       case 186: /* term ::= NULL */
   102812       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
   102813       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
   102814 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
   102815         break;
   102816       case 187: /* expr ::= id */
   102817       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
   102818 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
   102819         break;
   102820       case 189: /* expr ::= nm DOT nm */
   102821 {
   102822   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   102823   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   102824   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
   102825   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
   102826 }
   102827         break;
   102828       case 190: /* expr ::= nm DOT nm DOT nm */
   102829 {
   102830   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
   102831   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
   102832   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
   102833   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
   102834   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
   102835   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   102836 }
   102837         break;
   102838       case 193: /* expr ::= REGISTER */
   102839 {
   102840   /* When doing a nested parse, one can include terms in an expression
   102841   ** that look like this:   #1 #2 ...  These terms refer to registers
   102842   ** in the virtual machine.  #N is the N-th register. */
   102843   if( pParse->nested==0 ){
   102844     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
   102845     yygotominor.yy118.pExpr = 0;
   102846   }else{
   102847     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
   102848     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
   102849   }
   102850   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   102851 }
   102852         break;
   102853       case 194: /* expr ::= VARIABLE */
   102854 {
   102855   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
   102856   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
   102857   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   102858 }
   102859         break;
   102860       case 195: /* expr ::= expr COLLATE ids */
   102861 {
   102862   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
   102863   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
   102864   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   102865 }
   102866         break;
   102867       case 196: /* expr ::= CAST LP expr AS typetoken RP */
   102868 {
   102869   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
   102870   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
   102871 }
   102872         break;
   102873       case 197: /* expr ::= ID LP distinct exprlist RP */
   102874 {
   102875   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
   102876     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
   102877   }
   102878   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
   102879   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
   102880   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
   102881     yygotominor.yy118.pExpr->flags |= EP_Distinct;
   102882   }
   102883 }
   102884         break;
   102885       case 198: /* expr ::= ID LP STAR RP */
   102886 {
   102887   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
   102888   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
   102889 }
   102890         break;
   102891       case 199: /* term ::= CTIME_KW */
   102892 {
   102893   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
   102894   ** treated as functions that return constants */
   102895   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
   102896   if( yygotominor.yy118.pExpr ){
   102897     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
   102898   }
   102899   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
   102900 }
   102901         break;
   102902       case 200: /* expr ::= expr AND expr */
   102903       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
   102904       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
   102905       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
   102906       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
   102907       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
   102908       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
   102909       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
   102910 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
   102911         break;
   102912       case 208: /* likeop ::= LIKE_KW */
   102913       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
   102914 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
   102915         break;
   102916       case 209: /* likeop ::= NOT LIKE_KW */
   102917       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
   102918 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
   102919         break;
   102920       case 212: /* expr ::= expr likeop expr */
   102921 {
   102922   ExprList *pList;
   102923   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
   102924   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
   102925   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
   102926   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   102927   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
   102928   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
   102929   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
   102930 }
   102931         break;
   102932       case 213: /* expr ::= expr likeop expr ESCAPE expr */
   102933 {
   102934   ExprList *pList;
   102935   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
   102936   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
   102937   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
   102938   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
   102939   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   102940   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
   102941   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
   102942   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
   102943 }
   102944         break;
   102945       case 214: /* expr ::= expr ISNULL|NOTNULL */
   102946 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
   102947         break;
   102948       case 215: /* expr ::= expr NOT NULL */
   102949 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
   102950         break;
   102951       case 216: /* expr ::= expr IS expr */
   102952 {
   102953   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
   102954   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
   102955 }
   102956         break;
   102957       case 217: /* expr ::= expr IS NOT expr */
   102958 {
   102959   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
   102960   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
   102961 }
   102962         break;
   102963       case 218: /* expr ::= NOT expr */
   102964       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
   102965 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
   102966         break;
   102967       case 220: /* expr ::= MINUS expr */
   102968 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
   102969         break;
   102970       case 221: /* expr ::= PLUS expr */
   102971 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
   102972         break;
   102973       case 224: /* expr ::= expr between_op expr AND expr */
   102974 {
   102975   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
   102976   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
   102977   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
   102978   if( yygotominor.yy118.pExpr ){
   102979     yygotominor.yy118.pExpr->x.pList = pList;
   102980   }else{
   102981     sqlite3ExprListDelete(pParse->db, pList);
   102982   }
   102983   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   102984   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
   102985   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
   102986 }
   102987         break;
   102988       case 227: /* expr ::= expr in_op LP exprlist RP */
   102989 {
   102990     if( yymsp[-1].minor.yy322==0 ){
   102991       /* Expressions of the form
   102992       **
   102993       **      expr1 IN ()
   102994       **      expr1 NOT IN ()
   102995       **
   102996       ** simplify to constants 0 (false) and 1 (true), respectively,
   102997       ** regardless of the value of expr1.
   102998       */
   102999       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
   103000       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
   103001     }else{
   103002       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
   103003       if( yygotominor.yy118.pExpr ){
   103004         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
   103005         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
   103006       }else{
   103007         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
   103008       }
   103009       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   103010     }
   103011     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
   103012     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103013   }
   103014         break;
   103015       case 228: /* expr ::= LP select RP */
   103016 {
   103017     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
   103018     if( yygotominor.yy118.pExpr ){
   103019       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
   103020       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
   103021       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
   103022     }else{
   103023       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
   103024     }
   103025     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
   103026     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103027   }
   103028         break;
   103029       case 229: /* expr ::= expr in_op LP select RP */
   103030 {
   103031     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
   103032     if( yygotominor.yy118.pExpr ){
   103033       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
   103034       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
   103035       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
   103036     }else{
   103037       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
   103038     }
   103039     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   103040     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
   103041     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103042   }
   103043         break;
   103044       case 230: /* expr ::= expr in_op nm dbnm */
   103045 {
   103046     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
   103047     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
   103048     if( yygotominor.yy118.pExpr ){
   103049       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
   103050       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
   103051       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
   103052     }else{
   103053       sqlite3SrcListDelete(pParse->db, pSrc);
   103054     }
   103055     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
   103056     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
   103057     yygotominor.yy118.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];
   103058   }
   103059         break;
   103060       case 231: /* expr ::= EXISTS LP select RP */
   103061 {
   103062     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
   103063     if( p ){
   103064       p->x.pSelect = yymsp[-1].minor.yy387;
   103065       ExprSetProperty(p, EP_xIsSelect);
   103066       sqlite3ExprSetHeight(pParse, p);
   103067     }else{
   103068       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
   103069     }
   103070     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
   103071     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103072   }
   103073         break;
   103074       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
   103075 {
   103076   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
   103077   if( yygotominor.yy118.pExpr ){
   103078     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
   103079     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
   103080   }else{
   103081     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
   103082   }
   103083   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
   103084   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103085 }
   103086         break;
   103087       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
   103088 {
   103089   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
   103090   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
   103091 }
   103092         break;
   103093       case 234: /* case_exprlist ::= WHEN expr THEN expr */
   103094 {
   103095   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
   103096   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
   103097 }
   103098         break;
   103099       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
   103100 {
   103101   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
   103102                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
   103103                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
   103104 }
   103105         break;
   103106       case 244: /* uniqueflag ::= UNIQUE */
   103107       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
   103108 {yygotominor.yy4 = OE_Abort;}
   103109         break;
   103110       case 245: /* uniqueflag ::= */
   103111 {yygotominor.yy4 = OE_None;}
   103112         break;
   103113       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
   103114 {
   103115   Expr *p = 0;
   103116   if( yymsp[-1].minor.yy0.n>0 ){
   103117     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
   103118     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   103119   }
   103120   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
   103121   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
   103122   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
   103123   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
   103124 }
   103125         break;
   103126       case 249: /* idxlist ::= nm collate sortorder */
   103127 {
   103128   Expr *p = 0;
   103129   if( yymsp[-1].minor.yy0.n>0 ){
   103130     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
   103131     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
   103132   }
   103133   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
   103134   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
   103135   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
   103136   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
   103137 }
   103138         break;
   103139       case 250: /* collate ::= */
   103140 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
   103141         break;
   103142       case 252: /* cmd ::= DROP INDEX ifexists fullname */
   103143 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
   103144         break;
   103145       case 253: /* cmd ::= VACUUM */
   103146       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
   103147 {sqlite3Vacuum(pParse);}
   103148         break;
   103149       case 255: /* cmd ::= PRAGMA nm dbnm */
   103150 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
   103151         break;
   103152       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
   103153 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
   103154         break;
   103155       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
   103156 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
   103157         break;
   103158       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
   103159 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
   103160         break;
   103161       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
   103162 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
   103163         break;
   103164       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
   103165 {
   103166   Token all;
   103167   all.z = yymsp[-3].minor.yy0.z;
   103168   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
   103169   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
   103170 }
   103171         break;
   103172       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
   103173 {
   103174   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
   103175   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
   103176 }
   103177         break;
   103178       case 272: /* trigger_time ::= BEFORE */
   103179       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
   103180 { yygotominor.yy4 = TK_BEFORE; }
   103181         break;
   103182       case 273: /* trigger_time ::= AFTER */
   103183 { yygotominor.yy4 = TK_AFTER;  }
   103184         break;
   103185       case 274: /* trigger_time ::= INSTEAD OF */
   103186 { yygotominor.yy4 = TK_INSTEAD;}
   103187         break;
   103188       case 276: /* trigger_event ::= DELETE|INSERT */
   103189       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
   103190 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
   103191         break;
   103192       case 278: /* trigger_event ::= UPDATE OF inscollist */
   103193 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
   103194         break;
   103195       case 281: /* when_clause ::= */
   103196       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
   103197 { yygotominor.yy314 = 0; }
   103198         break;
   103199       case 282: /* when_clause ::= WHEN expr */
   103200       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
   103201 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
   103202         break;
   103203       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
   103204 {
   103205   assert( yymsp[-2].minor.yy203!=0 );
   103206   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
   103207   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
   103208   yygotominor.yy203 = yymsp[-2].minor.yy203;
   103209 }
   103210         break;
   103211       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
   103212 {
   103213   assert( yymsp[-1].minor.yy203!=0 );
   103214   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
   103215   yygotominor.yy203 = yymsp[-1].minor.yy203;
   103216 }
   103217         break;
   103218       case 286: /* trnm ::= nm DOT nm */
   103219 {
   103220   yygotominor.yy0 = yymsp[0].minor.yy0;
   103221   sqlite3ErrorMsg(pParse,
   103222         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
   103223         "statements within triggers");
   103224 }
   103225         break;
   103226       case 288: /* tridxby ::= INDEXED BY nm */
   103227 {
   103228   sqlite3ErrorMsg(pParse,
   103229         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
   103230         "within triggers");
   103231 }
   103232         break;
   103233       case 289: /* tridxby ::= NOT INDEXED */
   103234 {
   103235   sqlite3ErrorMsg(pParse,
   103236         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
   103237         "within triggers");
   103238 }
   103239         break;
   103240       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
   103241 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
   103242         break;
   103243       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
   103244 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
   103245         break;
   103246       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
   103247 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
   103248         break;
   103249       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
   103250 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
   103251         break;
   103252       case 294: /* trigger_cmd ::= select */
   103253 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
   103254         break;
   103255       case 295: /* expr ::= RAISE LP IGNORE RP */
   103256 {
   103257   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
   103258   if( yygotominor.yy118.pExpr ){
   103259     yygotominor.yy118.pExpr->affinity = OE_Ignore;
   103260   }
   103261   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
   103262   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103263 }
   103264         break;
   103265       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
   103266 {
   103267   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
   103268   if( yygotominor.yy118.pExpr ) {
   103269     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
   103270   }
   103271   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
   103272   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
   103273 }
   103274         break;
   103275       case 297: /* raisetype ::= ROLLBACK */
   103276 {yygotominor.yy4 = OE_Rollback;}
   103277         break;
   103278       case 299: /* raisetype ::= FAIL */
   103279 {yygotominor.yy4 = OE_Fail;}
   103280         break;
   103281       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
   103282 {
   103283   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
   103284 }
   103285         break;
   103286       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
   103287 {
   103288   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
   103289 }
   103290         break;
   103291       case 302: /* cmd ::= DETACH database_kw_opt expr */
   103292 {
   103293   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
   103294 }
   103295         break;
   103296       case 307: /* cmd ::= REINDEX */
   103297 {sqlite3Reindex(pParse, 0, 0);}
   103298         break;
   103299       case 308: /* cmd ::= REINDEX nm dbnm */
   103300 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   103301         break;
   103302       case 309: /* cmd ::= ANALYZE */
   103303 {sqlite3Analyze(pParse, 0, 0);}
   103304         break;
   103305       case 310: /* cmd ::= ANALYZE nm dbnm */
   103306 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
   103307         break;
   103308       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
   103309 {
   103310   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
   103311 }
   103312         break;
   103313       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
   103314 {
   103315   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
   103316 }
   103317         break;
   103318       case 313: /* add_column_fullname ::= fullname */
   103319 {
   103320   pParse->db->lookaside.bEnabled = 0;
   103321   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
   103322 }
   103323         break;
   103324       case 316: /* cmd ::= create_vtab */
   103325 {sqlite3VtabFinishParse(pParse,0);}
   103326         break;
   103327       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
   103328 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
   103329         break;
   103330       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
   103331 {
   103332     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
   103333 }
   103334         break;
   103335       case 321: /* vtabarg ::= */
   103336 {sqlite3VtabArgInit(pParse);}
   103337         break;
   103338       case 323: /* vtabargtoken ::= ANY */
   103339       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
   103340       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
   103341 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
   103342         break;
   103343       default:
   103344       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
   103345       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
   103346       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
   103347       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
   103348       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
   103349       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
   103350       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
   103351       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
   103352       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
   103353       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
   103354       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
   103355       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
   103356       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
   103357       /* (44) type ::= */ yytestcase(yyruleno==44);
   103358       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
   103359       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
   103360       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
   103361       /* (54) carglist ::= */ yytestcase(yyruleno==54);
   103362       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
   103363       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
   103364       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
   103365       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
   103366       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
   103367       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
   103368       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
   103369       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
   103370       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
   103371       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
   103372       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
   103373       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
   103374       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
   103375       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
   103376       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
   103377       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
   103378       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
   103379       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
   103380       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
   103381       /* (326) anylist ::= */ yytestcase(yyruleno==326);
   103382       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
   103383       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
   103384         break;
   103385   };
   103386   yygoto = yyRuleInfo[yyruleno].lhs;
   103387   yysize = yyRuleInfo[yyruleno].nrhs;
   103388   yypParser->yyidx -= yysize;
   103389   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
   103390   if( yyact < YYNSTATE ){
   103391 #ifdef NDEBUG
   103392     /* If we are not debugging and the reduce action popped at least
   103393     ** one element off the stack, then we can push the new element back
   103394     ** onto the stack here, and skip the stack overflow test in yy_shift().
   103395     ** That gives a significant speed improvement. */
   103396     if( yysize ){
   103397       yypParser->yyidx++;
   103398       yymsp -= yysize-1;
   103399       yymsp->stateno = (YYACTIONTYPE)yyact;
   103400       yymsp->major = (YYCODETYPE)yygoto;
   103401       yymsp->minor = yygotominor;
   103402     }else
   103403 #endif
   103404     {
   103405       yy_shift(yypParser,yyact,yygoto,&yygotominor);
   103406     }
   103407   }else{
   103408     assert( yyact == YYNSTATE + YYNRULE + 1 );
   103409     yy_accept(yypParser);
   103410   }
   103411 }
   103412 
   103413 /*
   103414 ** The following code executes when the parse fails
   103415 */
   103416 #ifndef YYNOERRORRECOVERY
   103417 static void yy_parse_failed(
   103418   yyParser *yypParser           /* The parser */
   103419 ){
   103420   sqlite3ParserARG_FETCH;
   103421 #ifndef NDEBUG
   103422   if( yyTraceFILE ){
   103423     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
   103424   }
   103425 #endif
   103426   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   103427   /* Here code is inserted which will be executed whenever the
   103428   ** parser fails */
   103429   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   103430 }
   103431 #endif /* YYNOERRORRECOVERY */
   103432 
   103433 /*
   103434 ** The following code executes when a syntax error first occurs.
   103435 */
   103436 static void yy_syntax_error(
   103437   yyParser *yypParser,           /* The parser */
   103438   int yymajor,                   /* The major type of the error token */
   103439   YYMINORTYPE yyminor            /* The minor type of the error token */
   103440 ){
   103441   sqlite3ParserARG_FETCH;
   103442 #define TOKEN (yyminor.yy0)
   103443 
   103444   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
   103445   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
   103446   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
   103447   pParse->parseError = 1;
   103448   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   103449 }
   103450 
   103451 /*
   103452 ** The following is executed when the parser accepts
   103453 */
   103454 static void yy_accept(
   103455   yyParser *yypParser           /* The parser */
   103456 ){
   103457   sqlite3ParserARG_FETCH;
   103458 #ifndef NDEBUG
   103459   if( yyTraceFILE ){
   103460     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
   103461   }
   103462 #endif
   103463   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
   103464   /* Here code is inserted which will be executed whenever the
   103465   ** parser accepts */
   103466   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
   103467 }
   103468 
   103469 /* The main parser program.
   103470 ** The first argument is a pointer to a structure obtained from
   103471 ** "sqlite3ParserAlloc" which describes the current state of the parser.
   103472 ** The second argument is the major token number.  The third is
   103473 ** the minor token.  The fourth optional argument is whatever the
   103474 ** user wants (and specified in the grammar) and is available for
   103475 ** use by the action routines.
   103476 **
   103477 ** Inputs:
   103478 ** <ul>
   103479 ** <li> A pointer to the parser (an opaque structure.)
   103480 ** <li> The major token number.
   103481 ** <li> The minor token number.
   103482 ** <li> An option argument of a grammar-specified type.
   103483 ** </ul>
   103484 **
   103485 ** Outputs:
   103486 ** None.
   103487 */
   103488 SQLITE_PRIVATE void sqlite3Parser(
   103489   void *yyp,                   /* The parser */
   103490   int yymajor,                 /* The major token code number */
   103491   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
   103492   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
   103493 ){
   103494   YYMINORTYPE yyminorunion;
   103495   int yyact;            /* The parser action. */
   103496   int yyendofinput;     /* True if we are at the end of input */
   103497 #ifdef YYERRORSYMBOL
   103498   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
   103499 #endif
   103500   yyParser *yypParser;  /* The parser */
   103501 
   103502   /* (re)initialize the parser, if necessary */
   103503   yypParser = (yyParser*)yyp;
   103504   if( yypParser->yyidx<0 ){
   103505 #if YYSTACKDEPTH<=0
   103506     if( yypParser->yystksz <=0 ){
   103507       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
   103508       yyminorunion = yyzerominor;
   103509       yyStackOverflow(yypParser, &yyminorunion);
   103510       return;
   103511     }
   103512 #endif
   103513     yypParser->yyidx = 0;
   103514     yypParser->yyerrcnt = -1;
   103515     yypParser->yystack[0].stateno = 0;
   103516     yypParser->yystack[0].major = 0;
   103517   }
   103518   yyminorunion.yy0 = yyminor;
   103519   yyendofinput = (yymajor==0);
   103520   sqlite3ParserARG_STORE;
   103521 
   103522 #ifndef NDEBUG
   103523   if( yyTraceFILE ){
   103524     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
   103525   }
   103526 #endif
   103527 
   103528   do{
   103529     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
   103530     if( yyact<YYNSTATE ){
   103531       assert( !yyendofinput );  /* Impossible to shift the $ token */
   103532       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
   103533       yypParser->yyerrcnt--;
   103534       yymajor = YYNOCODE;
   103535     }else if( yyact < YYNSTATE + YYNRULE ){
   103536       yy_reduce(yypParser,yyact-YYNSTATE);
   103537     }else{
   103538       assert( yyact == YY_ERROR_ACTION );
   103539 #ifdef YYERRORSYMBOL
   103540       int yymx;
   103541 #endif
   103542 #ifndef NDEBUG
   103543       if( yyTraceFILE ){
   103544         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
   103545       }
   103546 #endif
   103547 #ifdef YYERRORSYMBOL
   103548       /* A syntax error has occurred.
   103549       ** The response to an error depends upon whether or not the
   103550       ** grammar defines an error token "ERROR".
   103551       **
   103552       ** This is what we do if the grammar does define ERROR:
   103553       **
   103554       **  * Call the %syntax_error function.
   103555       **
   103556       **  * Begin popping the stack until we enter a state where
   103557       **    it is legal to shift the error symbol, then shift
   103558       **    the error symbol.
   103559       **
   103560       **  * Set the error count to three.
   103561       **
   103562       **  * Begin accepting and shifting new tokens.  No new error
   103563       **    processing will occur until three tokens have been
   103564       **    shifted successfully.
   103565       **
   103566       */
   103567       if( yypParser->yyerrcnt<0 ){
   103568         yy_syntax_error(yypParser,yymajor,yyminorunion);
   103569       }
   103570       yymx = yypParser->yystack[yypParser->yyidx].major;
   103571       if( yymx==YYERRORSYMBOL || yyerrorhit ){
   103572 #ifndef NDEBUG
   103573         if( yyTraceFILE ){
   103574           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
   103575              yyTracePrompt,yyTokenName[yymajor]);
   103576         }
   103577 #endif
   103578         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
   103579         yymajor = YYNOCODE;
   103580       }else{
   103581          while(
   103582           yypParser->yyidx >= 0 &&
   103583           yymx != YYERRORSYMBOL &&
   103584           (yyact = yy_find_reduce_action(
   103585                         yypParser->yystack[yypParser->yyidx].stateno,
   103586                         YYERRORSYMBOL)) >= YYNSTATE
   103587         ){
   103588           yy_pop_parser_stack(yypParser);
   103589         }
   103590         if( yypParser->yyidx < 0 || yymajor==0 ){
   103591           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   103592           yy_parse_failed(yypParser);
   103593           yymajor = YYNOCODE;
   103594         }else if( yymx!=YYERRORSYMBOL ){
   103595           YYMINORTYPE u2;
   103596           u2.YYERRSYMDT = 0;
   103597           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
   103598         }
   103599       }
   103600       yypParser->yyerrcnt = 3;
   103601       yyerrorhit = 1;
   103602 #elif defined(YYNOERRORRECOVERY)
   103603       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
   103604       ** do any kind of error recovery.  Instead, simply invoke the syntax
   103605       ** error routine and continue going as if nothing had happened.
   103606       **
   103607       ** Applications can set this macro (for example inside %include) if
   103608       ** they intend to abandon the parse upon the first syntax error seen.
   103609       */
   103610       yy_syntax_error(yypParser,yymajor,yyminorunion);
   103611       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   103612       yymajor = YYNOCODE;
   103613 
   103614 #else  /* YYERRORSYMBOL is not defined */
   103615       /* This is what we do if the grammar does not define ERROR:
   103616       **
   103617       **  * Report an error message, and throw away the input token.
   103618       **
   103619       **  * If the input token is $, then fail the parse.
   103620       **
   103621       ** As before, subsequent error messages are suppressed until
   103622       ** three input tokens have been successfully shifted.
   103623       */
   103624       if( yypParser->yyerrcnt<=0 ){
   103625         yy_syntax_error(yypParser,yymajor,yyminorunion);
   103626       }
   103627       yypParser->yyerrcnt = 3;
   103628       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
   103629       if( yyendofinput ){
   103630         yy_parse_failed(yypParser);
   103631       }
   103632       yymajor = YYNOCODE;
   103633 #endif
   103634     }
   103635   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
   103636   return;
   103637 }
   103638 
   103639 /************** End of parse.c ***********************************************/
   103640 /************** Begin file tokenize.c ****************************************/
   103641 /*
   103642 ** 2001 September 15
   103643 **
   103644 ** The author disclaims copyright to this source code.  In place of
   103645 ** a legal notice, here is a blessing:
   103646 **
   103647 **    May you do good and not evil.
   103648 **    May you find forgiveness for yourself and forgive others.
   103649 **    May you share freely, never taking more than you give.
   103650 **
   103651 *************************************************************************
   103652 ** An tokenizer for SQL
   103653 **
   103654 ** This file contains C code that splits an SQL input string up into
   103655 ** individual tokens and sends those tokens one-by-one over to the
   103656 ** parser for analysis.
   103657 */
   103658 
   103659 /*
   103660 ** The charMap() macro maps alphabetic characters into their
   103661 ** lower-case ASCII equivalent.  On ASCII machines, this is just
   103662 ** an upper-to-lower case map.  On EBCDIC machines we also need
   103663 ** to adjust the encoding.  Only alphabetic characters and underscores
   103664 ** need to be translated.
   103665 */
   103666 #ifdef SQLITE_ASCII
   103667 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
   103668 #endif
   103669 #ifdef SQLITE_EBCDIC
   103670 # define charMap(X) ebcdicToAscii[(unsigned char)X]
   103671 const unsigned char ebcdicToAscii[] = {
   103672 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
   103673    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
   103674    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
   103675    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
   103676    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
   103677    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
   103678    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
   103679    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
   103680    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
   103681    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
   103682    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
   103683    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
   103684    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
   103685    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
   103686    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
   103687    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
   103688    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
   103689 };
   103690 #endif
   103691 
   103692 /*
   103693 ** The sqlite3KeywordCode function looks up an identifier to determine if
   103694 ** it is a keyword.  If it is a keyword, the token code of that keyword is
   103695 ** returned.  If the input is not a keyword, TK_ID is returned.
   103696 **
   103697 ** The implementation of this routine was generated by a program,
   103698 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
   103699 ** The output of the mkkeywordhash.c program is written into a file
   103700 ** named keywordhash.h and then included into this source file by
   103701 ** the #include below.
   103702 */
   103703 /************** Include keywordhash.h in the middle of tokenize.c ************/
   103704 /************** Begin file keywordhash.h *************************************/
   103705 /***** This file contains automatically generated code ******
   103706 **
   103707 ** The code in this file has been automatically generated by
   103708 **
   103709 **   sqlite/tool/mkkeywordhash.c
   103710 **
   103711 ** The code in this file implements a function that determines whether
   103712 ** or not a given identifier is really an SQL keyword.  The same thing
   103713 ** might be implemented more directly using a hand-written hash table.
   103714 ** But by using this automatically generated code, the size of the code
   103715 ** is substantially reduced.  This is important for embedded applications
   103716 ** on platforms with limited memory.
   103717 */
   103718 /* Hash score: 175 */
   103719 static int keywordCode(const char *z, int n){
   103720   /* zText[] encodes 811 bytes of keywords in 541 bytes */
   103721   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
   103722   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
   103723   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
   103724   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
   103725   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
   103726   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
   103727   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
   103728   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
   103729   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
   103730   /*   INITIALLY                                                          */
   103731   static const char zText[540] = {
   103732     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   103733     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   103734     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
   103735     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
   103736     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
   103737     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
   103738     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
   103739     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
   103740     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
   103741     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
   103742     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
   103743     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
   103744     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
   103745     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
   103746     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
   103747     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
   103748     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
   103749     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
   103750     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
   103751     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
   103752     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
   103753     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
   103754     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
   103755     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
   103756     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
   103757     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
   103758     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
   103759     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
   103760     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
   103761     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
   103762   };
   103763   static const unsigned char aHash[127] = {
   103764       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
   103765       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
   103766      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
   103767        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
   103768        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
   103769       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
   103770       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
   103771       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
   103772       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
   103773       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
   103774   };
   103775   static const unsigned char aNext[121] = {
   103776        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
   103777        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
   103778        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
   103779        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
   103780        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
   103781       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
   103782       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
   103783        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
   103784      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
   103785       35,  64,   0,   0,
   103786   };
   103787   static const unsigned char aLen[121] = {
   103788        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
   103789        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
   103790       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
   103791        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
   103792        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
   103793        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
   103794        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
   103795        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
   103796        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
   103797        6,   4,   9,   3,
   103798   };
   103799   static const unsigned short int aOffset[121] = {
   103800        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
   103801       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
   103802       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
   103803      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
   103804      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
   103805      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
   103806      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
   103807      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
   103808      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
   103809      521, 527, 531, 536,
   103810   };
   103811   static const unsigned char aCode[121] = {
   103812     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
   103813     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
   103814     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
   103815     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
   103816     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
   103817     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
   103818     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
   103819     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
   103820     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
   103821     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
   103822     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
   103823     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
   103824     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
   103825     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
   103826     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
   103827     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
   103828     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
   103829     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
   103830     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
   103831     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
   103832     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
   103833     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
   103834     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
   103835     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
   103836     TK_ALL,
   103837   };
   103838   int h, i;
   103839   if( n<2 ) return TK_ID;
   103840   h = ((charMap(z[0])*4) ^
   103841       (charMap(z[n-1])*3) ^
   103842       n) % 127;
   103843   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
   103844     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
   103845       testcase( i==0 ); /* REINDEX */
   103846       testcase( i==1 ); /* INDEXED */
   103847       testcase( i==2 ); /* INDEX */
   103848       testcase( i==3 ); /* DESC */
   103849       testcase( i==4 ); /* ESCAPE */
   103850       testcase( i==5 ); /* EACH */
   103851       testcase( i==6 ); /* CHECK */
   103852       testcase( i==7 ); /* KEY */
   103853       testcase( i==8 ); /* BEFORE */
   103854       testcase( i==9 ); /* FOREIGN */
   103855       testcase( i==10 ); /* FOR */
   103856       testcase( i==11 ); /* IGNORE */
   103857       testcase( i==12 ); /* REGEXP */
   103858       testcase( i==13 ); /* EXPLAIN */
   103859       testcase( i==14 ); /* INSTEAD */
   103860       testcase( i==15 ); /* ADD */
   103861       testcase( i==16 ); /* DATABASE */
   103862       testcase( i==17 ); /* AS */
   103863       testcase( i==18 ); /* SELECT */
   103864       testcase( i==19 ); /* TABLE */
   103865       testcase( i==20 ); /* LEFT */
   103866       testcase( i==21 ); /* THEN */
   103867       testcase( i==22 ); /* END */
   103868       testcase( i==23 ); /* DEFERRABLE */
   103869       testcase( i==24 ); /* ELSE */
   103870       testcase( i==25 ); /* EXCEPT */
   103871       testcase( i==26 ); /* TRANSACTION */
   103872       testcase( i==27 ); /* ACTION */
   103873       testcase( i==28 ); /* ON */
   103874       testcase( i==29 ); /* NATURAL */
   103875       testcase( i==30 ); /* ALTER */
   103876       testcase( i==31 ); /* RAISE */
   103877       testcase( i==32 ); /* EXCLUSIVE */
   103878       testcase( i==33 ); /* EXISTS */
   103879       testcase( i==34 ); /* SAVEPOINT */
   103880       testcase( i==35 ); /* INTERSECT */
   103881       testcase( i==36 ); /* TRIGGER */
   103882       testcase( i==37 ); /* REFERENCES */
   103883       testcase( i==38 ); /* CONSTRAINT */
   103884       testcase( i==39 ); /* INTO */
   103885       testcase( i==40 ); /* OFFSET */
   103886       testcase( i==41 ); /* OF */
   103887       testcase( i==42 ); /* SET */
   103888       testcase( i==43 ); /* TEMPORARY */
   103889       testcase( i==44 ); /* TEMP */
   103890       testcase( i==45 ); /* OR */
   103891       testcase( i==46 ); /* UNIQUE */
   103892       testcase( i==47 ); /* QUERY */
   103893       testcase( i==48 ); /* ATTACH */
   103894       testcase( i==49 ); /* HAVING */
   103895       testcase( i==50 ); /* GROUP */
   103896       testcase( i==51 ); /* UPDATE */
   103897       testcase( i==52 ); /* BEGIN */
   103898       testcase( i==53 ); /* INNER */
   103899       testcase( i==54 ); /* RELEASE */
   103900       testcase( i==55 ); /* BETWEEN */
   103901       testcase( i==56 ); /* NOTNULL */
   103902       testcase( i==57 ); /* NOT */
   103903       testcase( i==58 ); /* NO */
   103904       testcase( i==59 ); /* NULL */
   103905       testcase( i==60 ); /* LIKE */
   103906       testcase( i==61 ); /* CASCADE */
   103907       testcase( i==62 ); /* ASC */
   103908       testcase( i==63 ); /* DELETE */
   103909       testcase( i==64 ); /* CASE */
   103910       testcase( i==65 ); /* COLLATE */
   103911       testcase( i==66 ); /* CREATE */
   103912       testcase( i==67 ); /* CURRENT_DATE */
   103913       testcase( i==68 ); /* DETACH */
   103914       testcase( i==69 ); /* IMMEDIATE */
   103915       testcase( i==70 ); /* JOIN */
   103916       testcase( i==71 ); /* INSERT */
   103917       testcase( i==72 ); /* MATCH */
   103918       testcase( i==73 ); /* PLAN */
   103919       testcase( i==74 ); /* ANALYZE */
   103920       testcase( i==75 ); /* PRAGMA */
   103921       testcase( i==76 ); /* ABORT */
   103922       testcase( i==77 ); /* VALUES */
   103923       testcase( i==78 ); /* VIRTUAL */
   103924       testcase( i==79 ); /* LIMIT */
   103925       testcase( i==80 ); /* WHEN */
   103926       testcase( i==81 ); /* WHERE */
   103927       testcase( i==82 ); /* RENAME */
   103928       testcase( i==83 ); /* AFTER */
   103929       testcase( i==84 ); /* REPLACE */
   103930       testcase( i==85 ); /* AND */
   103931       testcase( i==86 ); /* DEFAULT */
   103932       testcase( i==87 ); /* AUTOINCREMENT */
   103933       testcase( i==88 ); /* TO */
   103934       testcase( i==89 ); /* IN */
   103935       testcase( i==90 ); /* CAST */
   103936       testcase( i==91 ); /* COLUMN */
   103937       testcase( i==92 ); /* COMMIT */
   103938       testcase( i==93 ); /* CONFLICT */
   103939       testcase( i==94 ); /* CROSS */
   103940       testcase( i==95 ); /* CURRENT_TIMESTAMP */
   103941       testcase( i==96 ); /* CURRENT_TIME */
   103942       testcase( i==97 ); /* PRIMARY */
   103943       testcase( i==98 ); /* DEFERRED */
   103944       testcase( i==99 ); /* DISTINCT */
   103945       testcase( i==100 ); /* IS */
   103946       testcase( i==101 ); /* DROP */
   103947       testcase( i==102 ); /* FAIL */
   103948       testcase( i==103 ); /* FROM */
   103949       testcase( i==104 ); /* FULL */
   103950       testcase( i==105 ); /* GLOB */
   103951       testcase( i==106 ); /* BY */
   103952       testcase( i==107 ); /* IF */
   103953       testcase( i==108 ); /* ISNULL */
   103954       testcase( i==109 ); /* ORDER */
   103955       testcase( i==110 ); /* RESTRICT */
   103956       testcase( i==111 ); /* OUTER */
   103957       testcase( i==112 ); /* RIGHT */
   103958       testcase( i==113 ); /* ROLLBACK */
   103959       testcase( i==114 ); /* ROW */
   103960       testcase( i==115 ); /* UNION */
   103961       testcase( i==116 ); /* USING */
   103962       testcase( i==117 ); /* VACUUM */
   103963       testcase( i==118 ); /* VIEW */
   103964       testcase( i==119 ); /* INITIALLY */
   103965       testcase( i==120 ); /* ALL */
   103966       return aCode[i];
   103967     }
   103968   }
   103969   return TK_ID;
   103970 }
   103971 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   103972   return keywordCode((char*)z, n);
   103973 }
   103974 #define SQLITE_N_KEYWORD 121
   103975 
   103976 /************** End of keywordhash.h *****************************************/
   103977 /************** Continuing where we left off in tokenize.c *******************/
   103978 
   103979 
   103980 /*
   103981 ** If X is a character that can be used in an identifier then
   103982 ** IdChar(X) will be true.  Otherwise it is false.
   103983 **
   103984 ** For ASCII, any character with the high-order bit set is
   103985 ** allowed in an identifier.  For 7-bit characters,
   103986 ** sqlite3IsIdChar[X] must be 1.
   103987 **
   103988 ** For EBCDIC, the rules are more complex but have the same
   103989 ** end result.
   103990 **
   103991 ** Ticket #1066.  the SQL standard does not allow '$' in the
   103992 ** middle of identfiers.  But many SQL implementations do.
   103993 ** SQLite will allow '$' in identifiers for compatibility.
   103994 ** But the feature is undocumented.
   103995 */
   103996 #ifdef SQLITE_ASCII
   103997 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   103998 #endif
   103999 #ifdef SQLITE_EBCDIC
   104000 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
   104001 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   104002     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
   104003     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
   104004     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
   104005     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
   104006     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
   104007     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
   104008     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
   104009     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
   104010     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
   104011     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   104012     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   104013     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   104014 };
   104015 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   104016 #endif
   104017 
   104018 
   104019 /*
   104020 ** Return the length of the token that begins at z[0].
   104021 ** Store the token type in *tokenType before returning.
   104022 */
   104023 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
   104024   int i, c;
   104025   switch( *z ){
   104026     case ' ': case '\t': case '\n': case '\f': case '\r': {
   104027       testcase( z[0]==' ' );
   104028       testcase( z[0]=='\t' );
   104029       testcase( z[0]=='\n' );
   104030       testcase( z[0]=='\f' );
   104031       testcase( z[0]=='\r' );
   104032       for(i=1; sqlite3Isspace(z[i]); i++){}
   104033       *tokenType = TK_SPACE;
   104034       return i;
   104035     }
   104036     case '-': {
   104037       if( z[1]=='-' ){
   104038         /* IMP: R-15891-05542 -- syntax diagram for comments */
   104039         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   104040         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   104041         return i;
   104042       }
   104043       *tokenType = TK_MINUS;
   104044       return 1;
   104045     }
   104046     case '(': {
   104047       *tokenType = TK_LP;
   104048       return 1;
   104049     }
   104050     case ')': {
   104051       *tokenType = TK_RP;
   104052       return 1;
   104053     }
   104054     case ';': {
   104055       *tokenType = TK_SEMI;
   104056       return 1;
   104057     }
   104058     case '+': {
   104059       *tokenType = TK_PLUS;
   104060       return 1;
   104061     }
   104062     case '*': {
   104063       *tokenType = TK_STAR;
   104064       return 1;
   104065     }
   104066     case '/': {
   104067       if( z[1]!='*' || z[2]==0 ){
   104068         *tokenType = TK_SLASH;
   104069         return 1;
   104070       }
   104071       /* IMP: R-15891-05542 -- syntax diagram for comments */
   104072       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   104073       if( c ) i++;
   104074       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   104075       return i;
   104076     }
   104077     case '%': {
   104078       *tokenType = TK_REM;
   104079       return 1;
   104080     }
   104081     case '=': {
   104082       *tokenType = TK_EQ;
   104083       return 1 + (z[1]=='=');
   104084     }
   104085     case '<': {
   104086       if( (c=z[1])=='=' ){
   104087         *tokenType = TK_LE;
   104088         return 2;
   104089       }else if( c=='>' ){
   104090         *tokenType = TK_NE;
   104091         return 2;
   104092       }else if( c=='<' ){
   104093         *tokenType = TK_LSHIFT;
   104094         return 2;
   104095       }else{
   104096         *tokenType = TK_LT;
   104097         return 1;
   104098       }
   104099     }
   104100     case '>': {
   104101       if( (c=z[1])=='=' ){
   104102         *tokenType = TK_GE;
   104103         return 2;
   104104       }else if( c=='>' ){
   104105         *tokenType = TK_RSHIFT;
   104106         return 2;
   104107       }else{
   104108         *tokenType = TK_GT;
   104109         return 1;
   104110       }
   104111     }
   104112     case '!': {
   104113       if( z[1]!='=' ){
   104114         *tokenType = TK_ILLEGAL;
   104115         return 2;
   104116       }else{
   104117         *tokenType = TK_NE;
   104118         return 2;
   104119       }
   104120     }
   104121     case '|': {
   104122       if( z[1]!='|' ){
   104123         *tokenType = TK_BITOR;
   104124         return 1;
   104125       }else{
   104126         *tokenType = TK_CONCAT;
   104127         return 2;
   104128       }
   104129     }
   104130     case ',': {
   104131       *tokenType = TK_COMMA;
   104132       return 1;
   104133     }
   104134     case '&': {
   104135       *tokenType = TK_BITAND;
   104136       return 1;
   104137     }
   104138     case '~': {
   104139       *tokenType = TK_BITNOT;
   104140       return 1;
   104141     }
   104142     case '`':
   104143     case '\'':
   104144     case '"': {
   104145       int delim = z[0];
   104146       testcase( delim=='`' );
   104147       testcase( delim=='\'' );
   104148       testcase( delim=='"' );
   104149       for(i=1; (c=z[i])!=0; i++){
   104150         if( c==delim ){
   104151           if( z[i+1]==delim ){
   104152             i++;
   104153           }else{
   104154             break;
   104155           }
   104156         }
   104157       }
   104158       if( c=='\'' ){
   104159         *tokenType = TK_STRING;
   104160         return i+1;
   104161       }else if( c!=0 ){
   104162         *tokenType = TK_ID;
   104163         return i+1;
   104164       }else{
   104165         *tokenType = TK_ILLEGAL;
   104166         return i;
   104167       }
   104168     }
   104169     case '.': {
   104170 #ifndef SQLITE_OMIT_FLOATING_POINT
   104171       if( !sqlite3Isdigit(z[1]) )
   104172 #endif
   104173       {
   104174         *tokenType = TK_DOT;
   104175         return 1;
   104176       }
   104177       /* If the next character is a digit, this is a floating point
   104178       ** number that begins with ".".  Fall thru into the next case */
   104179     }
   104180     case '0': case '1': case '2': case '3': case '4':
   104181     case '5': case '6': case '7': case '8': case '9': {
   104182       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
   104183       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
   104184       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
   104185       testcase( z[0]=='9' );
   104186       *tokenType = TK_INTEGER;
   104187       for(i=0; sqlite3Isdigit(z[i]); i++){}
   104188 #ifndef SQLITE_OMIT_FLOATING_POINT
   104189       if( z[i]=='.' ){
   104190         i++;
   104191         while( sqlite3Isdigit(z[i]) ){ i++; }
   104192         *tokenType = TK_FLOAT;
   104193       }
   104194       if( (z[i]=='e' || z[i]=='E') &&
   104195            ( sqlite3Isdigit(z[i+1])
   104196             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
   104197            )
   104198       ){
   104199         i += 2;
   104200         while( sqlite3Isdigit(z[i]) ){ i++; }
   104201         *tokenType = TK_FLOAT;
   104202       }
   104203 #endif
   104204       while( IdChar(z[i]) ){
   104205         *tokenType = TK_ILLEGAL;
   104206         i++;
   104207       }
   104208       return i;
   104209     }
   104210     case '[': {
   104211       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
   104212       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
   104213       return i;
   104214     }
   104215     case '?': {
   104216       *tokenType = TK_VARIABLE;
   104217       for(i=1; sqlite3Isdigit(z[i]); i++){}
   104218       return i;
   104219     }
   104220     case '#': {
   104221       for(i=1; sqlite3Isdigit(z[i]); i++){}
   104222       if( i>1 ){
   104223         /* Parameters of the form #NNN (where NNN is a number) are used
   104224         ** internally by sqlite3NestedParse.  */
   104225         *tokenType = TK_REGISTER;
   104226         return i;
   104227       }
   104228       /* Fall through into the next case if the '#' is not followed by
   104229       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
   104230     }
   104231 #ifndef SQLITE_OMIT_TCL_VARIABLE
   104232     case '$':
   104233 #endif
   104234     case '@':  /* For compatibility with MS SQL Server */
   104235     case ':': {
   104236       int n = 0;
   104237       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
   104238       *tokenType = TK_VARIABLE;
   104239       for(i=1; (c=z[i])!=0; i++){
   104240         if( IdChar(c) ){
   104241           n++;
   104242 #ifndef SQLITE_OMIT_TCL_VARIABLE
   104243         }else if( c=='(' && n>0 ){
   104244           do{
   104245             i++;
   104246           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
   104247           if( c==')' ){
   104248             i++;
   104249           }else{
   104250             *tokenType = TK_ILLEGAL;
   104251           }
   104252           break;
   104253         }else if( c==':' && z[i+1]==':' ){
   104254           i++;
   104255 #endif
   104256         }else{
   104257           break;
   104258         }
   104259       }
   104260       if( n==0 ) *tokenType = TK_ILLEGAL;
   104261       return i;
   104262     }
   104263 #ifndef SQLITE_OMIT_BLOB_LITERAL
   104264     case 'x': case 'X': {
   104265       testcase( z[0]=='x' ); testcase( z[0]=='X' );
   104266       if( z[1]=='\'' ){
   104267         *tokenType = TK_BLOB;
   104268         for(i=2; (c=z[i])!=0 && c!='\''; i++){
   104269           if( !sqlite3Isxdigit(c) ){
   104270             *tokenType = TK_ILLEGAL;
   104271           }
   104272         }
   104273         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
   104274         if( c ) i++;
   104275         return i;
   104276       }
   104277       /* Otherwise fall through to the next case */
   104278     }
   104279 #endif
   104280     default: {
   104281       if( !IdChar(*z) ){
   104282         break;
   104283       }
   104284       for(i=1; IdChar(z[i]); i++){}
   104285       *tokenType = keywordCode((char*)z, i);
   104286       return i;
   104287     }
   104288   }
   104289   *tokenType = TK_ILLEGAL;
   104290   return 1;
   104291 }
   104292 
   104293 /*
   104294 ** Run the parser on the given SQL string.  The parser structure is
   104295 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
   104296 ** then an and attempt is made to write an error message into
   104297 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
   104298 ** error message.
   104299 */
   104300 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   104301   int nErr = 0;                   /* Number of errors encountered */
   104302   int i;                          /* Loop counter */
   104303   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   104304   int tokenType;                  /* type of the next token */
   104305   int lastTokenParsed = -1;       /* type of the previous token */
   104306   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   104307   sqlite3 *db = pParse->db;       /* The database connection */
   104308   int mxSqlLen;                   /* Max length of an SQL string */
   104309 
   104310 
   104311   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   104312   if( db->activeVdbeCnt==0 ){
   104313     db->u1.isInterrupted = 0;
   104314   }
   104315   pParse->rc = SQLITE_OK;
   104316   pParse->zTail = zSql;
   104317   i = 0;
   104318   assert( pzErrMsg!=0 );
   104319   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
   104320   if( pEngine==0 ){
   104321     db->mallocFailed = 1;
   104322     return SQLITE_NOMEM;
   104323   }
   104324   assert( pParse->pNewTable==0 );
   104325   assert( pParse->pNewTrigger==0 );
   104326   assert( pParse->nVar==0 );
   104327   assert( pParse->nVarExpr==0 );
   104328   assert( pParse->nVarExprAlloc==0 );
   104329   assert( pParse->apVarExpr==0 );
   104330   enableLookaside = db->lookaside.bEnabled;
   104331   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   104332   while( !db->mallocFailed && zSql[i]!=0 ){
   104333     assert( i>=0 );
   104334     pParse->sLastToken.z = &zSql[i];
   104335     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   104336     i += pParse->sLastToken.n;
   104337     if( i>mxSqlLen ){
   104338       pParse->rc = SQLITE_TOOBIG;
   104339       break;
   104340     }
   104341     switch( tokenType ){
   104342       case TK_SPACE: {
   104343         if( db->u1.isInterrupted ){
   104344           sqlite3ErrorMsg(pParse, "interrupt");
   104345           pParse->rc = SQLITE_INTERRUPT;
   104346           goto abort_parse;
   104347         }
   104348         break;
   104349       }
   104350       case TK_ILLEGAL: {
   104351         sqlite3DbFree(db, *pzErrMsg);
   104352         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
   104353                         &pParse->sLastToken);
   104354         nErr++;
   104355         goto abort_parse;
   104356       }
   104357       case TK_SEMI: {
   104358         pParse->zTail = &zSql[i];
   104359         /* Fall thru into the default case */
   104360       }
   104361       default: {
   104362         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
   104363         lastTokenParsed = tokenType;
   104364         if( pParse->rc!=SQLITE_OK ){
   104365           goto abort_parse;
   104366         }
   104367         break;
   104368       }
   104369     }
   104370   }
   104371 abort_parse:
   104372   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
   104373     if( lastTokenParsed!=TK_SEMI ){
   104374       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
   104375       pParse->zTail = &zSql[i];
   104376     }
   104377     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
   104378   }
   104379 #ifdef YYTRACKMAXSTACKDEPTH
   104380   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
   104381       sqlite3ParserStackPeak(pEngine)
   104382   );
   104383 #endif /* YYDEBUG */
   104384   sqlite3ParserFree(pEngine, sqlite3_free);
   104385   db->lookaside.bEnabled = enableLookaside;
   104386   if( db->mallocFailed ){
   104387     pParse->rc = SQLITE_NOMEM;
   104388   }
   104389   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   104390     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
   104391   }
   104392   assert( pzErrMsg!=0 );
   104393   if( pParse->zErrMsg ){
   104394     *pzErrMsg = pParse->zErrMsg;
   104395     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
   104396     pParse->zErrMsg = 0;
   104397     nErr++;
   104398   }
   104399   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
   104400     sqlite3VdbeDelete(pParse->pVdbe);
   104401     pParse->pVdbe = 0;
   104402   }
   104403 #ifndef SQLITE_OMIT_SHARED_CACHE
   104404   if( pParse->nested==0 ){
   104405     sqlite3DbFree(db, pParse->aTableLock);
   104406     pParse->aTableLock = 0;
   104407     pParse->nTableLock = 0;
   104408   }
   104409 #endif
   104410 #ifndef SQLITE_OMIT_VIRTUALTABLE
   104411   sqlite3_free(pParse->apVtabLock);
   104412 #endif
   104413 
   104414   if( !IN_DECLARE_VTAB ){
   104415     /* If the pParse->declareVtab flag is set, do not delete any table
   104416     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
   104417     ** will take responsibility for freeing the Table structure.
   104418     */
   104419     sqlite3DeleteTable(db, pParse->pNewTable);
   104420   }
   104421 
   104422   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
   104423   sqlite3DbFree(db, pParse->apVarExpr);
   104424   sqlite3DbFree(db, pParse->aAlias);
   104425   while( pParse->pAinc ){
   104426     AutoincInfo *p = pParse->pAinc;
   104427     pParse->pAinc = p->pNext;
   104428     sqlite3DbFree(db, p);
   104429   }
   104430   while( pParse->pZombieTab ){
   104431     Table *p = pParse->pZombieTab;
   104432     pParse->pZombieTab = p->pNextZombie;
   104433     sqlite3DeleteTable(db, p);
   104434   }
   104435   if( nErr>0 && pParse->rc==SQLITE_OK ){
   104436     pParse->rc = SQLITE_ERROR;
   104437   }
   104438   return nErr;
   104439 }
   104440 
   104441 /************** End of tokenize.c ********************************************/
   104442 /************** Begin file complete.c ****************************************/
   104443 /*
   104444 ** 2001 September 15
   104445 **
   104446 ** The author disclaims copyright to this source code.  In place of
   104447 ** a legal notice, here is a blessing:
   104448 **
   104449 **    May you do good and not evil.
   104450 **    May you find forgiveness for yourself and forgive others.
   104451 **    May you share freely, never taking more than you give.
   104452 **
   104453 *************************************************************************
   104454 ** An tokenizer for SQL
   104455 **
   104456 ** This file contains C code that implements the sqlite3_complete() API.
   104457 ** This code used to be part of the tokenizer.c source file.  But by
   104458 ** separating it out, the code will be automatically omitted from
   104459 ** static links that do not use it.
   104460 */
   104461 #ifndef SQLITE_OMIT_COMPLETE
   104462 
   104463 /*
   104464 ** This is defined in tokenize.c.  We just have to import the definition.
   104465 */
   104466 #ifndef SQLITE_AMALGAMATION
   104467 #ifdef SQLITE_ASCII
   104468 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
   104469 #endif
   104470 #ifdef SQLITE_EBCDIC
   104471 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
   104472 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   104473 #endif
   104474 #endif /* SQLITE_AMALGAMATION */
   104475 
   104476 
   104477 /*
   104478 ** Token types used by the sqlite3_complete() routine.  See the header
   104479 ** comments on that procedure for additional information.
   104480 */
   104481 #define tkSEMI    0
   104482 #define tkWS      1
   104483 #define tkOTHER   2
   104484 #ifndef SQLITE_OMIT_TRIGGER
   104485 #define tkEXPLAIN 3
   104486 #define tkCREATE  4
   104487 #define tkTEMP    5
   104488 #define tkTRIGGER 6
   104489 #define tkEND     7
   104490 #endif
   104491 
   104492 /*
   104493 ** Return TRUE if the given SQL string ends in a semicolon.
   104494 **
   104495 ** Special handling is require for CREATE TRIGGER statements.
   104496 ** Whenever the CREATE TRIGGER keywords are seen, the statement
   104497 ** must end with ";END;".
   104498 **
   104499 ** This implementation uses a state machine with 8 states:
   104500 **
   104501 **   (0) INVALID   We have not yet seen a non-whitespace character.
   104502 **
   104503 **   (1) START     At the beginning or end of an SQL statement.  This routine
   104504 **                 returns 1 if it ends in the START state and 0 if it ends
   104505 **                 in any other state.
   104506 **
   104507 **   (2) NORMAL    We are in the middle of statement which ends with a single
   104508 **                 semicolon.
   104509 **
   104510 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
   104511 **                 a statement.
   104512 **
   104513 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
   104514 **                 statement, possibly preceeded by EXPLAIN and/or followed by
   104515 **                 TEMP or TEMPORARY
   104516 **
   104517 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
   104518 **                 ended by a semicolon, the keyword END, and another semicolon.
   104519 **
   104520 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
   104521 **                 the end of a trigger definition.
   104522 **
   104523 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
   104524 **                 of a trigger difinition.
   104525 **
   104526 ** Transitions between states above are determined by tokens extracted
   104527 ** from the input.  The following tokens are significant:
   104528 **
   104529 **   (0) tkSEMI      A semicolon.
   104530 **   (1) tkWS        Whitespace.
   104531 **   (2) tkOTHER     Any other SQL token.
   104532 **   (3) tkEXPLAIN   The "explain" keyword.
   104533 **   (4) tkCREATE    The "create" keyword.
   104534 **   (5) tkTEMP      The "temp" or "temporary" keyword.
   104535 **   (6) tkTRIGGER   The "trigger" keyword.
   104536 **   (7) tkEND       The "end" keyword.
   104537 **
   104538 ** Whitespace never causes a state transition and is always ignored.
   104539 ** This means that a SQL string of all whitespace is invalid.
   104540 **
   104541 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
   104542 ** to recognize the end of a trigger can be omitted.  All we have to do
   104543 ** is look for a semicolon that is not part of an string or comment.
   104544 */
   104545 SQLITE_API int sqlite3_complete(const char *zSql){
   104546   u8 state = 0;   /* Current state, using numbers defined in header comment */
   104547   u8 token;       /* Value of the next token */
   104548 
   104549 #ifndef SQLITE_OMIT_TRIGGER
   104550   /* A complex statement machine used to detect the end of a CREATE TRIGGER
   104551   ** statement.  This is the normal case.
   104552   */
   104553   static const u8 trans[8][8] = {
   104554                      /* Token:                                                */
   104555      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
   104556      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
   104557      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
   104558      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
   104559      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
   104560      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
   104561      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
   104562      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
   104563      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
   104564   };
   104565 #else
   104566   /* If triggers are not supported by this compile then the statement machine
   104567   ** used to detect the end of a statement is much simplier
   104568   */
   104569   static const u8 trans[3][3] = {
   104570                      /* Token:           */
   104571      /* State:       **  SEMI  WS  OTHER */
   104572      /* 0 INVALID: */ {    1,  0,     2, },
   104573      /* 1   START: */ {    1,  1,     2, },
   104574      /* 2  NORMAL: */ {    1,  2,     2, },
   104575   };
   104576 #endif /* SQLITE_OMIT_TRIGGER */
   104577 
   104578   while( *zSql ){
   104579     switch( *zSql ){
   104580       case ';': {  /* A semicolon */
   104581         token = tkSEMI;
   104582         break;
   104583       }
   104584       case ' ':
   104585       case '\r':
   104586       case '\t':
   104587       case '\n':
   104588       case '\f': {  /* White space is ignored */
   104589         token = tkWS;
   104590         break;
   104591       }
   104592       case '/': {   /* C-style comments */
   104593         if( zSql[1]!='*' ){
   104594           token = tkOTHER;
   104595           break;
   104596         }
   104597         zSql += 2;
   104598         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
   104599         if( zSql[0]==0 ) return 0;
   104600         zSql++;
   104601         token = tkWS;
   104602         break;
   104603       }
   104604       case '-': {   /* SQL-style comments from "--" to end of line */
   104605         if( zSql[1]!='-' ){
   104606           token = tkOTHER;
   104607           break;
   104608         }
   104609         while( *zSql && *zSql!='\n' ){ zSql++; }
   104610         if( *zSql==0 ) return state==1;
   104611         token = tkWS;
   104612         break;
   104613       }
   104614       case '[': {   /* Microsoft-style identifiers in [...] */
   104615         zSql++;
   104616         while( *zSql && *zSql!=']' ){ zSql++; }
   104617         if( *zSql==0 ) return 0;
   104618         token = tkOTHER;
   104619         break;
   104620       }
   104621       case '`':     /* Grave-accent quoted symbols used by MySQL */
   104622       case '"':     /* single- and double-quoted strings */
   104623       case '\'': {
   104624         int c = *zSql;
   104625         zSql++;
   104626         while( *zSql && *zSql!=c ){ zSql++; }
   104627         if( *zSql==0 ) return 0;
   104628         token = tkOTHER;
   104629         break;
   104630       }
   104631       default: {
   104632 #ifdef SQLITE_EBCDIC
   104633         unsigned char c;
   104634 #endif
   104635         if( IdChar((u8)*zSql) ){
   104636           /* Keywords and unquoted identifiers */
   104637           int nId;
   104638           for(nId=1; IdChar(zSql[nId]); nId++){}
   104639 #ifdef SQLITE_OMIT_TRIGGER
   104640           token = tkOTHER;
   104641 #else
   104642           switch( *zSql ){
   104643             case 'c': case 'C': {
   104644               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
   104645                 token = tkCREATE;
   104646               }else{
   104647                 token = tkOTHER;
   104648               }
   104649               break;
   104650             }
   104651             case 't': case 'T': {
   104652               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
   104653                 token = tkTRIGGER;
   104654               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
   104655                 token = tkTEMP;
   104656               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
   104657                 token = tkTEMP;
   104658               }else{
   104659                 token = tkOTHER;
   104660               }
   104661               break;
   104662             }
   104663             case 'e':  case 'E': {
   104664               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
   104665                 token = tkEND;
   104666               }else
   104667 #ifndef SQLITE_OMIT_EXPLAIN
   104668               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
   104669                 token = tkEXPLAIN;
   104670               }else
   104671 #endif
   104672               {
   104673                 token = tkOTHER;
   104674               }
   104675               break;
   104676             }
   104677             default: {
   104678               token = tkOTHER;
   104679               break;
   104680             }
   104681           }
   104682 #endif /* SQLITE_OMIT_TRIGGER */
   104683           zSql += nId-1;
   104684         }else{
   104685           /* Operators and special symbols */
   104686           token = tkOTHER;
   104687         }
   104688         break;
   104689       }
   104690     }
   104691     state = trans[state][token];
   104692     zSql++;
   104693   }
   104694   return state==1;
   104695 }
   104696 
   104697 #ifndef SQLITE_OMIT_UTF16
   104698 /*
   104699 ** This routine is the same as the sqlite3_complete() routine described
   104700 ** above, except that the parameter is required to be UTF-16 encoded, not
   104701 ** UTF-8.
   104702 */
   104703 SQLITE_API int sqlite3_complete16(const void *zSql){
   104704   sqlite3_value *pVal;
   104705   char const *zSql8;
   104706   int rc = SQLITE_NOMEM;
   104707 
   104708 #ifndef SQLITE_OMIT_AUTOINIT
   104709   rc = sqlite3_initialize();
   104710   if( rc ) return rc;
   104711 #endif
   104712   pVal = sqlite3ValueNew(0);
   104713   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   104714   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   104715   if( zSql8 ){
   104716     rc = sqlite3_complete(zSql8);
   104717   }else{
   104718     rc = SQLITE_NOMEM;
   104719   }
   104720   sqlite3ValueFree(pVal);
   104721   return sqlite3ApiExit(0, rc);
   104722 }
   104723 #endif /* SQLITE_OMIT_UTF16 */
   104724 #endif /* SQLITE_OMIT_COMPLETE */
   104725 
   104726 /************** End of complete.c ********************************************/
   104727 /************** Begin file main.c ********************************************/
   104728 /*
   104729 ** 2001 September 15
   104730 **
   104731 ** The author disclaims copyright to this source code.  In place of
   104732 ** a legal notice, here is a blessing:
   104733 **
   104734 **    May you do good and not evil.
   104735 **    May you find forgiveness for yourself and forgive others.
   104736 **    May you share freely, never taking more than you give.
   104737 **
   104738 *************************************************************************
   104739 ** Main file for the SQLite library.  The routines in this file
   104740 ** implement the programmer interface to the library.  Routines in
   104741 ** other files are for internal use by SQLite and should not be
   104742 ** accessed by users of the library.
   104743 */
   104744 
   104745 #ifdef SQLITE_ENABLE_FTS3
   104746 /************** Include fts3.h in the middle of main.c ***********************/
   104747 /************** Begin file fts3.h ********************************************/
   104748 /*
   104749 ** 2006 Oct 10
   104750 **
   104751 ** The author disclaims copyright to this source code.  In place of
   104752 ** a legal notice, here is a blessing:
   104753 **
   104754 **    May you do good and not evil.
   104755 **    May you find forgiveness for yourself and forgive others.
   104756 **    May you share freely, never taking more than you give.
   104757 **
   104758 ******************************************************************************
   104759 **
   104760 ** This header file is used by programs that want to link against the
   104761 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
   104762 */
   104763 
   104764 #if 0
   104765 extern "C" {
   104766 #endif  /* __cplusplus */
   104767 
   104768 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs); // Android Change
   104769 
   104770 #if 0
   104771 }  /* extern "C" */
   104772 #endif  /* __cplusplus */
   104773 
   104774 /************** End of fts3.h ************************************************/
   104775 /************** Continuing where we left off in main.c ***********************/
   104776 #endif
   104777 #ifdef SQLITE_ENABLE_RTREE
   104778 /************** Include rtree.h in the middle of main.c **********************/
   104779 /************** Begin file rtree.h *******************************************/
   104780 /*
   104781 ** 2008 May 26
   104782 **
   104783 ** The author disclaims copyright to this source code.  In place of
   104784 ** a legal notice, here is a blessing:
   104785 **
   104786 **    May you do good and not evil.
   104787 **    May you find forgiveness for yourself and forgive others.
   104788 **    May you share freely, never taking more than you give.
   104789 **
   104790 ******************************************************************************
   104791 **
   104792 ** This header file is used by programs that want to link against the
   104793 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
   104794 */
   104795 
   104796 #if 0
   104797 extern "C" {
   104798 #endif  /* __cplusplus */
   104799 
   104800 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
   104801 
   104802 #if 0
   104803 }  /* extern "C" */
   104804 #endif  /* __cplusplus */
   104805 
   104806 /************** End of rtree.h ***********************************************/
   104807 /************** Continuing where we left off in main.c ***********************/
   104808 #endif
   104809 #ifdef SQLITE_ENABLE_ICU
   104810 /************** Include sqliteicu.h in the middle of main.c ******************/
   104811 /************** Begin file sqliteicu.h ***************************************/
   104812 /*
   104813 ** 2008 May 26
   104814 **
   104815 ** The author disclaims copyright to this source code.  In place of
   104816 ** a legal notice, here is a blessing:
   104817 **
   104818 **    May you do good and not evil.
   104819 **    May you find forgiveness for yourself and forgive others.
   104820 **    May you share freely, never taking more than you give.
   104821 **
   104822 ******************************************************************************
   104823 **
   104824 ** This header file is used by programs that want to link against the
   104825 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
   104826 */
   104827 
   104828 #if 0
   104829 extern "C" {
   104830 #endif  /* __cplusplus */
   104831 
   104832 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
   104833 
   104834 #if 0
   104835 }  /* extern "C" */
   104836 #endif  /* __cplusplus */
   104837 
   104838 
   104839 /************** End of sqliteicu.h *******************************************/
   104840 /************** Continuing where we left off in main.c ***********************/
   104841 #endif
   104842 
   104843 #ifndef SQLITE_AMALGAMATION
   104844 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
   104845 ** contains the text of SQLITE_VERSION macro.
   104846 */
   104847 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
   104848 #endif
   104849 
   104850 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
   104851 ** a pointer to the to the sqlite3_version[] string constant.
   104852 */
   104853 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
   104854 
   104855 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
   104856 ** pointer to a string constant whose value is the same as the
   104857 ** SQLITE_SOURCE_ID C preprocessor macro.
   104858 */
   104859 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
   104860 
   104861 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
   104862 ** returns an integer equal to SQLITE_VERSION_NUMBER.
   104863 */
   104864 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
   104865 
   104866 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
   104867 ** zero if and only if SQLite was compiled mutexing code omitted due to
   104868 ** the SQLITE_THREADSAFE compile-time option being set to 0.
   104869 */
   104870 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
   104871 
   104872 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
   104873 /*
   104874 ** If the following function pointer is not NULL and if
   104875 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
   104876 ** I/O active are written using this function.  These messages
   104877 ** are intended for debugging activity only.
   104878 */
   104879 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
   104880 #endif
   104881 
   104882 /*
   104883 ** If the following global variable points to a string which is the
   104884 ** name of a directory, then that directory will be used to store
   104885 ** temporary files.
   104886 **
   104887 ** See also the "PRAGMA temp_store_directory" SQL command.
   104888 */
   104889 SQLITE_API char *sqlite3_temp_directory = 0;
   104890 
   104891 /*
   104892 ** Initialize SQLite.
   104893 **
   104894 ** This routine must be called to initialize the memory allocation,
   104895 ** VFS, and mutex subsystems prior to doing any serious work with
   104896 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
   104897 ** this routine will be called automatically by key routines such as
   104898 ** sqlite3_open().
   104899 **
   104900 ** This routine is a no-op except on its very first call for the process,
   104901 ** or for the first call after a call to sqlite3_shutdown.
   104902 **
   104903 ** The first thread to call this routine runs the initialization to
   104904 ** completion.  If subsequent threads call this routine before the first
   104905 ** thread has finished the initialization process, then the subsequent
   104906 ** threads must block until the first thread finishes with the initialization.
   104907 **
   104908 ** The first thread might call this routine recursively.  Recursive
   104909 ** calls to this routine should not block, of course.  Otherwise the
   104910 ** initialization process would never complete.
   104911 **
   104912 ** Let X be the first thread to enter this routine.  Let Y be some other
   104913 ** thread.  Then while the initial invocation of this routine by X is
   104914 ** incomplete, it is required that:
   104915 **
   104916 **    *  Calls to this routine from Y must block until the outer-most
   104917 **       call by X completes.
   104918 **
   104919 **    *  Recursive calls to this routine from thread X return immediately
   104920 **       without blocking.
   104921 */
   104922 SQLITE_API int sqlite3_initialize(void){
   104923   sqlite3_mutex *pMaster;                      /* The main static mutex */
   104924   int rc;                                      /* Result code */
   104925 
   104926 #ifdef SQLITE_OMIT_WSD
   104927   rc = sqlite3_wsd_init(4096, 24);
   104928   if( rc!=SQLITE_OK ){
   104929     return rc;
   104930   }
   104931 #endif
   104932 
   104933   /* If SQLite is already completely initialized, then this call
   104934   ** to sqlite3_initialize() should be a no-op.  But the initialization
   104935   ** must be complete.  So isInit must not be set until the very end
   104936   ** of this routine.
   104937   */
   104938   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
   104939 
   104940   /* Make sure the mutex subsystem is initialized.  If unable to
   104941   ** initialize the mutex subsystem, return early with the error.
   104942   ** If the system is so sick that we are unable to allocate a mutex,
   104943   ** there is not much SQLite is going to be able to do.
   104944   **
   104945   ** The mutex subsystem must take care of serializing its own
   104946   ** initialization.
   104947   */
   104948   rc = sqlite3MutexInit();
   104949   if( rc ) return rc;
   104950 
   104951   /* Initialize the malloc() system and the recursive pInitMutex mutex.
   104952   ** This operation is protected by the STATIC_MASTER mutex.  Note that
   104953   ** MutexAlloc() is called for a static mutex prior to initializing the
   104954   ** malloc subsystem - this implies that the allocation of a static
   104955   ** mutex must not require support from the malloc subsystem.
   104956   */
   104957   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
   104958   sqlite3_mutex_enter(pMaster);
   104959   sqlite3GlobalConfig.isMutexInit = 1;
   104960   if( !sqlite3GlobalConfig.isMallocInit ){
   104961     rc = sqlite3MallocInit();
   104962   }
   104963   if( rc==SQLITE_OK ){
   104964     sqlite3GlobalConfig.isMallocInit = 1;
   104965     if( !sqlite3GlobalConfig.pInitMutex ){
   104966       sqlite3GlobalConfig.pInitMutex =
   104967            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   104968       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
   104969         rc = SQLITE_NOMEM;
   104970       }
   104971     }
   104972   }
   104973   if( rc==SQLITE_OK ){
   104974     sqlite3GlobalConfig.nRefInitMutex++;
   104975   }
   104976   sqlite3_mutex_leave(pMaster);
   104977 
   104978   /* If rc is not SQLITE_OK at this point, then either the malloc
   104979   ** subsystem could not be initialized or the system failed to allocate
   104980   ** the pInitMutex mutex. Return an error in either case.  */
   104981   if( rc!=SQLITE_OK ){
   104982     return rc;
   104983   }
   104984 
   104985   /* Do the rest of the initialization under the recursive mutex so
   104986   ** that we will be able to handle recursive calls into
   104987   ** sqlite3_initialize().  The recursive calls normally come through
   104988   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
   104989   ** recursive calls might also be possible.
   104990   **
   104991   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
   104992   ** to the xInit method, so the xInit method need not be threadsafe.
   104993   **
   104994   ** The following mutex is what serializes access to the appdef pcache xInit
   104995   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
   104996   ** call to sqlite3PcacheInitialize().
   104997   */
   104998   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
   104999   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
   105000     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
   105001     sqlite3GlobalConfig.inProgress = 1;
   105002     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
   105003     sqlite3RegisterGlobalFunctions();
   105004     if( sqlite3GlobalConfig.isPCacheInit==0 ){
   105005       rc = sqlite3PcacheInitialize();
   105006     }
   105007     if( rc==SQLITE_OK ){
   105008       sqlite3GlobalConfig.isPCacheInit = 1;
   105009       rc = sqlite3OsInit();
   105010     }
   105011     if( rc==SQLITE_OK ){
   105012       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
   105013           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
   105014       sqlite3GlobalConfig.isInit = 1;
   105015     }
   105016     sqlite3GlobalConfig.inProgress = 0;
   105017   }
   105018   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
   105019 
   105020   /* Go back under the static mutex and clean up the recursive
   105021   ** mutex to prevent a resource leak.
   105022   */
   105023   sqlite3_mutex_enter(pMaster);
   105024   sqlite3GlobalConfig.nRefInitMutex--;
   105025   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
   105026     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
   105027     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
   105028     sqlite3GlobalConfig.pInitMutex = 0;
   105029   }
   105030   sqlite3_mutex_leave(pMaster);
   105031 
   105032   /* The following is just a sanity check to make sure SQLite has
   105033   ** been compiled correctly.  It is important to run this code, but
   105034   ** we don't want to run it too often and soak up CPU cycles for no
   105035   ** reason.  So we run it once during initialization.
   105036   */
   105037 #ifndef NDEBUG
   105038 #ifndef SQLITE_OMIT_FLOATING_POINT
   105039   /* This section of code's only "output" is via assert() statements. */
   105040   if ( rc==SQLITE_OK ){
   105041     u64 x = (((u64)1)<<63)-1;
   105042     double y;
   105043     assert(sizeof(x)==8);
   105044     assert(sizeof(x)==sizeof(y));
   105045     memcpy(&y, &x, 8);
   105046     assert( sqlite3IsNaN(y) );
   105047   }
   105048 #endif
   105049 #endif
   105050 
   105051   return rc;
   105052 }
   105053 
   105054 /*
   105055 ** Undo the effects of sqlite3_initialize().  Must not be called while
   105056 ** there are outstanding database connections or memory allocations or
   105057 ** while any part of SQLite is otherwise in use in any thread.  This
   105058 ** routine is not threadsafe.  But it is safe to invoke this routine
   105059 ** on when SQLite is already shut down.  If SQLite is already shut down
   105060 ** when this routine is invoked, then this routine is a harmless no-op.
   105061 */
   105062 SQLITE_API int sqlite3_shutdown(void){
   105063   if( sqlite3GlobalConfig.isInit ){
   105064     sqlite3_os_end();
   105065     sqlite3_reset_auto_extension();
   105066     sqlite3GlobalConfig.isInit = 0;
   105067   }
   105068   if( sqlite3GlobalConfig.isPCacheInit ){
   105069     sqlite3PcacheShutdown();
   105070     sqlite3GlobalConfig.isPCacheInit = 0;
   105071   }
   105072   if( sqlite3GlobalConfig.isMallocInit ){
   105073     sqlite3MallocEnd();
   105074     sqlite3GlobalConfig.isMallocInit = 0;
   105075   }
   105076   if( sqlite3GlobalConfig.isMutexInit ){
   105077     sqlite3MutexEnd();
   105078     sqlite3GlobalConfig.isMutexInit = 0;
   105079   }
   105080 
   105081   return SQLITE_OK;
   105082 }
   105083 
   105084 /*
   105085 ** This API allows applications to modify the global configuration of
   105086 ** the SQLite library at run-time.
   105087 **
   105088 ** This routine should only be called when there are no outstanding
   105089 ** database connections or memory allocations.  This routine is not
   105090 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
   105091 ** behavior.
   105092 */
   105093 SQLITE_API int sqlite3_config(int op, ...){
   105094   va_list ap;
   105095   int rc = SQLITE_OK;
   105096 
   105097   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
   105098   ** the SQLite library is in use. */
   105099   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
   105100 
   105101   va_start(ap, op);
   105102   switch( op ){
   105103 
   105104     /* Mutex configuration options are only available in a threadsafe
   105105     ** compile.
   105106     */
   105107 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
   105108     case SQLITE_CONFIG_SINGLETHREAD: {
   105109       /* Disable all mutexing */
   105110       sqlite3GlobalConfig.bCoreMutex = 0;
   105111       sqlite3GlobalConfig.bFullMutex = 0;
   105112       break;
   105113     }
   105114     case SQLITE_CONFIG_MULTITHREAD: {
   105115       /* Disable mutexing of database connections */
   105116       /* Enable mutexing of core data structures */
   105117       sqlite3GlobalConfig.bCoreMutex = 1;
   105118       sqlite3GlobalConfig.bFullMutex = 0;
   105119       break;
   105120     }
   105121     case SQLITE_CONFIG_SERIALIZED: {
   105122       /* Enable all mutexing */
   105123       sqlite3GlobalConfig.bCoreMutex = 1;
   105124       sqlite3GlobalConfig.bFullMutex = 1;
   105125       break;
   105126     }
   105127     case SQLITE_CONFIG_MUTEX: {
   105128       /* Specify an alternative mutex implementation */
   105129       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
   105130       break;
   105131     }
   105132     case SQLITE_CONFIG_GETMUTEX: {
   105133       /* Retrieve the current mutex implementation */
   105134       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
   105135       break;
   105136     }
   105137 #endif
   105138 
   105139 
   105140     case SQLITE_CONFIG_MALLOC: {
   105141       /* Specify an alternative malloc implementation */
   105142       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
   105143       break;
   105144     }
   105145     case SQLITE_CONFIG_GETMALLOC: {
   105146       /* Retrieve the current malloc() implementation */
   105147       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
   105148       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
   105149       break;
   105150     }
   105151     case SQLITE_CONFIG_MEMSTATUS: {
   105152       /* Enable or disable the malloc status collection */
   105153       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
   105154       break;
   105155     }
   105156     case SQLITE_CONFIG_SCRATCH: {
   105157       /* Designate a buffer for scratch memory space */
   105158       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
   105159       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
   105160       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
   105161       break;
   105162     }
   105163     case SQLITE_CONFIG_PAGECACHE: {
   105164       /* Designate a buffer for page cache memory space */
   105165       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   105166       sqlite3GlobalConfig.szPage = va_arg(ap, int);
   105167       sqlite3GlobalConfig.nPage = va_arg(ap, int);
   105168       break;
   105169     }
   105170 
   105171     case SQLITE_CONFIG_PCACHE: {
   105172       /* Specify an alternative page cache implementation */
   105173       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
   105174       break;
   105175     }
   105176 
   105177     case SQLITE_CONFIG_GETPCACHE: {
   105178       if( sqlite3GlobalConfig.pcache.xInit==0 ){
   105179         sqlite3PCacheSetDefault();
   105180       }
   105181       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
   105182       break;
   105183     }
   105184 
   105185 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   105186     case SQLITE_CONFIG_HEAP: {
   105187       /* Designate a buffer for heap memory space */
   105188       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
   105189       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
   105190       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
   105191 
   105192       if( sqlite3GlobalConfig.pHeap==0 ){
   105193         /* If the heap pointer is NULL, then restore the malloc implementation
   105194         ** back to NULL pointers too.  This will cause the malloc to go
   105195         ** back to its default implementation when sqlite3_initialize() is
   105196         ** run.
   105197         */
   105198         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
   105199       }else{
   105200         /* The heap pointer is not NULL, then install one of the
   105201         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
   105202         ** ENABLE_MEMSYS5 is defined, return an error.
   105203         */
   105204 #ifdef SQLITE_ENABLE_MEMSYS3
   105205         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
   105206 #endif
   105207 #ifdef SQLITE_ENABLE_MEMSYS5
   105208         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
   105209 #endif
   105210       }
   105211       break;
   105212     }
   105213 #endif
   105214 
   105215     case SQLITE_CONFIG_LOOKASIDE: {
   105216       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
   105217       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
   105218       break;
   105219     }
   105220 
   105221     /* Record a pointer to the logger funcction and its first argument.
   105222     ** The default is NULL.  Logging is disabled if the function pointer is
   105223     ** NULL.
   105224     */
   105225     case SQLITE_CONFIG_LOG: {
   105226       /* MSVC is picky about pulling func ptrs from va lists.
   105227       ** http://support.microsoft.com/kb/47961
   105228       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
   105229       */
   105230       typedef void(*LOGFUNC_t)(void*,int,const char*);
   105231       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
   105232       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
   105233       break;
   105234     }
   105235 
   105236     default: {
   105237       rc = SQLITE_ERROR;
   105238       break;
   105239     }
   105240   }
   105241   va_end(ap);
   105242   return rc;
   105243 }
   105244 
   105245 /*
   105246 ** Set up the lookaside buffers for a database connection.
   105247 ** Return SQLITE_OK on success.
   105248 ** If lookaside is already active, return SQLITE_BUSY.
   105249 **
   105250 ** The sz parameter is the number of bytes in each lookaside slot.
   105251 ** The cnt parameter is the number of slots.  If pStart is NULL the
   105252 ** space for the lookaside memory is obtained from sqlite3_malloc().
   105253 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
   105254 ** the lookaside memory.
   105255 */
   105256 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
   105257   void *pStart;
   105258   if( db->lookaside.nOut ){
   105259     return SQLITE_BUSY;
   105260   }
   105261   /* Free any existing lookaside buffer for this handle before
   105262   ** allocating a new one so we don't have to have space for
   105263   ** both at the same time.
   105264   */
   105265   if( db->lookaside.bMalloced ){
   105266     sqlite3_free(db->lookaside.pStart);
   105267   }
   105268   /* The size of a lookaside slot needs to be larger than a pointer
   105269   ** to be useful.
   105270   */
   105271   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   105272   if( cnt<0 ) cnt = 0;
   105273   if( sz==0 || cnt==0 ){
   105274     sz = 0;
   105275     pStart = 0;
   105276   }else if( pBuf==0 ){
   105277     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
   105278     sqlite3BeginBenignMalloc();
   105279     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   105280     sqlite3EndBenignMalloc();
   105281   }else{
   105282     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
   105283     pStart = pBuf;
   105284   }
   105285   db->lookaside.pStart = pStart;
   105286   db->lookaside.pFree = 0;
   105287   db->lookaside.sz = (u16)sz;
   105288   if( pStart ){
   105289     int i;
   105290     LookasideSlot *p;
   105291     assert( sz > (int)sizeof(LookasideSlot*) );
   105292     p = (LookasideSlot*)pStart;
   105293     for(i=cnt-1; i>=0; i--){
   105294       p->pNext = db->lookaside.pFree;
   105295       db->lookaside.pFree = p;
   105296       p = (LookasideSlot*)&((u8*)p)[sz];
   105297     }
   105298     db->lookaside.pEnd = p;
   105299     db->lookaside.bEnabled = 1;
   105300     db->lookaside.bMalloced = pBuf==0 ?1:0;
   105301   }else{
   105302     db->lookaside.pEnd = 0;
   105303     db->lookaside.bEnabled = 0;
   105304     db->lookaside.bMalloced = 0;
   105305   }
   105306   return SQLITE_OK;
   105307 }
   105308 
   105309 /*
   105310 ** Return the mutex associated with a database connection.
   105311 */
   105312 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   105313   return db->mutex;
   105314 }
   105315 
   105316 /*
   105317 ** Configuration settings for an individual database connection
   105318 */
   105319 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
   105320   va_list ap;
   105321   int rc;
   105322   va_start(ap, op);
   105323   switch( op ){
   105324     case SQLITE_DBCONFIG_LOOKASIDE: {
   105325       void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
   105326       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
   105327       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
   105328       rc = setupLookaside(db, pBuf, sz, cnt);
   105329       break;
   105330     }
   105331     default: {
   105332       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
   105333       break;
   105334     }
   105335   }
   105336   va_end(ap);
   105337   return rc;
   105338 }
   105339 
   105340 
   105341 /*
   105342 ** Return true if the buffer z[0..n-1] contains all spaces.
   105343 */
   105344 static int allSpaces(const char *z, int n){
   105345   while( n>0 && z[n-1]==' ' ){ n--; }
   105346   return n==0;
   105347 }
   105348 
   105349 /*
   105350 ** This is the default collating function named "BINARY" which is always
   105351 ** available.
   105352 **
   105353 ** If the padFlag argument is not NULL then space padding at the end
   105354 ** of strings is ignored.  This implements the RTRIM collation.
   105355 */
   105356 static int binCollFunc(
   105357   void *padFlag,
   105358   int nKey1, const void *pKey1,
   105359   int nKey2, const void *pKey2
   105360 ){
   105361   int rc, n;
   105362   n = nKey1<nKey2 ? nKey1 : nKey2;
   105363   rc = memcmp(pKey1, pKey2, n);
   105364   if( rc==0 ){
   105365     if( padFlag
   105366      && allSpaces(((char*)pKey1)+n, nKey1-n)
   105367      && allSpaces(((char*)pKey2)+n, nKey2-n)
   105368     ){
   105369       /* Leave rc unchanged at 0 */
   105370     }else{
   105371       rc = nKey1 - nKey2;
   105372     }
   105373   }
   105374   return rc;
   105375 }
   105376 
   105377 /*
   105378 ** Another built-in collating sequence: NOCASE.
   105379 **
   105380 ** This collating sequence is intended to be used for "case independant
   105381 ** comparison". SQLite's knowledge of upper and lower case equivalents
   105382 ** extends only to the 26 characters used in the English language.
   105383 **
   105384 ** At the moment there is only a UTF-8 implementation.
   105385 */
   105386 static int nocaseCollatingFunc(
   105387   void *NotUsed,
   105388   int nKey1, const void *pKey1,
   105389   int nKey2, const void *pKey2
   105390 ){
   105391   int r = sqlite3StrNICmp(
   105392       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
   105393   UNUSED_PARAMETER(NotUsed);
   105394   if( 0==r ){
   105395     r = nKey1-nKey2;
   105396   }
   105397   return r;
   105398 }
   105399 
   105400 /*
   105401 ** Return the ROWID of the most recent insert
   105402 */
   105403 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
   105404   return db->lastRowid;
   105405 }
   105406 
   105407 /*
   105408 ** Return the number of changes in the most recent call to sqlite3_exec().
   105409 */
   105410 SQLITE_API int sqlite3_changes(sqlite3 *db){
   105411   return db->nChange;
   105412 }
   105413 
   105414 /*
   105415 ** Return the number of changes since the database handle was opened.
   105416 */
   105417 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
   105418   return db->nTotalChange;
   105419 }
   105420 
   105421 /*
   105422 ** Close all open savepoints. This function only manipulates fields of the
   105423 ** database handle object, it does not close any savepoints that may be open
   105424 ** at the b-tree/pager level.
   105425 */
   105426 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
   105427   while( db->pSavepoint ){
   105428     Savepoint *pTmp = db->pSavepoint;
   105429     db->pSavepoint = pTmp->pNext;
   105430     sqlite3DbFree(db, pTmp);
   105431   }
   105432   db->nSavepoint = 0;
   105433   db->nStatement = 0;
   105434   db->isTransactionSavepoint = 0;
   105435 }
   105436 
   105437 /*
   105438 ** Invoke the destructor function associated with FuncDef p, if any. Except,
   105439 ** if this is not the last copy of the function, do not invoke it. Multiple
   105440 ** copies of a single function are created when create_function() is called
   105441 ** with SQLITE_ANY as the encoding.
   105442 */
   105443 static void functionDestroy(sqlite3 *db, FuncDef *p){
   105444   FuncDestructor *pDestructor = p->pDestructor;
   105445   if( pDestructor ){
   105446     pDestructor->nRef--;
   105447     if( pDestructor->nRef==0 ){
   105448       pDestructor->xDestroy(pDestructor->pUserData);
   105449       sqlite3DbFree(db, pDestructor);
   105450     }
   105451   }
   105452 }
   105453 
   105454 /*
   105455 ** Close an existing SQLite database
   105456 */
   105457 SQLITE_API int sqlite3_close(sqlite3 *db){
   105458   HashElem *i;                    /* Hash table iterator */
   105459   int j;
   105460 
   105461   if( !db ){
   105462     return SQLITE_OK;
   105463   }
   105464   if( !sqlite3SafetyCheckSickOrOk(db) ){
   105465     return SQLITE_MISUSE_BKPT;
   105466   }
   105467   sqlite3_mutex_enter(db->mutex);
   105468 
   105469   sqlite3ResetInternalSchema(db, 0);
   105470 
   105471   /* If a transaction is open, the ResetInternalSchema() call above
   105472   ** will not have called the xDisconnect() method on any virtual
   105473   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
   105474   ** call will do so. We need to do this before the check for active
   105475   ** SQL statements below, as the v-table implementation may be storing
   105476   ** some prepared statements internally.
   105477   */
   105478   sqlite3VtabRollback(db);
   105479 
   105480   /* If there are any outstanding VMs, return SQLITE_BUSY. */
   105481   if( db->pVdbe ){
   105482     // Begin Android Change
   105483     // print the first unfinalized statement in the error message, to help the developer
   105484     // figure out what the unfinalized statement is.
   105485     char buff[120];
   105486     snprintf(buff, sizeof(buff), "%d,%s", (int)db->pVdbe, db->pVdbe->zSql);
   105487     sqlite3Error(db, SQLITE_UNCLOSED, buff);
   105488     // End Android Change
   105489 
   105490     sqlite3_mutex_leave(db->mutex);
   105491     return SQLITE_UNCLOSED;
   105492   }
   105493   assert( sqlite3SafetyCheckSickOrOk(db) );
   105494 
   105495   for(j=0; j<db->nDb; j++){
   105496     Btree *pBt = db->aDb[j].pBt;
   105497     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
   105498       sqlite3Error(db, SQLITE_BUSY,
   105499           "unable to close due to unfinished backup operation");
   105500       sqlite3_mutex_leave(db->mutex);
   105501       return SQLITE_BUSY;
   105502     }
   105503   }
   105504 
   105505   /* Free any outstanding Savepoint structures. */
   105506   sqlite3CloseSavepoints(db);
   105507 
   105508   for(j=0; j<db->nDb; j++){
   105509     struct Db *pDb = &db->aDb[j];
   105510     if( pDb->pBt ){
   105511       sqlite3BtreeClose(pDb->pBt);
   105512       pDb->pBt = 0;
   105513       if( j!=1 ){
   105514         pDb->pSchema = 0;
   105515       }
   105516     }
   105517   }
   105518   sqlite3ResetInternalSchema(db, 0);
   105519 
   105520   /* Tell the code in notify.c that the connection no longer holds any
   105521   ** locks and does not require any further unlock-notify callbacks.
   105522   */
   105523   sqlite3ConnectionClosed(db);
   105524 
   105525   assert( db->nDb<=2 );
   105526   assert( db->aDb==db->aDbStatic );
   105527   for(j=0; j<ArraySize(db->aFunc.a); j++){
   105528     FuncDef *pNext, *pHash, *p;
   105529     for(p=db->aFunc.a[j]; p; p=pHash){
   105530       pHash = p->pHash;
   105531       while( p ){
   105532         functionDestroy(db, p);
   105533         pNext = p->pNext;
   105534         sqlite3DbFree(db, p);
   105535         p = pNext;
   105536       }
   105537     }
   105538   }
   105539   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
   105540     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
   105541     /* Invoke any destructors registered for collation sequence user data. */
   105542     for(j=0; j<3; j++){
   105543       if( pColl[j].xDel ){
   105544         pColl[j].xDel(pColl[j].pUser);
   105545       }
   105546     }
   105547     sqlite3DbFree(db, pColl);
   105548   }
   105549   sqlite3HashClear(&db->aCollSeq);
   105550 #ifndef SQLITE_OMIT_VIRTUALTABLE
   105551   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
   105552     Module *pMod = (Module *)sqliteHashData(i);
   105553     if( pMod->xDestroy ){
   105554       pMod->xDestroy(pMod->pAux);
   105555     }
   105556     sqlite3DbFree(db, pMod);
   105557   }
   105558   sqlite3HashClear(&db->aModule);
   105559 #endif
   105560 
   105561   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
   105562   if( db->pErr ){
   105563     sqlite3ValueFree(db->pErr);
   105564   }
   105565   sqlite3CloseExtensions(db);
   105566 
   105567   db->magic = SQLITE_MAGIC_ERROR;
   105568 
   105569   /* The temp-database schema is allocated differently from the other schema
   105570   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   105571   ** So it needs to be freed here. Todo: Why not roll the temp schema into
   105572   ** the same sqliteMalloc() as the one that allocates the database
   105573   ** structure?
   105574   */
   105575   sqlite3DbFree(db, db->aDb[1].pSchema);
   105576   sqlite3_mutex_leave(db->mutex);
   105577   db->magic = SQLITE_MAGIC_CLOSED;
   105578   sqlite3_mutex_free(db->mutex);
   105579   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
   105580   if( db->lookaside.bMalloced ){
   105581     sqlite3_free(db->lookaside.pStart);
   105582   }
   105583   sqlite3_free(db);
   105584   return SQLITE_OK;
   105585 }
   105586 
   105587 /*
   105588 ** Rollback all database files.
   105589 */
   105590 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
   105591   int i;
   105592   int inTrans = 0;
   105593   assert( sqlite3_mutex_held(db->mutex) );
   105594   sqlite3BeginBenignMalloc();
   105595   for(i=0; i<db->nDb; i++){
   105596     if( db->aDb[i].pBt ){
   105597       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
   105598         inTrans = 1;
   105599       }
   105600       sqlite3BtreeRollback(db->aDb[i].pBt);
   105601       db->aDb[i].inTrans = 0;
   105602     }
   105603   }
   105604   sqlite3VtabRollback(db);
   105605   sqlite3EndBenignMalloc();
   105606 
   105607   if( db->flags&SQLITE_InternChanges ){
   105608     sqlite3ExpirePreparedStatements(db);
   105609     sqlite3ResetInternalSchema(db, 0);
   105610   }
   105611 
   105612   /* Any deferred constraint violations have now been resolved. */
   105613   db->nDeferredCons = 0;
   105614 
   105615   /* If one has been configured, invoke the rollback-hook callback */
   105616   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
   105617     db->xRollbackCallback(db->pRollbackArg);
   105618   }
   105619 }
   105620 
   105621 /*
   105622 ** Return a static string that describes the kind of error specified in the
   105623 ** argument.
   105624 */
   105625 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
   105626   static const char* const aMsg[] = {
   105627     /* SQLITE_OK          */ "not an error",
   105628     /* SQLITE_ERROR       */ "SQL logic error or missing database",
   105629     /* SQLITE_INTERNAL    */ 0,
   105630     /* SQLITE_PERM        */ "access permission denied",
   105631     /* SQLITE_ABORT       */ "callback requested query abort",
   105632     /* SQLITE_BUSY        */ "database is locked",
   105633     /* SQLITE_LOCKED      */ "database table is locked",
   105634     /* SQLITE_NOMEM       */ "out of memory",
   105635     /* SQLITE_READONLY    */ "attempt to write a readonly database",
   105636     /* SQLITE_INTERRUPT   */ "interrupted",
   105637     /* SQLITE_IOERR       */ "disk I/O error",
   105638     /* SQLITE_CORRUPT     */ "database disk image is malformed",
   105639     /* SQLITE_NOTFOUND    */ 0,
   105640     /* SQLITE_FULL        */ "database or disk is full",
   105641     /* SQLITE_CANTOPEN    */ "unable to open database file",
   105642     /* SQLITE_PROTOCOL    */ "locking protocol",
   105643     /* SQLITE_EMPTY       */ "table contains no data",
   105644     /* SQLITE_SCHEMA      */ "database schema has changed",
   105645     /* SQLITE_TOOBIG      */ "string or blob too big",
   105646     /* SQLITE_CONSTRAINT  */ "constraint failed",
   105647     /* SQLITE_MISMATCH    */ "datatype mismatch",
   105648     /* SQLITE_MISUSE      */ "library routine called out of sequence",
   105649     /* SQLITE_NOLFS       */ "large file support is disabled",
   105650     /* SQLITE_AUTH        */ "authorization denied",
   105651     /* SQLITE_FORMAT      */ "auxiliary database format error",
   105652     /* SQLITE_RANGE       */ "bind or column index out of range",
   105653     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
   105654   };
   105655   rc &= 0xff;
   105656   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
   105657     return aMsg[rc];
   105658   }else{
   105659     return "unknown error";
   105660   }
   105661 }
   105662 
   105663 /*
   105664 ** This routine implements a busy callback that sleeps and tries
   105665 ** again until a timeout value is reached.  The timeout value is
   105666 ** an integer number of milliseconds passed in as the first
   105667 ** argument.
   105668 */
   105669 static int sqliteDefaultBusyCallback(
   105670  void *ptr,               /* Database connection */
   105671  int count                /* Number of times table has been busy */
   105672 ){
   105673 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
   105674   static const u8 delays[] =
   105675      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
   105676   static const u8 totals[] =
   105677      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
   105678 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
   105679   sqlite3 *db = (sqlite3 *)ptr;
   105680   int timeout = db->busyTimeout;
   105681   int delay, prior;
   105682 
   105683   assert( count>=0 );
   105684   if( count < NDELAY ){
   105685     delay = delays[count];
   105686     prior = totals[count];
   105687   }else{
   105688     delay = delays[NDELAY-1];
   105689     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
   105690   }
   105691   if( prior + delay > timeout ){
   105692     delay = timeout - prior;
   105693     if( delay<=0 ) return 0;
   105694   }
   105695   sqlite3OsSleep(db->pVfs, delay*1000);
   105696   return 1;
   105697 #else
   105698   sqlite3 *db = (sqlite3 *)ptr;
   105699   int timeout = ((sqlite3 *)ptr)->busyTimeout;
   105700   if( (count+1)*1000 > timeout ){
   105701     return 0;
   105702   }
   105703   sqlite3OsSleep(db->pVfs, 1000000);
   105704   return 1;
   105705 #endif
   105706 }
   105707 
   105708 /*
   105709 ** Invoke the given busy handler.
   105710 **
   105711 ** This routine is called when an operation failed with a lock.
   105712 ** If this routine returns non-zero, the lock is retried.  If it
   105713 ** returns 0, the operation aborts with an SQLITE_BUSY error.
   105714 */
   105715 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   105716   int rc;
   105717   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
   105718   rc = p->xFunc(p->pArg, p->nBusy);
   105719   if( rc==0 ){
   105720     p->nBusy = -1;
   105721   }else{
   105722     p->nBusy++;
   105723   }
   105724   return rc;
   105725 }
   105726 
   105727 /*
   105728 ** This routine sets the busy callback for an Sqlite database to the
   105729 ** given callback function with the given argument.
   105730 */
   105731 SQLITE_API int sqlite3_busy_handler(
   105732   sqlite3 *db,
   105733   int (*xBusy)(void*,int),
   105734   void *pArg
   105735 ){
   105736   sqlite3_mutex_enter(db->mutex);
   105737   db->busyHandler.xFunc = xBusy;
   105738   db->busyHandler.pArg = pArg;
   105739   db->busyHandler.nBusy = 0;
   105740   sqlite3_mutex_leave(db->mutex);
   105741   return SQLITE_OK;
   105742 }
   105743 
   105744 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   105745 /*
   105746 ** This routine sets the progress callback for an Sqlite database to the
   105747 ** given callback function with the given argument. The progress callback will
   105748 ** be invoked every nOps opcodes.
   105749 */
   105750 SQLITE_API void sqlite3_progress_handler(
   105751   sqlite3 *db,
   105752   int nOps,
   105753   int (*xProgress)(void*),
   105754   void *pArg
   105755 ){
   105756   sqlite3_mutex_enter(db->mutex);
   105757   if( nOps>0 ){
   105758     db->xProgress = xProgress;
   105759     db->nProgressOps = nOps;
   105760     db->pProgressArg = pArg;
   105761   }else{
   105762     db->xProgress = 0;
   105763     db->nProgressOps = 0;
   105764     db->pProgressArg = 0;
   105765   }
   105766   sqlite3_mutex_leave(db->mutex);
   105767 }
   105768 #endif
   105769 
   105770 
   105771 /*
   105772 ** This routine installs a default busy handler that waits for the
   105773 ** specified number of milliseconds before returning 0.
   105774 */
   105775 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
   105776   if( ms>0 ){
   105777     db->busyTimeout = ms;
   105778     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
   105779   }else{
   105780     sqlite3_busy_handler(db, 0, 0);
   105781   }
   105782   return SQLITE_OK;
   105783 }
   105784 
   105785 /*
   105786 ** Cause any pending operation to stop at its earliest opportunity.
   105787 */
   105788 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
   105789   db->u1.isInterrupted = 1;
   105790 }
   105791 
   105792 
   105793 /*
   105794 ** This function is exactly the same as sqlite3_create_function(), except
   105795 ** that it is designed to be called by internal code. The difference is
   105796 ** that if a malloc() fails in sqlite3_create_function(), an error code
   105797 ** is returned and the mallocFailed flag cleared.
   105798 */
   105799 SQLITE_PRIVATE int sqlite3CreateFunc(
   105800   sqlite3 *db,
   105801   const char *zFunctionName,
   105802   int nArg,
   105803   int enc,
   105804   void *pUserData,
   105805   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   105806   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   105807   void (*xFinal)(sqlite3_context*),
   105808   FuncDestructor *pDestructor
   105809 ){
   105810   FuncDef *p;
   105811   int nName;
   105812 
   105813   assert( sqlite3_mutex_held(db->mutex) );
   105814   if( zFunctionName==0 ||
   105815       (xFunc && (xFinal || xStep)) ||
   105816       (!xFunc && (xFinal && !xStep)) ||
   105817       (!xFunc && (!xFinal && xStep)) ||
   105818       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
   105819       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
   105820     return SQLITE_MISUSE_BKPT;
   105821   }
   105822 
   105823 #ifndef SQLITE_OMIT_UTF16
   105824   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   105825   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   105826   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   105827   **
   105828   ** If SQLITE_ANY is specified, add three versions of the function
   105829   ** to the hash table.
   105830   */
   105831   if( enc==SQLITE_UTF16 ){
   105832     enc = SQLITE_UTF16NATIVE;
   105833   }else if( enc==SQLITE_ANY ){
   105834     int rc;
   105835     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
   105836          pUserData, xFunc, xStep, xFinal, pDestructor);
   105837     if( rc==SQLITE_OK ){
   105838       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
   105839           pUserData, xFunc, xStep, xFinal, pDestructor);
   105840     }
   105841     if( rc!=SQLITE_OK ){
   105842       return rc;
   105843     }
   105844     enc = SQLITE_UTF16BE;
   105845   }
   105846 #else
   105847   enc = SQLITE_UTF8;
   105848 #endif
   105849 
   105850   /* Check if an existing function is being overridden or deleted. If so,
   105851   ** and there are active VMs, then return SQLITE_BUSY. If a function
   105852   ** is being overridden/deleted but there are no active VMs, allow the
   105853   ** operation to continue but invalidate all precompiled statements.
   105854   */
   105855   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
   105856   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
   105857     if( db->activeVdbeCnt ){
   105858       sqlite3Error(db, SQLITE_BUSY,
   105859         "unable to delete/modify user-function due to active statements");
   105860       assert( !db->mallocFailed );
   105861       return SQLITE_BUSY;
   105862     }else{
   105863       sqlite3ExpirePreparedStatements(db);
   105864     }
   105865   }
   105866 
   105867   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
   105868   assert(p || db->mallocFailed);
   105869   if( !p ){
   105870     return SQLITE_NOMEM;
   105871   }
   105872 
   105873   /* If an older version of the function with a configured destructor is
   105874   ** being replaced invoke the destructor function here. */
   105875   functionDestroy(db, p);
   105876 
   105877   if( pDestructor ){
   105878     pDestructor->nRef++;
   105879   }
   105880   p->pDestructor = pDestructor;
   105881   p->flags = 0;
   105882   p->xFunc = xFunc;
   105883   p->xStep = xStep;
   105884   p->xFinalize = xFinal;
   105885   p->pUserData = pUserData;
   105886   p->nArg = (u16)nArg;
   105887   return SQLITE_OK;
   105888 }
   105889 
   105890 /*
   105891 ** Create new user functions.
   105892 */
   105893 SQLITE_API int sqlite3_create_function(
   105894   sqlite3 *db,
   105895   const char *zFunc,
   105896   int nArg,
   105897   int enc,
   105898   void *p,
   105899   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   105900   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   105901   void (*xFinal)(sqlite3_context*)
   105902 ){
   105903   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
   105904                                     xFinal, 0);
   105905 }
   105906 
   105907 SQLITE_API int sqlite3_create_function_v2(
   105908   sqlite3 *db,
   105909   const char *zFunc,
   105910   int nArg,
   105911   int enc,
   105912   void *p,
   105913   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
   105914   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
   105915   void (*xFinal)(sqlite3_context*),
   105916   void (*xDestroy)(void *)
   105917 ){
   105918   int rc = SQLITE_ERROR;
   105919   FuncDestructor *pArg = 0;
   105920   sqlite3_mutex_enter(db->mutex);
   105921   if( xDestroy ){
   105922     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
   105923     if( !pArg ){
   105924       xDestroy(p);
   105925       goto out;
   105926     }
   105927     pArg->xDestroy = xDestroy;
   105928     pArg->pUserData = p;
   105929   }
   105930   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
   105931   if( pArg && pArg->nRef==0 ){
   105932     assert( rc!=SQLITE_OK );
   105933     xDestroy(p);
   105934     sqlite3DbFree(db, pArg);
   105935   }
   105936 
   105937  out:
   105938   rc = sqlite3ApiExit(db, rc);
   105939   sqlite3_mutex_leave(db->mutex);
   105940   return rc;
   105941 }
   105942 
   105943 #ifndef SQLITE_OMIT_UTF16
   105944 SQLITE_API int sqlite3_create_function16(
   105945   sqlite3 *db,
   105946   const void *zFunctionName,
   105947   int nArg,
   105948   int eTextRep,
   105949   void *p,
   105950   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   105951   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   105952   void (*xFinal)(sqlite3_context*)
   105953 ){
   105954   int rc;
   105955   char *zFunc8;
   105956   sqlite3_mutex_enter(db->mutex);
   105957   assert( !db->mallocFailed );
   105958   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
   105959   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
   105960   sqlite3DbFree(db, zFunc8);
   105961   rc = sqlite3ApiExit(db, rc);
   105962   sqlite3_mutex_leave(db->mutex);
   105963   return rc;
   105964 }
   105965 #endif
   105966 
   105967 
   105968 /*
   105969 ** Declare that a function has been overloaded by a virtual table.
   105970 **
   105971 ** If the function already exists as a regular global function, then
   105972 ** this routine is a no-op.  If the function does not exist, then create
   105973 ** a new one that always throws a run-time error.
   105974 **
   105975 ** When virtual tables intend to provide an overloaded function, they
   105976 ** should call this routine to make sure the global function exists.
   105977 ** A global function must exist in order for name resolution to work
   105978 ** properly.
   105979 */
   105980 SQLITE_API int sqlite3_overload_function(
   105981   sqlite3 *db,
   105982   const char *zName,
   105983   int nArg
   105984 ){
   105985   int nName = sqlite3Strlen30(zName);
   105986   int rc;
   105987   sqlite3_mutex_enter(db->mutex);
   105988   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
   105989     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
   105990                       0, sqlite3InvalidFunction, 0, 0, 0);
   105991   }
   105992   rc = sqlite3ApiExit(db, SQLITE_OK);
   105993   sqlite3_mutex_leave(db->mutex);
   105994   return rc;
   105995 }
   105996 
   105997 #ifndef SQLITE_OMIT_TRACE
   105998 /*
   105999 ** Register a trace function.  The pArg from the previously registered trace
   106000 ** is returned.
   106001 **
   106002 ** A NULL trace function means that no tracing is executes.  A non-NULL
   106003 ** trace is a pointer to a function that is invoked at the start of each
   106004 ** SQL statement.
   106005 */
   106006 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
   106007   void *pOld;
   106008   sqlite3_mutex_enter(db->mutex);
   106009   pOld = db->pTraceArg;
   106010   db->xTrace = xTrace;
   106011   db->pTraceArg = pArg;
   106012   sqlite3_mutex_leave(db->mutex);
   106013   return pOld;
   106014 }
   106015 /*
   106016 ** Register a profile function.  The pArg from the previously registered
   106017 ** profile function is returned.
   106018 **
   106019 ** A NULL profile function means that no profiling is executes.  A non-NULL
   106020 ** profile is a pointer to a function that is invoked at the conclusion of
   106021 ** each SQL statement that is run.
   106022 */
   106023 SQLITE_API void *sqlite3_profile(
   106024   sqlite3 *db,
   106025   void (*xProfile)(void*,const char*,sqlite_uint64),
   106026   void *pArg
   106027 ){
   106028   void *pOld;
   106029   sqlite3_mutex_enter(db->mutex);
   106030   pOld = db->pProfileArg;
   106031   db->xProfile = xProfile;
   106032   db->pProfileArg = pArg;
   106033   sqlite3_mutex_leave(db->mutex);
   106034   return pOld;
   106035 }
   106036 #endif /* SQLITE_OMIT_TRACE */
   106037 
   106038 /*** EXPERIMENTAL ***
   106039 **
   106040 ** Register a function to be invoked when a transaction comments.
   106041 ** If the invoked function returns non-zero, then the commit becomes a
   106042 ** rollback.
   106043 */
   106044 SQLITE_API void *sqlite3_commit_hook(
   106045   sqlite3 *db,              /* Attach the hook to this database */
   106046   int (*xCallback)(void*),  /* Function to invoke on each commit */
   106047   void *pArg                /* Argument to the function */
   106048 ){
   106049   void *pOld;
   106050   sqlite3_mutex_enter(db->mutex);
   106051   pOld = db->pCommitArg;
   106052   db->xCommitCallback = xCallback;
   106053   db->pCommitArg = pArg;
   106054   sqlite3_mutex_leave(db->mutex);
   106055   return pOld;
   106056 }
   106057 
   106058 /*
   106059 ** Register a callback to be invoked each time a row is updated,
   106060 ** inserted or deleted using this database connection.
   106061 */
   106062 SQLITE_API void *sqlite3_update_hook(
   106063   sqlite3 *db,              /* Attach the hook to this database */
   106064   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
   106065   void *pArg                /* Argument to the function */
   106066 ){
   106067   void *pRet;
   106068   sqlite3_mutex_enter(db->mutex);
   106069   pRet = db->pUpdateArg;
   106070   db->xUpdateCallback = xCallback;
   106071   db->pUpdateArg = pArg;
   106072   sqlite3_mutex_leave(db->mutex);
   106073   return pRet;
   106074 }
   106075 
   106076 /*
   106077 ** Register a callback to be invoked each time a transaction is rolled
   106078 ** back by this database connection.
   106079 */
   106080 SQLITE_API void *sqlite3_rollback_hook(
   106081   sqlite3 *db,              /* Attach the hook to this database */
   106082   void (*xCallback)(void*), /* Callback function */
   106083   void *pArg                /* Argument to the function */
   106084 ){
   106085   void *pRet;
   106086   sqlite3_mutex_enter(db->mutex);
   106087   pRet = db->pRollbackArg;
   106088   db->xRollbackCallback = xCallback;
   106089   db->pRollbackArg = pArg;
   106090   sqlite3_mutex_leave(db->mutex);
   106091   return pRet;
   106092 }
   106093 
   106094 #ifndef SQLITE_OMIT_WAL
   106095 /*
   106096 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
   106097 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
   106098 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
   106099 ** wal_autocheckpoint()).
   106100 */
   106101 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   106102   void *pClientData,     /* Argument */
   106103   sqlite3 *db,           /* Connection */
   106104   const char *zDb,       /* Database */
   106105   int nFrame             /* Size of WAL */
   106106 ){
   106107   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
   106108     sqlite3BeginBenignMalloc();
   106109     sqlite3_wal_checkpoint(db, zDb);
   106110     sqlite3EndBenignMalloc();
   106111   }
   106112   return SQLITE_OK;
   106113 }
   106114 #endif /* SQLITE_OMIT_WAL */
   106115 
   106116 /*
   106117 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
   106118 ** a database after committing a transaction if there are nFrame or
   106119 ** more frames in the log file. Passing zero or a negative value as the
   106120 ** nFrame parameter disables automatic checkpoints entirely.
   106121 **
   106122 ** The callback registered by this function replaces any existing callback
   106123 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
   106124 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
   106125 ** configured by this function.
   106126 */
   106127 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
   106128 #ifdef SQLITE_OMIT_WAL
   106129   UNUSED_PARAMETER(db);
   106130   UNUSED_PARAMETER(nFrame);
   106131 #else
   106132   if( nFrame>0 ){
   106133     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
   106134   }else{
   106135     sqlite3_wal_hook(db, 0, 0);
   106136   }
   106137 #endif
   106138   return SQLITE_OK;
   106139 }
   106140 
   106141 /*
   106142 ** Register a callback to be invoked each time a transaction is written
   106143 ** into the write-ahead-log by this database connection.
   106144 */
   106145 SQLITE_API void *sqlite3_wal_hook(
   106146   sqlite3 *db,                    /* Attach the hook to this db handle */
   106147   int(*xCallback)(void *, sqlite3*, const char*, int),
   106148   void *pArg                      /* First argument passed to xCallback() */
   106149 ){
   106150 #ifndef SQLITE_OMIT_WAL
   106151   void *pRet;
   106152   sqlite3_mutex_enter(db->mutex);
   106153   pRet = db->pWalArg;
   106154   db->xWalCallback = xCallback;
   106155   db->pWalArg = pArg;
   106156   sqlite3_mutex_leave(db->mutex);
   106157   return pRet;
   106158 #else
   106159   return 0;
   106160 #endif
   106161 }
   106162 
   106163 
   106164 /*
   106165 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
   106166 ** to contains a zero-length string, all attached databases are
   106167 ** checkpointed.
   106168 */
   106169 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
   106170 #ifdef SQLITE_OMIT_WAL
   106171   return SQLITE_OK;
   106172 #else
   106173   int rc;                         /* Return code */
   106174   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
   106175 
   106176   sqlite3_mutex_enter(db->mutex);
   106177   if( zDb && zDb[0] ){
   106178     iDb = sqlite3FindDbName(db, zDb);
   106179   }
   106180   if( iDb<0 ){
   106181     rc = SQLITE_ERROR;
   106182     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
   106183   }else{
   106184     rc = sqlite3Checkpoint(db, iDb);
   106185     sqlite3Error(db, rc, 0);
   106186   }
   106187   rc = sqlite3ApiExit(db, rc);
   106188   sqlite3_mutex_leave(db->mutex);
   106189   return rc;
   106190 #endif
   106191 }
   106192 
   106193 #ifndef SQLITE_OMIT_WAL
   106194 /*
   106195 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
   106196 ** not currently open in WAL mode.
   106197 **
   106198 ** If a transaction is open on the database being checkpointed, this
   106199 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
   106200 ** an error occurs while running the checkpoint, an SQLite error code is
   106201 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
   106202 **
   106203 ** The mutex on database handle db should be held by the caller. The mutex
   106204 ** associated with the specific b-tree being checkpointed is taken by
   106205 ** this function while the checkpoint is running.
   106206 **
   106207 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
   106208 ** checkpointed. If an error is encountered it is returned immediately -
   106209 ** no attempt is made to checkpoint any remaining databases.
   106210 */
   106211 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
   106212   int rc = SQLITE_OK;             /* Return code */
   106213   int i;                          /* Used to iterate through attached dbs */
   106214 
   106215   assert( sqlite3_mutex_held(db->mutex) );
   106216 
   106217   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
   106218     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
   106219       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
   106220     }
   106221   }
   106222 
   106223   return rc;
   106224 }
   106225 #endif /* SQLITE_OMIT_WAL */
   106226 
   106227 /*
   106228 ** This function returns true if main-memory should be used instead of
   106229 ** a temporary file for transient pager files and statement journals.
   106230 ** The value returned depends on the value of db->temp_store (runtime
   106231 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
   106232 ** following table describes the relationship between these two values
   106233 ** and this functions return value.
   106234 **
   106235 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
   106236 **   -----------------     --------------     ------------------------------
   106237 **   0                     any                file      (return 0)
   106238 **   1                     1                  file      (return 0)
   106239 **   1                     2                  memory    (return 1)
   106240 **   1                     0                  file      (return 0)
   106241 **   2                     1                  file      (return 0)
   106242 **   2                     2                  memory    (return 1)
   106243 **   2                     0                  memory    (return 1)
   106244 **   3                     any                memory    (return 1)
   106245 */
   106246 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
   106247 #if SQLITE_TEMP_STORE==1
   106248   return ( db->temp_store==2 );
   106249 #endif
   106250 #if SQLITE_TEMP_STORE==2
   106251   return ( db->temp_store!=1 );
   106252 #endif
   106253 #if SQLITE_TEMP_STORE==3
   106254   return 1;
   106255 #endif
   106256 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
   106257   return 0;
   106258 #endif
   106259 }
   106260 
   106261 /*
   106262 ** Return UTF-8 encoded English language explanation of the most recent
   106263 ** error.
   106264 */
   106265 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
   106266   const char *z;
   106267   if( !db ){
   106268     return sqlite3ErrStr(SQLITE_NOMEM);
   106269   }
   106270   if( !sqlite3SafetyCheckSickOrOk(db) ){
   106271     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
   106272   }
   106273   sqlite3_mutex_enter(db->mutex);
   106274   if( db->mallocFailed ){
   106275     z = sqlite3ErrStr(SQLITE_NOMEM);
   106276   }else{
   106277     z = (char*)sqlite3_value_text(db->pErr);
   106278     assert( !db->mallocFailed );
   106279     if( z==0 ){
   106280       z = sqlite3ErrStr(db->errCode);
   106281     }
   106282   }
   106283   sqlite3_mutex_leave(db->mutex);
   106284   return z;
   106285 }
   106286 
   106287 #ifndef SQLITE_OMIT_UTF16
   106288 /*
   106289 ** Return UTF-16 encoded English language explanation of the most recent
   106290 ** error.
   106291 */
   106292 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
   106293   static const u16 outOfMem[] = {
   106294     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
   106295   };
   106296   static const u16 misuse[] = {
   106297     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
   106298     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
   106299     'c', 'a', 'l', 'l', 'e', 'd', ' ',
   106300     'o', 'u', 't', ' ',
   106301     'o', 'f', ' ',
   106302     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
   106303   };
   106304 
   106305   const void *z;
   106306   if( !db ){
   106307     return (void *)outOfMem;
   106308   }
   106309   if( !sqlite3SafetyCheckSickOrOk(db) ){
   106310     return (void *)misuse;
   106311   }
   106312   sqlite3_mutex_enter(db->mutex);
   106313   if( db->mallocFailed ){
   106314     z = (void *)outOfMem;
   106315   }else{
   106316     z = sqlite3_value_text16(db->pErr);
   106317     if( z==0 ){
   106318       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
   106319            SQLITE_UTF8, SQLITE_STATIC);
   106320       z = sqlite3_value_text16(db->pErr);
   106321     }
   106322     /* A malloc() may have failed within the call to sqlite3_value_text16()
   106323     ** above. If this is the case, then the db->mallocFailed flag needs to
   106324     ** be cleared before returning. Do this directly, instead of via
   106325     ** sqlite3ApiExit(), to avoid setting the database handle error message.
   106326     */
   106327     db->mallocFailed = 0;
   106328   }
   106329   sqlite3_mutex_leave(db->mutex);
   106330   return z;
   106331 }
   106332 #endif /* SQLITE_OMIT_UTF16 */
   106333 
   106334 /*
   106335 ** Return the most recent error code generated by an SQLite routine. If NULL is
   106336 ** passed to this function, we assume a malloc() failed during sqlite3_open().
   106337 */
   106338 SQLITE_API int sqlite3_errcode(sqlite3 *db){
   106339   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   106340     return SQLITE_MISUSE_BKPT;
   106341   }
   106342   if( !db || db->mallocFailed ){
   106343     return SQLITE_NOMEM;
   106344   }
   106345   return db->errCode & db->errMask;
   106346 }
   106347 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
   106348   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
   106349     return SQLITE_MISUSE_BKPT;
   106350   }
   106351   if( !db || db->mallocFailed ){
   106352     return SQLITE_NOMEM;
   106353   }
   106354   return db->errCode;
   106355 }
   106356 
   106357 /*
   106358 ** Create a new collating function for database "db".  The name is zName
   106359 ** and the encoding is enc.
   106360 */
   106361 static int createCollation(
   106362   sqlite3* db,
   106363   const char *zName,
   106364   u8 enc,
   106365   u8 collType,
   106366   void* pCtx,
   106367   int(*xCompare)(void*,int,const void*,int,const void*),
   106368   void(*xDel)(void*)
   106369 ){
   106370   CollSeq *pColl;
   106371   int enc2;
   106372   int nName = sqlite3Strlen30(zName);
   106373 
   106374   assert( sqlite3_mutex_held(db->mutex) );
   106375 
   106376   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   106377   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
   106378   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
   106379   */
   106380   enc2 = enc;
   106381   testcase( enc2==SQLITE_UTF16 );
   106382   testcase( enc2==SQLITE_UTF16_ALIGNED );
   106383   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
   106384     enc2 = SQLITE_UTF16NATIVE;
   106385   }
   106386   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
   106387     return SQLITE_MISUSE_BKPT;
   106388   }
   106389 
   106390   /* Check if this call is removing or replacing an existing collation
   106391   ** sequence. If so, and there are active VMs, return busy. If there
   106392   ** are no active VMs, invalidate any pre-compiled statements.
   106393   */
   106394   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   106395   if( pColl && pColl->xCmp ){
   106396     if( db->activeVdbeCnt ){
   106397       sqlite3Error(db, SQLITE_BUSY,
   106398         "unable to delete/modify collation sequence due to active statements");
   106399       return SQLITE_BUSY;
   106400     }
   106401     sqlite3ExpirePreparedStatements(db);
   106402 
   106403     /* If collation sequence pColl was created directly by a call to
   106404     ** sqlite3_create_collation, and not generated by synthCollSeq(),
   106405     ** then any copies made by synthCollSeq() need to be invalidated.
   106406     ** Also, collation destructor - CollSeq.xDel() - function may need
   106407     ** to be called.
   106408     */
   106409     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
   106410       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
   106411       int j;
   106412       for(j=0; j<3; j++){
   106413         CollSeq *p = &aColl[j];
   106414         if( p->enc==pColl->enc ){
   106415           if( p->xDel ){
   106416             p->xDel(p->pUser);
   106417           }
   106418           p->xCmp = 0;
   106419         }
   106420       }
   106421     }
   106422   }
   106423 
   106424   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
   106425   if( pColl==0 ) return SQLITE_NOMEM;
   106426   pColl->xCmp = xCompare;
   106427   pColl->pUser = pCtx;
   106428   pColl->xDel = xDel;
   106429   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
   106430   pColl->type = collType;
   106431   sqlite3Error(db, SQLITE_OK, 0);
   106432   return SQLITE_OK;
   106433 }
   106434 
   106435 
   106436 /*
   106437 ** This array defines hard upper bounds on limit values.  The
   106438 ** initializer must be kept in sync with the SQLITE_LIMIT_*
   106439 ** #defines in sqlite3.h.
   106440 */
   106441 static const int aHardLimit[] = {
   106442   SQLITE_MAX_LENGTH,
   106443   SQLITE_MAX_SQL_LENGTH,
   106444   SQLITE_MAX_COLUMN,
   106445   SQLITE_MAX_EXPR_DEPTH,
   106446   SQLITE_MAX_COMPOUND_SELECT,
   106447   SQLITE_MAX_VDBE_OP,
   106448   SQLITE_MAX_FUNCTION_ARG,
   106449   SQLITE_MAX_ATTACHED,
   106450   SQLITE_MAX_LIKE_PATTERN_LENGTH,
   106451   SQLITE_MAX_VARIABLE_NUMBER,
   106452   SQLITE_MAX_TRIGGER_DEPTH,
   106453 };
   106454 
   106455 /*
   106456 ** Make sure the hard limits are set to reasonable values
   106457 */
   106458 #if SQLITE_MAX_LENGTH<100
   106459 # error SQLITE_MAX_LENGTH must be at least 100
   106460 #endif
   106461 #if SQLITE_MAX_SQL_LENGTH<100
   106462 # error SQLITE_MAX_SQL_LENGTH must be at least 100
   106463 #endif
   106464 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
   106465 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
   106466 #endif
   106467 #if SQLITE_MAX_COMPOUND_SELECT<2
   106468 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
   106469 #endif
   106470 #if SQLITE_MAX_VDBE_OP<40
   106471 # error SQLITE_MAX_VDBE_OP must be at least 40
   106472 #endif
   106473 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
   106474 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
   106475 #endif
   106476 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
   106477 # error SQLITE_MAX_ATTACHED must be between 0 and 30
   106478 #endif
   106479 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
   106480 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
   106481 #endif
   106482 #if SQLITE_MAX_COLUMN>32767
   106483 # error SQLITE_MAX_COLUMN must not exceed 32767
   106484 #endif
   106485 #if SQLITE_MAX_TRIGGER_DEPTH<1
   106486 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
   106487 #endif
   106488 
   106489 
   106490 /*
   106491 ** Change the value of a limit.  Report the old value.
   106492 ** If an invalid limit index is supplied, report -1.
   106493 ** Make no changes but still report the old value if the
   106494 ** new limit is negative.
   106495 **
   106496 ** A new lower limit does not shrink existing constructs.
   106497 ** It merely prevents new constructs that exceed the limit
   106498 ** from forming.
   106499 */
   106500 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
   106501   int oldLimit;
   106502 
   106503 
   106504   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
   106505   ** there is a hard upper bound set at compile-time by a C preprocessor
   106506   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
   106507   ** "_MAX_".)
   106508   */
   106509   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
   106510   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
   106511   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
   106512   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
   106513   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
   106514   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
   106515   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
   106516   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
   106517   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
   106518                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
   106519   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
   106520   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
   106521   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
   106522 
   106523 
   106524   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
   106525     return -1;
   106526   }
   106527   oldLimit = db->aLimit[limitId];
   106528   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
   106529     if( newLimit>aHardLimit[limitId] ){
   106530       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
   106531     }
   106532     db->aLimit[limitId] = newLimit;
   106533   }
   106534   return oldLimit;                     /* IMP: R-53341-35419 */
   106535 }
   106536 
   106537 /*
   106538 ** This routine does the work of opening a database on behalf of
   106539 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
   106540 ** is UTF-8 encoded.
   106541 */
   106542 static int openDatabase(
   106543   const char *zFilename, /* Database filename UTF-8 encoded */
   106544   sqlite3 **ppDb,        /* OUT: Returned database handle */
   106545   unsigned flags,        /* Operational flags */
   106546   const char *zVfs       /* Name of the VFS to use */
   106547 ){
   106548   sqlite3 *db;
   106549   int rc;
   106550   int isThreadsafe;
   106551 
   106552   *ppDb = 0;
   106553 #ifndef SQLITE_OMIT_AUTOINIT
   106554   rc = sqlite3_initialize();
   106555   if( rc ) return rc;
   106556 #endif
   106557 
   106558   /* Only allow sensible combinations of bits in the flags argument.
   106559   ** Throw an error if any non-sense combination is used.  If we
   106560   ** do not block illegal combinations here, it could trigger
   106561   ** assert() statements in deeper layers.  Sensible combinations
   106562   ** are:
   106563   **
   106564   **  1:  SQLITE_OPEN_READONLY
   106565   **  2:  SQLITE_OPEN_READWRITE
   106566   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
   106567   */
   106568   assert( SQLITE_OPEN_READONLY  == 0x01 );
   106569   assert( SQLITE_OPEN_READWRITE == 0x02 );
   106570   assert( SQLITE_OPEN_CREATE    == 0x04 );
   106571   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
   106572   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   106573   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   106574   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
   106575 
   106576   if( sqlite3GlobalConfig.bCoreMutex==0 ){
   106577     isThreadsafe = 0;
   106578   }else if( flags & SQLITE_OPEN_NOMUTEX ){
   106579     isThreadsafe = 0;
   106580   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
   106581     isThreadsafe = 1;
   106582   }else{
   106583     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
   106584   }
   106585   if( flags & SQLITE_OPEN_PRIVATECACHE ){
   106586     flags &= ~SQLITE_OPEN_SHAREDCACHE;
   106587   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
   106588     flags |= SQLITE_OPEN_SHAREDCACHE;
   106589   }
   106590 
   106591   /* Remove harmful bits from the flags parameter
   106592   **
   106593   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
   106594   ** dealt with in the previous code block.  Besides these, the only
   106595   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
   106596   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
   106597   ** off all other flags.
   106598   */
   106599   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
   106600                SQLITE_OPEN_EXCLUSIVE |
   106601                SQLITE_OPEN_MAIN_DB |
   106602                SQLITE_OPEN_TEMP_DB |
   106603                SQLITE_OPEN_TRANSIENT_DB |
   106604                SQLITE_OPEN_MAIN_JOURNAL |
   106605                SQLITE_OPEN_TEMP_JOURNAL |
   106606                SQLITE_OPEN_SUBJOURNAL |
   106607                SQLITE_OPEN_MASTER_JOURNAL |
   106608                SQLITE_OPEN_NOMUTEX |
   106609                SQLITE_OPEN_FULLMUTEX |
   106610                SQLITE_OPEN_WAL
   106611              );
   106612 
   106613   /* Allocate the sqlite data structure */
   106614   db = sqlite3MallocZero( sizeof(sqlite3) );
   106615   if( db==0 ) goto opendb_out;
   106616   if( isThreadsafe ){
   106617     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
   106618     if( db->mutex==0 ){
   106619       sqlite3_free(db);
   106620       db = 0;
   106621       goto opendb_out;
   106622     }
   106623   }
   106624   sqlite3_mutex_enter(db->mutex);
   106625   db->errMask = 0xff;
   106626   db->nDb = 2;
   106627   db->magic = SQLITE_MAGIC_BUSY;
   106628   db->aDb = db->aDbStatic;
   106629 
   106630   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   106631   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
   106632   db->autoCommit = 1;
   106633   db->nextAutovac = -1;
   106634   db->nextPagesize = 0;
   106635   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
   106636 #if SQLITE_DEFAULT_FILE_FORMAT<4
   106637                  | SQLITE_LegacyFileFmt
   106638 #endif
   106639 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
   106640                  | SQLITE_LoadExtension
   106641 #endif
   106642 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
   106643                  | SQLITE_RecTriggers
   106644 #endif
   106645       ;
   106646   sqlite3HashInit(&db->aCollSeq);
   106647 #ifndef SQLITE_OMIT_VIRTUALTABLE
   106648   sqlite3HashInit(&db->aModule);
   106649 #endif
   106650 
   106651   db->pVfs = sqlite3_vfs_find(zVfs);
   106652   if( !db->pVfs ){
   106653     rc = SQLITE_ERROR;
   106654     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
   106655     goto opendb_out;
   106656   }
   106657 
   106658   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
   106659   ** and UTF-16, so add a version for each to avoid any unnecessary
   106660   ** conversions. The only error that can occur here is a malloc() failure.
   106661   */
   106662   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
   106663                   binCollFunc, 0);
   106664   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
   106665                   binCollFunc, 0);
   106666   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
   106667                   binCollFunc, 0);
   106668   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
   106669                   binCollFunc, 0);
   106670   if( db->mallocFailed ){
   106671     goto opendb_out;
   106672   }
   106673   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
   106674   assert( db->pDfltColl!=0 );
   106675 
   106676   /* Also add a UTF-8 case-insensitive collation sequence. */
   106677   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
   106678                   nocaseCollatingFunc, 0);
   106679 
   106680   /* Open the backend database driver */
   106681   db->openFlags = flags;
   106682   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
   106683                         flags | SQLITE_OPEN_MAIN_DB);
   106684   if( rc!=SQLITE_OK ){
   106685     if( rc==SQLITE_IOERR_NOMEM ){
   106686       rc = SQLITE_NOMEM;
   106687     }
   106688     sqlite3Error(db, rc, 0);
   106689     goto opendb_out;
   106690   }
   106691   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
   106692   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
   106693 
   106694 
   106695   /* The default safety_level for the main database is 'full'; for the temp
   106696   ** database it is 'NONE'. This matches the pager layer defaults.
   106697   */
   106698   db->aDb[0].zName = "main";
   106699   db->aDb[0].safety_level = 3;
   106700   db->aDb[1].zName = "temp";
   106701   db->aDb[1].safety_level = 1;
   106702 
   106703   db->magic = SQLITE_MAGIC_OPEN;
   106704   if( db->mallocFailed ){
   106705     goto opendb_out;
   106706   }
   106707 
   106708   /* Register all built-in functions, but do not attempt to read the
   106709   ** database schema yet. This is delayed until the first time the database
   106710   ** is accessed.
   106711   */
   106712   sqlite3Error(db, SQLITE_OK, 0);
   106713   sqlite3RegisterBuiltinFunctions(db);
   106714 
   106715   /* Load automatic extensions - extensions that have been registered
   106716   ** using the sqlite3_automatic_extension() API.
   106717   */
   106718   sqlite3AutoLoadExtensions(db);
   106719   rc = sqlite3_errcode(db);
   106720   if( rc!=SQLITE_OK ){
   106721     goto opendb_out;
   106722   }
   106723 
   106724 #ifdef SQLITE_ENABLE_FTS1
   106725   if( !db->mallocFailed ){
   106726     extern int sqlite3Fts1Init(sqlite3*);
   106727     rc = sqlite3Fts1Init(db);
   106728   }
   106729 #endif
   106730 
   106731 #ifdef SQLITE_ENABLE_FTS2
   106732   if( !db->mallocFailed && rc==SQLITE_OK ){
   106733     extern int sqlite3Fts2Init(sqlite3*);
   106734     rc = sqlite3Fts2Init(db);
   106735   }
   106736 #endif
   106737 
   106738 #ifdef SQLITE_ENABLE_FTS3
   106739   // Begin Android change
   106740   #ifdef SQLITE_ENABLE_FTS3_BACKWARDS
   106741     /* Also register as fts1 and fts2, for backwards compatability on
   106742     ** systems known to have never seen a pre-fts3 database.
   106743     */
   106744     if( !db->mallocFailed && rc==SQLITE_OK ){
   106745       rc = sqlite3Fts3Init(db, "fts1");
   106746     }
   106747 
   106748     if( !db->mallocFailed && rc==SQLITE_OK ){
   106749       rc = sqlite3Fts3Init(db, "fts2");
   106750     }
   106751   #endif
   106752 
   106753     if( !db->mallocFailed && rc==SQLITE_OK ){
   106754       rc = sqlite3Fts3Init(db, "fts3");
   106755     }
   106756   // End Android change
   106757 #endif
   106758 
   106759 #ifdef SQLITE_ENABLE_ICU
   106760   if( !db->mallocFailed && rc==SQLITE_OK ){
   106761     rc = sqlite3IcuInit(db);
   106762   }
   106763 #endif
   106764 
   106765 #ifdef SQLITE_ENABLE_RTREE
   106766   if( !db->mallocFailed && rc==SQLITE_OK){
   106767     rc = sqlite3RtreeInit(db);
   106768   }
   106769 #endif
   106770 
   106771   sqlite3Error(db, rc, 0);
   106772 
   106773   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
   106774   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
   106775   ** mode.  Doing nothing at all also makes NORMAL the default.
   106776   */
   106777 #ifdef SQLITE_DEFAULT_LOCKING_MODE
   106778   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
   106779   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
   106780                           SQLITE_DEFAULT_LOCKING_MODE);
   106781 #endif
   106782 
   106783   /* Enable the lookaside-malloc subsystem */
   106784   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
   106785                         sqlite3GlobalConfig.nLookaside);
   106786 
   106787   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
   106788 
   106789 opendb_out:
   106790   if( db ){
   106791     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
   106792     sqlite3_mutex_leave(db->mutex);
   106793   }
   106794   rc = sqlite3_errcode(db);
   106795   if( rc==SQLITE_NOMEM ){
   106796     sqlite3_close(db);
   106797     db = 0;
   106798   }else if( rc!=SQLITE_OK ){
   106799     db->magic = SQLITE_MAGIC_SICK;
   106800   }
   106801   *ppDb = db;
   106802   return sqlite3ApiExit(0, rc);
   106803 }
   106804 
   106805 /*
   106806 ** Open a new database handle.
   106807 */
   106808 SQLITE_API int sqlite3_open(
   106809   const char *zFilename,
   106810   sqlite3 **ppDb
   106811 ){
   106812   return openDatabase(zFilename, ppDb,
   106813                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   106814 }
   106815 SQLITE_API int sqlite3_open_v2(
   106816   const char *filename,   /* Database filename (UTF-8) */
   106817   sqlite3 **ppDb,         /* OUT: SQLite db handle */
   106818   int flags,              /* Flags */
   106819   const char *zVfs        /* Name of VFS module to use */
   106820 ){
   106821   return openDatabase(filename, ppDb, flags, zVfs);
   106822 }
   106823 
   106824 #ifndef SQLITE_OMIT_UTF16
   106825 /*
   106826 ** Open a new database handle.
   106827 */
   106828 SQLITE_API int sqlite3_open16(
   106829   const void *zFilename,
   106830   sqlite3 **ppDb
   106831 ){
   106832   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
   106833   sqlite3_value *pVal;
   106834   int rc;
   106835 
   106836   assert( zFilename );
   106837   assert( ppDb );
   106838   *ppDb = 0;
   106839 #ifndef SQLITE_OMIT_AUTOINIT
   106840   rc = sqlite3_initialize();
   106841   if( rc ) return rc;
   106842 #endif
   106843   pVal = sqlite3ValueNew(0);
   106844   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
   106845   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
   106846   if( zFilename8 ){
   106847     rc = openDatabase(zFilename8, ppDb,
   106848                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
   106849     assert( *ppDb || rc==SQLITE_NOMEM );
   106850     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
   106851       ENC(*ppDb) = SQLITE_UTF16NATIVE;
   106852     }
   106853   }else{
   106854     rc = SQLITE_NOMEM;
   106855   }
   106856   sqlite3ValueFree(pVal);
   106857 
   106858   return sqlite3ApiExit(0, rc);
   106859 }
   106860 #endif /* SQLITE_OMIT_UTF16 */
   106861 
   106862 /*
   106863 ** Register a new collation sequence with the database handle db.
   106864 */
   106865 SQLITE_API int sqlite3_create_collation(
   106866   sqlite3* db,
   106867   const char *zName,
   106868   int enc,
   106869   void* pCtx,
   106870   int(*xCompare)(void*,int,const void*,int,const void*)
   106871 ){
   106872   int rc;
   106873   sqlite3_mutex_enter(db->mutex);
   106874   assert( !db->mallocFailed );
   106875   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   106876   rc = sqlite3ApiExit(db, rc);
   106877   sqlite3_mutex_leave(db->mutex);
   106878   return rc;
   106879 }
   106880 
   106881 /*
   106882 ** Register a new collation sequence with the database handle db.
   106883 */
   106884 SQLITE_API int sqlite3_create_collation_v2(
   106885   sqlite3* db,
   106886   const char *zName,
   106887   int enc,
   106888   void* pCtx,
   106889   int(*xCompare)(void*,int,const void*,int,const void*),
   106890   void(*xDel)(void*)
   106891 ){
   106892   int rc;
   106893   sqlite3_mutex_enter(db->mutex);
   106894   assert( !db->mallocFailed );
   106895   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
   106896   rc = sqlite3ApiExit(db, rc);
   106897   sqlite3_mutex_leave(db->mutex);
   106898   return rc;
   106899 }
   106900 
   106901 #ifndef SQLITE_OMIT_UTF16
   106902 /*
   106903 ** Register a new collation sequence with the database handle db.
   106904 */
   106905 SQLITE_API int sqlite3_create_collation16(
   106906   sqlite3* db,
   106907   const void *zName,
   106908   int enc,
   106909   void* pCtx,
   106910   int(*xCompare)(void*,int,const void*,int,const void*)
   106911 ){
   106912   int rc = SQLITE_OK;
   106913   char *zName8;
   106914   sqlite3_mutex_enter(db->mutex);
   106915   assert( !db->mallocFailed );
   106916   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
   106917   if( zName8 ){
   106918     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
   106919     sqlite3DbFree(db, zName8);
   106920   }
   106921   rc = sqlite3ApiExit(db, rc);
   106922   sqlite3_mutex_leave(db->mutex);
   106923   return rc;
   106924 }
   106925 #endif /* SQLITE_OMIT_UTF16 */
   106926 
   106927 /*
   106928 ** Register a collation sequence factory callback with the database handle
   106929 ** db. Replace any previously installed collation sequence factory.
   106930 */
   106931 SQLITE_API int sqlite3_collation_needed(
   106932   sqlite3 *db,
   106933   void *pCollNeededArg,
   106934   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
   106935 ){
   106936   sqlite3_mutex_enter(db->mutex);
   106937   db->xCollNeeded = xCollNeeded;
   106938   db->xCollNeeded16 = 0;
   106939   db->pCollNeededArg = pCollNeededArg;
   106940   sqlite3_mutex_leave(db->mutex);
   106941   return SQLITE_OK;
   106942 }
   106943 
   106944 #ifndef SQLITE_OMIT_UTF16
   106945 /*
   106946 ** Register a collation sequence factory callback with the database handle
   106947 ** db. Replace any previously installed collation sequence factory.
   106948 */
   106949 SQLITE_API int sqlite3_collation_needed16(
   106950   sqlite3 *db,
   106951   void *pCollNeededArg,
   106952   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
   106953 ){
   106954   sqlite3_mutex_enter(db->mutex);
   106955   db->xCollNeeded = 0;
   106956   db->xCollNeeded16 = xCollNeeded16;
   106957   db->pCollNeededArg = pCollNeededArg;
   106958   sqlite3_mutex_leave(db->mutex);
   106959   return SQLITE_OK;
   106960 }
   106961 #endif /* SQLITE_OMIT_UTF16 */
   106962 
   106963 #ifndef SQLITE_OMIT_DEPRECATED
   106964 /*
   106965 ** This function is now an anachronism. It used to be used to recover from a
   106966 ** malloc() failure, but SQLite now does this automatically.
   106967 */
   106968 SQLITE_API int sqlite3_global_recover(void){
   106969   return SQLITE_OK;
   106970 }
   106971 #endif
   106972 
   106973 /*
   106974 ** Test to see whether or not the database connection is in autocommit
   106975 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
   106976 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
   106977 ** by the next COMMIT or ROLLBACK.
   106978 **
   106979 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
   106980 */
   106981 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
   106982   return db->autoCommit;
   106983 }
   106984 
   106985 /*
   106986 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
   106987 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
   106988 ** constants.  They server two purposes:
   106989 **
   106990 **   1.  Serve as a convenient place to set a breakpoint in a debugger
   106991 **       to detect when version error conditions occurs.
   106992 **
   106993 **   2.  Invoke sqlite3_log() to provide the source code location where
   106994 **       a low-level error is first detected.
   106995 */
   106996 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
   106997   testcase( sqlite3GlobalConfig.xLog!=0 );
   106998   sqlite3_log(SQLITE_CORRUPT,
   106999               "database corruption at line %d of [%.10s]",
   107000               lineno, 20+sqlite3_sourceid());
   107001   return SQLITE_CORRUPT;
   107002 }
   107003 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
   107004   testcase( sqlite3GlobalConfig.xLog!=0 );
   107005   sqlite3_log(SQLITE_MISUSE,
   107006               "misuse at line %d of [%.10s]",
   107007               lineno, 20+sqlite3_sourceid());
   107008   return SQLITE_MISUSE;
   107009 }
   107010 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   107011   testcase( sqlite3GlobalConfig.xLog!=0 );
   107012   sqlite3_log(SQLITE_CANTOPEN,
   107013               "cannot open file at line %d of [%.10s]",
   107014               lineno, 20+sqlite3_sourceid());
   107015   return SQLITE_CANTOPEN;
   107016 }
   107017 
   107018 
   107019 #ifndef SQLITE_OMIT_DEPRECATED
   107020 /*
   107021 ** This is a convenience routine that makes sure that all thread-specific
   107022 ** data for this thread has been deallocated.
   107023 **
   107024 ** SQLite no longer uses thread-specific data so this routine is now a
   107025 ** no-op.  It is retained for historical compatibility.
   107026 */
   107027 SQLITE_API void sqlite3_thread_cleanup(void){
   107028 }
   107029 #endif
   107030 
   107031 /*
   107032 ** Return meta information about a specific column of a database table.
   107033 ** See comment in sqlite3.h (sqlite.h.in) for details.
   107034 */
   107035 #ifdef SQLITE_ENABLE_COLUMN_METADATA
   107036 SQLITE_API int sqlite3_table_column_metadata(
   107037   sqlite3 *db,                /* Connection handle */
   107038   const char *zDbName,        /* Database name or NULL */
   107039   const char *zTableName,     /* Table name */
   107040   const char *zColumnName,    /* Column name */
   107041   char const **pzDataType,    /* OUTPUT: Declared data type */
   107042   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
   107043   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
   107044   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
   107045   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
   107046 ){
   107047   int rc;
   107048   char *zErrMsg = 0;
   107049   Table *pTab = 0;
   107050   Column *pCol = 0;
   107051   int iCol;
   107052 
   107053   char const *zDataType = 0;
   107054   char const *zCollSeq = 0;
   107055   int notnull = 0;
   107056   int primarykey = 0;
   107057   int autoinc = 0;
   107058 
   107059   /* Ensure the database schema has been loaded */
   107060   sqlite3_mutex_enter(db->mutex);
   107061   sqlite3BtreeEnterAll(db);
   107062   rc = sqlite3Init(db, &zErrMsg);
   107063   if( SQLITE_OK!=rc ){
   107064     goto error_out;
   107065   }
   107066 
   107067   /* Locate the table in question */
   107068   pTab = sqlite3FindTable(db, zTableName, zDbName);
   107069   if( !pTab || pTab->pSelect ){
   107070     pTab = 0;
   107071     goto error_out;
   107072   }
   107073 
   107074   /* Find the column for which info is requested */
   107075   if( sqlite3IsRowid(zColumnName) ){
   107076     iCol = pTab->iPKey;
   107077     if( iCol>=0 ){
   107078       pCol = &pTab->aCol[iCol];
   107079     }
   107080   }else{
   107081     for(iCol=0; iCol<pTab->nCol; iCol++){
   107082       pCol = &pTab->aCol[iCol];
   107083       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
   107084         break;
   107085       }
   107086     }
   107087     if( iCol==pTab->nCol ){
   107088       pTab = 0;
   107089       goto error_out;
   107090     }
   107091   }
   107092 
   107093   /* The following block stores the meta information that will be returned
   107094   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   107095   ** and autoinc. At this point there are two possibilities:
   107096   **
   107097   **     1. The specified column name was rowid", "oid" or "_rowid_"
   107098   **        and there is no explicitly declared IPK column.
   107099   **
   107100   **     2. The table is not a view and the column name identified an
   107101   **        explicitly declared column. Copy meta information from *pCol.
   107102   */
   107103   if( pCol ){
   107104     zDataType = pCol->zType;
   107105     zCollSeq = pCol->zColl;
   107106     notnull = pCol->notNull!=0;
   107107     primarykey  = pCol->isPrimKey!=0;
   107108     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
   107109   }else{
   107110     zDataType = "INTEGER";
   107111     primarykey = 1;
   107112   }
   107113   if( !zCollSeq ){
   107114     zCollSeq = "BINARY";
   107115   }
   107116 
   107117 error_out:
   107118   sqlite3BtreeLeaveAll(db);
   107119 
   107120   /* Whether the function call succeeded or failed, set the output parameters
   107121   ** to whatever their local counterparts contain. If an error did occur,
   107122   ** this has the effect of zeroing all output parameters.
   107123   */
   107124   if( pzDataType ) *pzDataType = zDataType;
   107125   if( pzCollSeq ) *pzCollSeq = zCollSeq;
   107126   if( pNotNull ) *pNotNull = notnull;
   107127   if( pPrimaryKey ) *pPrimaryKey = primarykey;
   107128   if( pAutoinc ) *pAutoinc = autoinc;
   107129 
   107130   if( SQLITE_OK==rc && !pTab ){
   107131     sqlite3DbFree(db, zErrMsg);
   107132     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
   107133         zColumnName);
   107134     rc = SQLITE_ERROR;
   107135   }
   107136   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
   107137   sqlite3DbFree(db, zErrMsg);
   107138   rc = sqlite3ApiExit(db, rc);
   107139   sqlite3_mutex_leave(db->mutex);
   107140   return rc;
   107141 }
   107142 #endif
   107143 
   107144 /*
   107145 ** Sleep for a little while.  Return the amount of time slept.
   107146 */
   107147 SQLITE_API int sqlite3_sleep(int ms){
   107148   sqlite3_vfs *pVfs;
   107149   int rc;
   107150   pVfs = sqlite3_vfs_find(0);
   107151   if( pVfs==0 ) return 0;
   107152 
   107153   /* This function works in milliseconds, but the underlying OsSleep()
   107154   ** API uses microseconds. Hence the 1000's.
   107155   */
   107156   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
   107157   return rc;
   107158 }
   107159 
   107160 /*
   107161 ** Enable or disable the extended result codes.
   107162 */
   107163 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
   107164   sqlite3_mutex_enter(db->mutex);
   107165   db->errMask = onoff ? 0xffffffff : 0xff;
   107166   sqlite3_mutex_leave(db->mutex);
   107167   return SQLITE_OK;
   107168 }
   107169 
   107170 /*
   107171 ** Invoke the xFileControl method on a particular database.
   107172 */
   107173 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
   107174   int rc = SQLITE_ERROR;
   107175   int iDb;
   107176   sqlite3_mutex_enter(db->mutex);
   107177   if( zDbName==0 ){
   107178     iDb = 0;
   107179   }else{
   107180     for(iDb=0; iDb<db->nDb; iDb++){
   107181       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
   107182     }
   107183   }
   107184   if( iDb<db->nDb ){
   107185     Btree *pBtree = db->aDb[iDb].pBt;
   107186     if( pBtree ){
   107187       Pager *pPager;
   107188       sqlite3_file *fd;
   107189       sqlite3BtreeEnter(pBtree);
   107190       pPager = sqlite3BtreePager(pBtree);
   107191       assert( pPager!=0 );
   107192       fd = sqlite3PagerFile(pPager);
   107193       assert( fd!=0 );
   107194       if( op==SQLITE_FCNTL_FILE_POINTER ){
   107195         *(sqlite3_file**)pArg = fd;
   107196         rc = SQLITE_OK;
   107197       }else if( fd->pMethods ){
   107198         rc = sqlite3OsFileControl(fd, op, pArg);
   107199       }
   107200       sqlite3BtreeLeave(pBtree);
   107201     }
   107202   }
   107203   sqlite3_mutex_leave(db->mutex);
   107204   return rc;
   107205 }
   107206 
   107207 /*
   107208 ** Interface to the testing logic.
   107209 */
   107210 SQLITE_API int sqlite3_test_control(int op, ...){
   107211   int rc = 0;
   107212 #ifndef SQLITE_OMIT_BUILTIN_TEST
   107213   va_list ap;
   107214   va_start(ap, op);
   107215   switch( op ){
   107216 
   107217     /*
   107218     ** Save the current state of the PRNG.
   107219     */
   107220     case SQLITE_TESTCTRL_PRNG_SAVE: {
   107221       sqlite3PrngSaveState();
   107222       break;
   107223     }
   107224 
   107225     /*
   107226     ** Restore the state of the PRNG to the last state saved using
   107227     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
   107228     ** this verb acts like PRNG_RESET.
   107229     */
   107230     case SQLITE_TESTCTRL_PRNG_RESTORE: {
   107231       sqlite3PrngRestoreState();
   107232       break;
   107233     }
   107234 
   107235     /*
   107236     ** Reset the PRNG back to its uninitialized state.  The next call
   107237     ** to sqlite3_randomness() will reseed the PRNG using a single call
   107238     ** to the xRandomness method of the default VFS.
   107239     */
   107240     case SQLITE_TESTCTRL_PRNG_RESET: {
   107241       sqlite3PrngResetState();
   107242       break;
   107243     }
   107244 
   107245     /*
   107246     **  sqlite3_test_control(BITVEC_TEST, size, program)
   107247     **
   107248     ** Run a test against a Bitvec object of size.  The program argument
   107249     ** is an array of integers that defines the test.  Return -1 on a
   107250     ** memory allocation error, 0 on success, or non-zero for an error.
   107251     ** See the sqlite3BitvecBuiltinTest() for additional information.
   107252     */
   107253     case SQLITE_TESTCTRL_BITVEC_TEST: {
   107254       int sz = va_arg(ap, int);
   107255       int *aProg = va_arg(ap, int*);
   107256       rc = sqlite3BitvecBuiltinTest(sz, aProg);
   107257       break;
   107258     }
   107259 
   107260     /*
   107261     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
   107262     **
   107263     ** Register hooks to call to indicate which malloc() failures
   107264     ** are benign.
   107265     */
   107266     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
   107267       typedef void (*void_function)(void);
   107268       void_function xBenignBegin;
   107269       void_function xBenignEnd;
   107270       xBenignBegin = va_arg(ap, void_function);
   107271       xBenignEnd = va_arg(ap, void_function);
   107272       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
   107273       break;
   107274     }
   107275 
   107276     /*
   107277     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
   107278     **
   107279     ** Set the PENDING byte to the value in the argument, if X>0.
   107280     ** Make no changes if X==0.  Return the value of the pending byte
   107281     ** as it existing before this routine was called.
   107282     **
   107283     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
   107284     ** an incompatible database file format.  Changing the PENDING byte
   107285     ** while any database connection is open results in undefined and
   107286     ** dileterious behavior.
   107287     */
   107288     case SQLITE_TESTCTRL_PENDING_BYTE: {
   107289       rc = PENDING_BYTE;
   107290 #ifndef SQLITE_OMIT_WSD
   107291       {
   107292         unsigned int newVal = va_arg(ap, unsigned int);
   107293         if( newVal ) sqlite3PendingByte = newVal;
   107294       }
   107295 #endif
   107296       break;
   107297     }
   107298 
   107299     /*
   107300     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
   107301     **
   107302     ** This action provides a run-time test to see whether or not
   107303     ** assert() was enabled at compile-time.  If X is true and assert()
   107304     ** is enabled, then the return value is true.  If X is true and
   107305     ** assert() is disabled, then the return value is zero.  If X is
   107306     ** false and assert() is enabled, then the assertion fires and the
   107307     ** process aborts.  If X is false and assert() is disabled, then the
   107308     ** return value is zero.
   107309     */
   107310     case SQLITE_TESTCTRL_ASSERT: {
   107311       volatile int x = 0;
   107312       assert( (x = va_arg(ap,int))!=0 );
   107313       rc = x;
   107314       break;
   107315     }
   107316 
   107317 
   107318     /*
   107319     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
   107320     **
   107321     ** This action provides a run-time test to see how the ALWAYS and
   107322     ** NEVER macros were defined at compile-time.
   107323     **
   107324     ** The return value is ALWAYS(X).
   107325     **
   107326     ** The recommended test is X==2.  If the return value is 2, that means
   107327     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
   107328     ** default setting.  If the return value is 1, then ALWAYS() is either
   107329     ** hard-coded to true or else it asserts if its argument is false.
   107330     ** The first behavior (hard-coded to true) is the case if
   107331     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
   107332     ** behavior (assert if the argument to ALWAYS() is false) is the case if
   107333     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
   107334     **
   107335     ** The run-time test procedure might look something like this:
   107336     **
   107337     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
   107338     **      // ALWAYS() and NEVER() are no-op pass-through macros
   107339     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
   107340     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
   107341     **    }else{
   107342     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
   107343     **    }
   107344     */
   107345     case SQLITE_TESTCTRL_ALWAYS: {
   107346       int x = va_arg(ap,int);
   107347       rc = ALWAYS(x);
   107348       break;
   107349     }
   107350 
   107351     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
   107352     **
   107353     ** Set the nReserve size to N for the main database on the database
   107354     ** connection db.
   107355     */
   107356     case SQLITE_TESTCTRL_RESERVE: {
   107357       sqlite3 *db = va_arg(ap, sqlite3*);
   107358       int x = va_arg(ap,int);
   107359       sqlite3_mutex_enter(db->mutex);
   107360       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
   107361       sqlite3_mutex_leave(db->mutex);
   107362       break;
   107363     }
   107364 
   107365     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
   107366     **
   107367     ** Enable or disable various optimizations for testing purposes.  The
   107368     ** argument N is a bitmask of optimizations to be disabled.  For normal
   107369     ** operation N should be 0.  The idea is that a test program (like the
   107370     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
   107371     ** with various optimizations disabled to verify that the same answer
   107372     ** is obtained in every case.
   107373     */
   107374     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
   107375       sqlite3 *db = va_arg(ap, sqlite3*);
   107376       int x = va_arg(ap,int);
   107377       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
   107378       break;
   107379     }
   107380 
   107381 #ifdef SQLITE_N_KEYWORD
   107382     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
   107383     **
   107384     ** If zWord is a keyword recognized by the parser, then return the
   107385     ** number of keywords.  Or if zWord is not a keyword, return 0.
   107386     **
   107387     ** This test feature is only available in the amalgamation since
   107388     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
   107389     ** is built using separate source files.
   107390     */
   107391     case SQLITE_TESTCTRL_ISKEYWORD: {
   107392       const char *zWord = va_arg(ap, const char*);
   107393       int n = sqlite3Strlen30(zWord);
   107394       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
   107395       break;
   107396     }
   107397 #endif
   107398 
   107399     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
   107400     **
   107401     ** Return the size of a pcache header in bytes.
   107402     */
   107403     case SQLITE_TESTCTRL_PGHDRSZ: {
   107404       rc = sizeof(PgHdr);
   107405       break;
   107406     }
   107407 
   107408     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
   107409     **
   107410     ** Pass pFree into sqlite3ScratchFree().
   107411     ** If sz>0 then allocate a scratch buffer into pNew.
   107412     */
   107413     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
   107414       void *pFree, **ppNew;
   107415       int sz;
   107416       sz = va_arg(ap, int);
   107417       ppNew = va_arg(ap, void**);
   107418       pFree = va_arg(ap, void*);
   107419       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
   107420       sqlite3ScratchFree(pFree);
   107421       break;
   107422     }
   107423 
   107424   }
   107425   va_end(ap);
   107426 #endif /* SQLITE_OMIT_BUILTIN_TEST */
   107427   return rc;
   107428 }
   107429 
   107430 /************** End of main.c ************************************************/
   107431 /************** Begin file notify.c ******************************************/
   107432 /*
   107433 ** 2009 March 3
   107434 **
   107435 ** The author disclaims copyright to this source code.  In place of
   107436 ** a legal notice, here is a blessing:
   107437 **
   107438 **    May you do good and not evil.
   107439 **    May you find forgiveness for yourself and forgive others.
   107440 **    May you share freely, never taking more than you give.
   107441 **
   107442 *************************************************************************
   107443 **
   107444 ** This file contains the implementation of the sqlite3_unlock_notify()
   107445 ** API method and its associated functionality.
   107446 */
   107447 
   107448 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
   107449 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   107450 
   107451 /*
   107452 ** Public interfaces:
   107453 **
   107454 **   sqlite3ConnectionBlocked()
   107455 **   sqlite3ConnectionUnlocked()
   107456 **   sqlite3ConnectionClosed()
   107457 **   sqlite3_unlock_notify()
   107458 */
   107459 
   107460 #define assertMutexHeld() \
   107461   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
   107462 
   107463 /*
   107464 ** Head of a linked list of all sqlite3 objects created by this process
   107465 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
   107466 ** is not NULL. This variable may only accessed while the STATIC_MASTER
   107467 ** mutex is held.
   107468 */
   107469 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
   107470 
   107471 #ifndef NDEBUG
   107472 /*
   107473 ** This function is a complex assert() that verifies the following
   107474 ** properties of the blocked connections list:
   107475 **
   107476 **   1) Each entry in the list has a non-NULL value for either
   107477 **      pUnlockConnection or pBlockingConnection, or both.
   107478 **
   107479 **   2) All entries in the list that share a common value for
   107480 **      xUnlockNotify are grouped together.
   107481 **
   107482 **   3) If the argument db is not NULL, then none of the entries in the
   107483 **      blocked connections list have pUnlockConnection or pBlockingConnection
   107484 **      set to db. This is used when closing connection db.
   107485 */
   107486 static void checkListProperties(sqlite3 *db){
   107487   sqlite3 *p;
   107488   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
   107489     int seen = 0;
   107490     sqlite3 *p2;
   107491 
   107492     /* Verify property (1) */
   107493     assert( p->pUnlockConnection || p->pBlockingConnection );
   107494 
   107495     /* Verify property (2) */
   107496     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
   107497       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
   107498       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
   107499       assert( db==0 || p->pUnlockConnection!=db );
   107500       assert( db==0 || p->pBlockingConnection!=db );
   107501     }
   107502   }
   107503 }
   107504 #else
   107505 # define checkListProperties(x)
   107506 #endif
   107507 
   107508 /*
   107509 ** Remove connection db from the blocked connections list. If connection
   107510 ** db is not currently a part of the list, this function is a no-op.
   107511 */
   107512 static void removeFromBlockedList(sqlite3 *db){
   107513   sqlite3 **pp;
   107514   assertMutexHeld();
   107515   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
   107516     if( *pp==db ){
   107517       *pp = (*pp)->pNextBlocked;
   107518       break;
   107519     }
   107520   }
   107521 }
   107522 
   107523 /*
   107524 ** Add connection db to the blocked connections list. It is assumed
   107525 ** that it is not already a part of the list.
   107526 */
   107527 static void addToBlockedList(sqlite3 *db){
   107528   sqlite3 **pp;
   107529   assertMutexHeld();
   107530   for(
   107531     pp=&sqlite3BlockedList;
   107532     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
   107533     pp=&(*pp)->pNextBlocked
   107534   );
   107535   db->pNextBlocked = *pp;
   107536   *pp = db;
   107537 }
   107538 
   107539 /*
   107540 ** Obtain the STATIC_MASTER mutex.
   107541 */
   107542 static void enterMutex(void){
   107543   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   107544   checkListProperties(0);
   107545 }
   107546 
   107547 /*
   107548 ** Release the STATIC_MASTER mutex.
   107549 */
   107550 static void leaveMutex(void){
   107551   assertMutexHeld();
   107552   checkListProperties(0);
   107553   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
   107554 }
   107555 
   107556 /*
   107557 ** Register an unlock-notify callback.
   107558 **
   107559 ** This is called after connection "db" has attempted some operation
   107560 ** but has received an SQLITE_LOCKED error because another connection
   107561 ** (call it pOther) in the same process was busy using the same shared
   107562 ** cache.  pOther is found by looking at db->pBlockingConnection.
   107563 **
   107564 ** If there is no blocking connection, the callback is invoked immediately,
   107565 ** before this routine returns.
   107566 **
   107567 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
   107568 ** a deadlock.
   107569 **
   107570 ** Otherwise, make arrangements to invoke xNotify when pOther drops
   107571 ** its locks.
   107572 **
   107573 ** Each call to this routine overrides any prior callbacks registered
   107574 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
   107575 ** cancelled.
   107576 */
   107577 SQLITE_API int sqlite3_unlock_notify(
   107578   sqlite3 *db,
   107579   void (*xNotify)(void **, int),
   107580   void *pArg
   107581 ){
   107582   int rc = SQLITE_OK;
   107583 
   107584   sqlite3_mutex_enter(db->mutex);
   107585   enterMutex();
   107586 
   107587   if( xNotify==0 ){
   107588     removeFromBlockedList(db);
   107589     db->pBlockingConnection = 0;
   107590     db->pUnlockConnection = 0;
   107591     db->xUnlockNotify = 0;
   107592     db->pUnlockArg = 0;
   107593   }else if( 0==db->pBlockingConnection ){
   107594     /* The blocking transaction has been concluded. Or there never was a
   107595     ** blocking transaction. In either case, invoke the notify callback
   107596     ** immediately.
   107597     */
   107598     xNotify(&pArg, 1);
   107599   }else{
   107600     sqlite3 *p;
   107601 
   107602     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
   107603     if( p ){
   107604       rc = SQLITE_LOCKED;              /* Deadlock detected. */
   107605     }else{
   107606       db->pUnlockConnection = db->pBlockingConnection;
   107607       db->xUnlockNotify = xNotify;
   107608       db->pUnlockArg = pArg;
   107609       removeFromBlockedList(db);
   107610       addToBlockedList(db);
   107611     }
   107612   }
   107613 
   107614   leaveMutex();
   107615   assert( !db->mallocFailed );
   107616   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
   107617   sqlite3_mutex_leave(db->mutex);
   107618   return rc;
   107619 }
   107620 
   107621 /*
   107622 ** This function is called while stepping or preparing a statement
   107623 ** associated with connection db. The operation will return SQLITE_LOCKED
   107624 ** to the user because it requires a lock that will not be available
   107625 ** until connection pBlocker concludes its current transaction.
   107626 */
   107627 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
   107628   enterMutex();
   107629   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
   107630     addToBlockedList(db);
   107631   }
   107632   db->pBlockingConnection = pBlocker;
   107633   leaveMutex();
   107634 }
   107635 
   107636 /*
   107637 ** This function is called when
   107638 ** the transaction opened by database db has just finished. Locks held
   107639 ** by database connection db have been released.
   107640 **
   107641 ** This function loops through each entry in the blocked connections
   107642 ** list and does the following:
   107643 **
   107644 **   1) If the sqlite3.pBlockingConnection member of a list entry is
   107645 **      set to db, then set pBlockingConnection=0.
   107646 **
   107647 **   2) If the sqlite3.pUnlockConnection member of a list entry is
   107648 **      set to db, then invoke the configured unlock-notify callback and
   107649 **      set pUnlockConnection=0.
   107650 **
   107651 **   3) If the two steps above mean that pBlockingConnection==0 and
   107652 **      pUnlockConnection==0, remove the entry from the blocked connections
   107653 **      list.
   107654 */
   107655 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   107656   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
   107657   int nArg = 0;                            /* Number of entries in aArg[] */
   107658   sqlite3 **pp;                            /* Iterator variable */
   107659   void **aArg;               /* Arguments to the unlock callback */
   107660   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
   107661   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
   107662 
   107663   aArg = aStatic;
   107664   enterMutex();         /* Enter STATIC_MASTER mutex */
   107665 
   107666   /* This loop runs once for each entry in the blocked-connections list. */
   107667   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
   107668     sqlite3 *p = *pp;
   107669 
   107670     /* Step 1. */
   107671     if( p->pBlockingConnection==db ){
   107672       p->pBlockingConnection = 0;
   107673     }
   107674 
   107675     /* Step 2. */
   107676     if( p->pUnlockConnection==db ){
   107677       assert( p->xUnlockNotify );
   107678       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
   107679         xUnlockNotify(aArg, nArg);
   107680         nArg = 0;
   107681       }
   107682 
   107683       sqlite3BeginBenignMalloc();
   107684       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
   107685       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
   107686       if( (!aDyn && nArg==(int)ArraySize(aStatic))
   107687        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
   107688       ){
   107689         /* The aArg[] array needs to grow. */
   107690         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
   107691         if( pNew ){
   107692           memcpy(pNew, aArg, nArg*sizeof(void *));
   107693           sqlite3_free(aDyn);
   107694           aDyn = aArg = pNew;
   107695         }else{
   107696           /* This occurs when the array of context pointers that need to
   107697           ** be passed to the unlock-notify callback is larger than the
   107698           ** aStatic[] array allocated on the stack and the attempt to
   107699           ** allocate a larger array from the heap has failed.
   107700           **
   107701           ** This is a difficult situation to handle. Returning an error
   107702           ** code to the caller is insufficient, as even if an error code
   107703           ** is returned the transaction on connection db will still be
   107704           ** closed and the unlock-notify callbacks on blocked connections
   107705           ** will go unissued. This might cause the application to wait
   107706           ** indefinitely for an unlock-notify callback that will never
   107707           ** arrive.
   107708           **
   107709           ** Instead, invoke the unlock-notify callback with the context
   107710           ** array already accumulated. We can then clear the array and
   107711           ** begin accumulating any further context pointers without
   107712           ** requiring any dynamic allocation. This is sub-optimal because
   107713           ** it means that instead of one callback with a large array of
   107714           ** context pointers the application will receive two or more
   107715           ** callbacks with smaller arrays of context pointers, which will
   107716           ** reduce the applications ability to prioritize multiple
   107717           ** connections. But it is the best that can be done under the
   107718           ** circumstances.
   107719           */
   107720           xUnlockNotify(aArg, nArg);
   107721           nArg = 0;
   107722         }
   107723       }
   107724       sqlite3EndBenignMalloc();
   107725 
   107726       aArg[nArg++] = p->pUnlockArg;
   107727       xUnlockNotify = p->xUnlockNotify;
   107728       p->pUnlockConnection = 0;
   107729       p->xUnlockNotify = 0;
   107730       p->pUnlockArg = 0;
   107731     }
   107732 
   107733     /* Step 3. */
   107734     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
   107735       /* Remove connection p from the blocked connections list. */
   107736       *pp = p->pNextBlocked;
   107737       p->pNextBlocked = 0;
   107738     }else{
   107739       pp = &p->pNextBlocked;
   107740     }
   107741   }
   107742 
   107743   if( nArg!=0 ){
   107744     xUnlockNotify(aArg, nArg);
   107745   }
   107746   sqlite3_free(aDyn);
   107747   leaveMutex();         /* Leave STATIC_MASTER mutex */
   107748 }
   107749 
   107750 /*
   107751 ** This is called when the database connection passed as an argument is
   107752 ** being closed. The connection is removed from the blocked list.
   107753 */
   107754 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
   107755   sqlite3ConnectionUnlocked(db);
   107756   enterMutex();
   107757   removeFromBlockedList(db);
   107758   checkListProperties(db);
   107759   leaveMutex();
   107760 }
   107761 #endif
   107762 
   107763 /************** End of notify.c **********************************************/
   107764 /************** Begin file fts3.c ********************************************/
   107765 /*
   107766 ** 2006 Oct 10
   107767 **
   107768 ** The author disclaims copyright to this source code.  In place of
   107769 ** a legal notice, here is a blessing:
   107770 **
   107771 **    May you do good and not evil.
   107772 **    May you find forgiveness for yourself and forgive others.
   107773 **    May you share freely, never taking more than you give.
   107774 **
   107775 ******************************************************************************
   107776 **
   107777 ** This is an SQLite module implementing full-text search.
   107778 */
   107779 
   107780 /*
   107781 ** The code in this file is only compiled if:
   107782 **
   107783 **     * The FTS3 module is being built as an extension
   107784 **       (in which case SQLITE_CORE is not defined), or
   107785 **
   107786 **     * The FTS3 module is being built into the core of
   107787 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   107788 */
   107789 
   107790 /* The full-text index is stored in a series of b+tree (-like)
   107791 ** structures called segments which map terms to doclists.  The
   107792 ** structures are like b+trees in layout, but are constructed from the
   107793 ** bottom up in optimal fashion and are not updatable.  Since trees
   107794 ** are built from the bottom up, things will be described from the
   107795 ** bottom up.
   107796 **
   107797 **
   107798 **** Varints ****
   107799 ** The basic unit of encoding is a variable-length integer called a
   107800 ** varint.  We encode variable-length integers in little-endian order
   107801 ** using seven bits * per byte as follows:
   107802 **
   107803 ** KEY:
   107804 **         A = 0xxxxxxx    7 bits of data and one flag bit
   107805 **         B = 1xxxxxxx    7 bits of data and one flag bit
   107806 **
   107807 **  7 bits - A
   107808 ** 14 bits - BA
   107809 ** 21 bits - BBA
   107810 ** and so on.
   107811 **
   107812 ** This is similar in concept to how sqlite encodes "varints" but
   107813 ** the encoding is not the same.  SQLite varints are big-endian
   107814 ** are are limited to 9 bytes in length whereas FTS3 varints are
   107815 ** little-endian and can be up to 10 bytes in length (in theory).
   107816 **
   107817 ** Example encodings:
   107818 **
   107819 **     1:    0x01
   107820 **   127:    0x7f
   107821 **   128:    0x81 0x00
   107822 **
   107823 **
   107824 **** Document lists ****
   107825 ** A doclist (document list) holds a docid-sorted list of hits for a
   107826 ** given term.  Doclists hold docids and associated token positions.
   107827 ** A docid is the unique integer identifier for a single document.
   107828 ** A position is the index of a word within the document.  The first
   107829 ** word of the document has a position of 0.
   107830 **
   107831 ** FTS3 used to optionally store character offsets using a compile-time
   107832 ** option.  But that functionality is no longer supported.
   107833 **
   107834 ** A doclist is stored like this:
   107835 **
   107836 ** array {
   107837 **   varint docid;
   107838 **   array {                (position list for column 0)
   107839 **     varint position;     (2 more than the delta from previous position)
   107840 **   }
   107841 **   array {
   107842 **     varint POS_COLUMN;   (marks start of position list for new column)
   107843 **     varint column;       (index of new column)
   107844 **     array {
   107845 **       varint position;   (2 more than the delta from previous position)
   107846 **     }
   107847 **   }
   107848 **   varint POS_END;        (marks end of positions for this document.
   107849 ** }
   107850 **
   107851 ** Here, array { X } means zero or more occurrences of X, adjacent in
   107852 ** memory.  A "position" is an index of a token in the token stream
   107853 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
   107854 ** in the same logical place as the position element, and act as sentinals
   107855 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
   107856 ** The positions numbers are not stored literally but rather as two more
   107857 ** than the difference from the prior position, or the just the position plus
   107858 ** 2 for the first position.  Example:
   107859 **
   107860 **   label:       A B C D E  F  G H   I  J K
   107861 **   value:     123 5 9 1 1 14 35 0 234 72 0
   107862 **
   107863 ** The 123 value is the first docid.  For column zero in this document
   107864 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
   107865 ** at D signals the start of a new column; the 1 at E indicates that the
   107866 ** new column is column number 1.  There are two positions at 12 and 45
   107867 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
   107868 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
   107869 ** terminates with the 0 at K.
   107870 **
   107871 ** A "position-list" is the list of positions for multiple columns for
   107872 ** a single docid.  A "column-list" is the set of positions for a single
   107873 ** column.  Hence, a position-list consists of one or more column-lists,
   107874 ** a document record consists of a docid followed by a position-list and
   107875 ** a doclist consists of one or more document records.
   107876 **
   107877 ** A bare doclist omits the position information, becoming an
   107878 ** array of varint-encoded docids.
   107879 **
   107880 **** Segment leaf nodes ****
   107881 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
   107882 ** nodes are written using LeafWriter, and read using LeafReader (to
   107883 ** iterate through a single leaf node's data) and LeavesReader (to
   107884 ** iterate through a segment's entire leaf layer).  Leaf nodes have
   107885 ** the format:
   107886 **
   107887 ** varint iHeight;             (height from leaf level, always 0)
   107888 ** varint nTerm;               (length of first term)
   107889 ** char pTerm[nTerm];          (content of first term)
   107890 ** varint nDoclist;            (length of term's associated doclist)
   107891 ** char pDoclist[nDoclist];    (content of doclist)
   107892 ** array {
   107893 **                             (further terms are delta-encoded)
   107894 **   varint nPrefix;           (length of prefix shared with previous term)
   107895 **   varint nSuffix;           (length of unshared suffix)
   107896 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
   107897 **   varint nDoclist;          (length of term's associated doclist)
   107898 **   char pDoclist[nDoclist];  (content of doclist)
   107899 ** }
   107900 **
   107901 ** Here, array { X } means zero or more occurrences of X, adjacent in
   107902 ** memory.
   107903 **
   107904 ** Leaf nodes are broken into blocks which are stored contiguously in
   107905 ** the %_segments table in sorted order.  This means that when the end
   107906 ** of a node is reached, the next term is in the node with the next
   107907 ** greater node id.
   107908 **
   107909 ** New data is spilled to a new leaf node when the current node
   107910 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
   107911 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
   107912 ** node (a leaf node with a single term and doclist).  The goal of
   107913 ** these settings is to pack together groups of small doclists while
   107914 ** making it efficient to directly access large doclists.  The
   107915 ** assumption is that large doclists represent terms which are more
   107916 ** likely to be query targets.
   107917 **
   107918 ** TODO(shess) It may be useful for blocking decisions to be more
   107919 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
   107920 ** node rather than splitting into 2k and .5k nodes.  My intuition is
   107921 ** that this might extend through 2x or 4x the pagesize.
   107922 **
   107923 **
   107924 **** Segment interior nodes ****
   107925 ** Segment interior nodes store blockids for subtree nodes and terms
   107926 ** to describe what data is stored by the each subtree.  Interior
   107927 ** nodes are written using InteriorWriter, and read using
   107928 ** InteriorReader.  InteriorWriters are created as needed when
   107929 ** SegmentWriter creates new leaf nodes, or when an interior node
   107930 ** itself grows too big and must be split.  The format of interior
   107931 ** nodes:
   107932 **
   107933 ** varint iHeight;           (height from leaf level, always >0)
   107934 ** varint iBlockid;          (block id of node's leftmost subtree)
   107935 ** optional {
   107936 **   varint nTerm;           (length of first term)
   107937 **   char pTerm[nTerm];      (content of first term)
   107938 **   array {
   107939 **                                (further terms are delta-encoded)
   107940 **     varint nPrefix;            (length of shared prefix with previous term)
   107941 **     varint nSuffix;            (length of unshared suffix)
   107942 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
   107943 **   }
   107944 ** }
   107945 **
   107946 ** Here, optional { X } means an optional element, while array { X }
   107947 ** means zero or more occurrences of X, adjacent in memory.
   107948 **
   107949 ** An interior node encodes n terms separating n+1 subtrees.  The
   107950 ** subtree blocks are contiguous, so only the first subtree's blockid
   107951 ** is encoded.  The subtree at iBlockid will contain all terms less
   107952 ** than the first term encoded (or all terms if no term is encoded).
   107953 ** Otherwise, for terms greater than or equal to pTerm[i] but less
   107954 ** than pTerm[i+1], the subtree for that term will be rooted at
   107955 ** iBlockid+i.  Interior nodes only store enough term data to
   107956 ** distinguish adjacent children (if the rightmost term of the left
   107957 ** child is "something", and the leftmost term of the right child is
   107958 ** "wicked", only "w" is stored).
   107959 **
   107960 ** New data is spilled to a new interior node at the same height when
   107961 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
   107962 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
   107963 ** interior nodes and making the tree too skinny.  The interior nodes
   107964 ** at a given height are naturally tracked by interior nodes at
   107965 ** height+1, and so on.
   107966 **
   107967 **
   107968 **** Segment directory ****
   107969 ** The segment directory in table %_segdir stores meta-information for
   107970 ** merging and deleting segments, and also the root node of the
   107971 ** segment's tree.
   107972 **
   107973 ** The root node is the top node of the segment's tree after encoding
   107974 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
   107975 ** This could be either a leaf node or an interior node.  If the top
   107976 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
   107977 ** and a new root interior node is generated (which should always fit
   107978 ** within ROOT_MAX because it only needs space for 2 varints, the
   107979 ** height and the blockid of the previous root).
   107980 **
   107981 ** The meta-information in the segment directory is:
   107982 **   level               - segment level (see below)
   107983 **   idx                 - index within level
   107984 **                       - (level,idx uniquely identify a segment)
   107985 **   start_block         - first leaf node
   107986 **   leaves_end_block    - last leaf node
   107987 **   end_block           - last block (including interior nodes)
   107988 **   root                - contents of root node
   107989 **
   107990 ** If the root node is a leaf node, then start_block,
   107991 ** leaves_end_block, and end_block are all 0.
   107992 **
   107993 **
   107994 **** Segment merging ****
   107995 ** To amortize update costs, segments are grouped into levels and
   107996 ** merged in batches.  Each increase in level represents exponentially
   107997 ** more documents.
   107998 **
   107999 ** New documents (actually, document updates) are tokenized and
   108000 ** written individually (using LeafWriter) to a level 0 segment, with
   108001 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
   108002 ** level 0 segments are merged into a single level 1 segment.  Level 1
   108003 ** is populated like level 0, and eventually MERGE_COUNT level 1
   108004 ** segments are merged to a single level 2 segment (representing
   108005 ** MERGE_COUNT^2 updates), and so on.
   108006 **
   108007 ** A segment merge traverses all segments at a given level in
   108008 ** parallel, performing a straightforward sorted merge.  Since segment
   108009 ** leaf nodes are written in to the %_segments table in order, this
   108010 ** merge traverses the underlying sqlite disk structures efficiently.
   108011 ** After the merge, all segment blocks from the merged level are
   108012 ** deleted.
   108013 **
   108014 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
   108015 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
   108016 ** very similar performance numbers to 16 on insertion, though they're
   108017 ** a tiny bit slower (perhaps due to more overhead in merge-time
   108018 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
   108019 ** 16, 2 about 66% slower than 16.
   108020 **
   108021 ** At query time, high MERGE_COUNT increases the number of segments
   108022 ** which need to be scanned and merged.  For instance, with 100k docs
   108023 ** inserted:
   108024 **
   108025 **    MERGE_COUNT   segments
   108026 **       16           25
   108027 **        8           12
   108028 **        4           10
   108029 **        2            6
   108030 **
   108031 ** This appears to have only a moderate impact on queries for very
   108032 ** frequent terms (which are somewhat dominated by segment merge
   108033 ** costs), and infrequent and non-existent terms still seem to be fast
   108034 ** even with many segments.
   108035 **
   108036 ** TODO(shess) That said, it would be nice to have a better query-side
   108037 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
   108038 ** optimizations to things like doclist merging will swing the sweet
   108039 ** spot around.
   108040 **
   108041 **
   108042 **
   108043 **** Handling of deletions and updates ****
   108044 ** Since we're using a segmented structure, with no docid-oriented
   108045 ** index into the term index, we clearly cannot simply update the term
   108046 ** index when a document is deleted or updated.  For deletions, we
   108047 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
   108048 ** we simply write the new doclist.  Segment merges overwrite older
   108049 ** data for a particular docid with newer data, so deletes or updates
   108050 ** will eventually overtake the earlier data and knock it out.  The
   108051 ** query logic likewise merges doclists so that newer data knocks out
   108052 ** older data.
   108053 **
   108054 ** TODO(shess) Provide a VACUUM type operation to clear out all
   108055 ** deletions and duplications.  This would basically be a forced merge
   108056 ** into a single segment.
   108057 */
   108058 
   108059 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   108060 
   108061 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
   108062 # define SQLITE_CORE 1
   108063 #endif
   108064 
   108065 /************** Include fts3Int.h in the middle of fts3.c ********************/
   108066 /************** Begin file fts3Int.h *****************************************/
   108067 /*
   108068 ** 2009 Nov 12
   108069 **
   108070 ** The author disclaims copyright to this source code.  In place of
   108071 ** a legal notice, here is a blessing:
   108072 **
   108073 **    May you do good and not evil.
   108074 **    May you find forgiveness for yourself and forgive others.
   108075 **    May you share freely, never taking more than you give.
   108076 **
   108077 ******************************************************************************
   108078 **
   108079 */
   108080 
   108081 #ifndef _FTSINT_H
   108082 #define _FTSINT_H
   108083 
   108084 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   108085 # define NDEBUG 1
   108086 #endif
   108087 
   108088 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
   108089 /************** Begin file fts3_tokenizer.h **********************************/
   108090 /*
   108091 ** 2006 July 10
   108092 **
   108093 ** The author disclaims copyright to this source code.
   108094 **
   108095 *************************************************************************
   108096 ** Defines the interface to tokenizers used by fulltext-search.  There
   108097 ** are three basic components:
   108098 **
   108099 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
   108100 ** interface functions.  This is essentially the class structure for
   108101 ** tokenizers.
   108102 **
   108103 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
   108104 ** including customization information defined at creation time.
   108105 **
   108106 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
   108107 ** tokens from a particular input.
   108108 */
   108109 #ifndef _FTS3_TOKENIZER_H_
   108110 #define _FTS3_TOKENIZER_H_
   108111 
   108112 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
   108113 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
   108114 ** we will need a way to register the API consistently.
   108115 */
   108116 
   108117 /*
   108118 ** Structures used by the tokenizer interface. When a new tokenizer
   108119 ** implementation is registered, the caller provides a pointer to
   108120 ** an sqlite3_tokenizer_module containing pointers to the callback
   108121 ** functions that make up an implementation.
   108122 **
   108123 ** When an fts3 table is created, it passes any arguments passed to
   108124 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
   108125 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
   108126 ** implementation. The xCreate() function in turn returns an
   108127 ** sqlite3_tokenizer structure representing the specific tokenizer to
   108128 ** be used for the fts3 table (customized by the tokenizer clause arguments).
   108129 **
   108130 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
   108131 ** method is called. It returns an sqlite3_tokenizer_cursor object
   108132 ** that may be used to tokenize a specific input buffer based on
   108133 ** the tokenization rules supplied by a specific sqlite3_tokenizer
   108134 ** object.
   108135 */
   108136 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
   108137 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
   108138 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
   108139 
   108140 struct sqlite3_tokenizer_module {
   108141 
   108142   /*
   108143   ** Structure version. Should always be set to 0.
   108144   */
   108145   int iVersion;
   108146 
   108147   /*
   108148   ** Create a new tokenizer. The values in the argv[] array are the
   108149   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
   108150   ** TABLE statement that created the fts3 table. For example, if
   108151   ** the following SQL is executed:
   108152   **
   108153   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
   108154   **
   108155   ** then argc is set to 2, and the argv[] array contains pointers
   108156   ** to the strings "arg1" and "arg2".
   108157   **
   108158   ** This method should return either SQLITE_OK (0), or an SQLite error
   108159   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   108160   ** to point at the newly created tokenizer structure. The generic
   108161   ** sqlite3_tokenizer.pModule variable should not be initialised by
   108162   ** this callback. The caller will do so.
   108163   */
   108164   int (*xCreate)(
   108165     int argc,                           /* Size of argv array */
   108166     const char *const*argv,             /* Tokenizer argument strings */
   108167     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
   108168   );
   108169 
   108170   /*
   108171   ** Destroy an existing tokenizer. The fts3 module calls this method
   108172   ** exactly once for each successful call to xCreate().
   108173   */
   108174   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
   108175 
   108176   /*
   108177   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   108178   ** is responsible for ensuring that the input buffer remains valid
   108179   ** until the cursor is closed (using the xClose() method).
   108180   */
   108181   int (*xOpen)(
   108182     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
   108183     const char *pInput, int nBytes,      /* Input buffer */
   108184     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
   108185   );
   108186 
   108187   /*
   108188   ** Destroy an existing tokenizer cursor. The fts3 module calls this
   108189   ** method exactly once for each successful call to xOpen().
   108190   */
   108191   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
   108192 
   108193   /*
   108194   ** Retrieve the next token from the tokenizer cursor pCursor. This
   108195   ** method should either return SQLITE_OK and set the values of the
   108196   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   108197   ** the end of the buffer has been reached, or an SQLite error code.
   108198   **
   108199   ** *ppToken should be set to point at a buffer containing the
   108200   ** normalized version of the token (i.e. after any case-folding and/or
   108201   ** stemming has been performed). *pnBytes should be set to the length
   108202   ** of this buffer in bytes. The input text that generated the token is
   108203   ** identified by the byte offsets returned in *piStartOffset and
   108204   ** *piEndOffset. *piStartOffset should be set to the index of the first
   108205   ** byte of the token in the input buffer. *piEndOffset should be set
   108206   ** to the index of the first byte just past the end of the token in
   108207   ** the input buffer.
   108208   **
   108209   ** The buffer *ppToken is set to point at is managed by the tokenizer
   108210   ** implementation. It is only required to be valid until the next call
   108211   ** to xNext() or xClose().
   108212   */
   108213   /* TODO(shess) current implementation requires pInput to be
   108214   ** nul-terminated.  This should either be fixed, or pInput/nBytes
   108215   ** should be converted to zInput.
   108216   */
   108217   int (*xNext)(
   108218     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
   108219     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
   108220     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
   108221     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
   108222     int *piPosition      /* OUT: Number of tokens returned before this one */
   108223   );
   108224 };
   108225 
   108226 struct sqlite3_tokenizer {
   108227   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
   108228   /* Tokenizer implementations will typically add additional fields */
   108229 };
   108230 
   108231 struct sqlite3_tokenizer_cursor {
   108232   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
   108233   /* Tokenizer implementations will typically add additional fields */
   108234 };
   108235 
   108236 int fts3_global_term_cnt(int iTerm, int iCol);
   108237 int fts3_term_cnt(int iTerm, int iCol);
   108238 
   108239 
   108240 #endif /* _FTS3_TOKENIZER_H_ */
   108241 
   108242 /************** End of fts3_tokenizer.h **************************************/
   108243 /************** Continuing where we left off in fts3Int.h ********************/
   108244 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
   108245 /************** Begin file fts3_hash.h ***************************************/
   108246 /*
   108247 ** 2001 September 22
   108248 **
   108249 ** The author disclaims copyright to this source code.  In place of
   108250 ** a legal notice, here is a blessing:
   108251 **
   108252 **    May you do good and not evil.
   108253 **    May you find forgiveness for yourself and forgive others.
   108254 **    May you share freely, never taking more than you give.
   108255 **
   108256 *************************************************************************
   108257 ** This is the header file for the generic hash-table implemenation
   108258 ** used in SQLite.  We've modified it slightly to serve as a standalone
   108259 ** hash table implementation for the full-text indexing module.
   108260 **
   108261 */
   108262 #ifndef _FTS3_HASH_H_
   108263 #define _FTS3_HASH_H_
   108264 
   108265 /* Forward declarations of structures. */
   108266 typedef struct Fts3Hash Fts3Hash;
   108267 typedef struct Fts3HashElem Fts3HashElem;
   108268 
   108269 /* A complete hash table is an instance of the following structure.
   108270 ** The internals of this structure are intended to be opaque -- client
   108271 ** code should not attempt to access or modify the fields of this structure
   108272 ** directly.  Change this structure only by using the routines below.
   108273 ** However, many of the "procedures" and "functions" for modifying and
   108274 ** accessing this structure are really macros, so we can't really make
   108275 ** this structure opaque.
   108276 */
   108277 struct Fts3Hash {
   108278   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
   108279   char copyKey;           /* True if copy of key made on insert */
   108280   int count;              /* Number of entries in this table */
   108281   Fts3HashElem *first;    /* The first element of the array */
   108282   int htsize;             /* Number of buckets in the hash table */
   108283   struct _fts3ht {        /* the hash table */
   108284     int count;               /* Number of entries with this hash */
   108285     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
   108286   } *ht;
   108287 };
   108288 
   108289 /* Each element in the hash table is an instance of the following
   108290 ** structure.  All elements are stored on a single doubly-linked list.
   108291 **
   108292 ** Again, this structure is intended to be opaque, but it can't really
   108293 ** be opaque because it is used by macros.
   108294 */
   108295 struct Fts3HashElem {
   108296   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
   108297   void *data;                /* Data associated with this element */
   108298   void *pKey; int nKey;      /* Key associated with this element */
   108299 };
   108300 
   108301 /*
   108302 ** There are 2 different modes of operation for a hash table:
   108303 **
   108304 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
   108305 **                           (including the null-terminator, if any).  Case
   108306 **                           is respected in comparisons.
   108307 **
   108308 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
   108309 **                           memcmp() is used to compare keys.
   108310 **
   108311 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
   108312 */
   108313 #define FTS3_HASH_STRING    1
   108314 #define FTS3_HASH_BINARY    2
   108315 
   108316 /*
   108317 ** Access routines.  To delete, insert a NULL pointer.
   108318 */
   108319 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
   108320 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
   108321 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
   108322 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
   108323 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
   108324 
   108325 /*
   108326 ** Shorthand for the functions above
   108327 */
   108328 #define fts3HashInit     sqlite3Fts3HashInit
   108329 #define fts3HashInsert   sqlite3Fts3HashInsert
   108330 #define fts3HashFind     sqlite3Fts3HashFind
   108331 #define fts3HashClear    sqlite3Fts3HashClear
   108332 #define fts3HashFindElem sqlite3Fts3HashFindElem
   108333 
   108334 /*
   108335 ** Macros for looping over all elements of a hash table.  The idiom is
   108336 ** like this:
   108337 **
   108338 **   Fts3Hash h;
   108339 **   Fts3HashElem *p;
   108340 **   ...
   108341 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
   108342 **     SomeStructure *pData = fts3HashData(p);
   108343 **     // do something with pData
   108344 **   }
   108345 */
   108346 #define fts3HashFirst(H)  ((H)->first)
   108347 #define fts3HashNext(E)   ((E)->next)
   108348 #define fts3HashData(E)   ((E)->data)
   108349 #define fts3HashKey(E)    ((E)->pKey)
   108350 #define fts3HashKeysize(E) ((E)->nKey)
   108351 
   108352 /*
   108353 ** Number of entries in a hash table
   108354 */
   108355 #define fts3HashCount(H)  ((H)->count)
   108356 
   108357 #endif /* _FTS3_HASH_H_ */
   108358 
   108359 /************** End of fts3_hash.h *******************************************/
   108360 /************** Continuing where we left off in fts3Int.h ********************/
   108361 
   108362 /*
   108363 ** This constant controls how often segments are merged. Once there are
   108364 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
   108365 ** segment of level N+1.
   108366 */
   108367 #define FTS3_MERGE_COUNT 16
   108368 
   108369 /*
   108370 ** This is the maximum amount of data (in bytes) to store in the
   108371 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
   108372 ** populated as documents are inserted/updated/deleted in a transaction
   108373 ** and used to create a new segment when the transaction is committed.
   108374 ** However if this limit is reached midway through a transaction, a new
   108375 ** segment is created and the hash table cleared immediately.
   108376 */
   108377 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
   108378 
   108379 /*
   108380 ** Macro to return the number of elements in an array. SQLite has a
   108381 ** similar macro called ArraySize(). Use a different name to avoid
   108382 ** a collision when building an amalgamation with built-in FTS3.
   108383 */
   108384 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
   108385 
   108386 /*
   108387 ** Maximum length of a varint encoded integer. The varint format is different
   108388 ** from that used by SQLite, so the maximum length is 10, not 9.
   108389 */
   108390 #define FTS3_VARINT_MAX 10
   108391 
   108392 /*
   108393 ** The testcase() macro is only used by the amalgamation.  If undefined,
   108394 ** make it a no-op.
   108395 */
   108396 #ifndef testcase
   108397 # define testcase(X)
   108398 #endif
   108399 
   108400 /*
   108401 ** Terminator values for position-lists and column-lists.
   108402 */
   108403 #define POS_COLUMN  (1)     /* Column-list terminator */
   108404 #define POS_END     (0)     /* Position-list terminator */
   108405 
   108406 /*
   108407 ** This section provides definitions to allow the
   108408 ** FTS3 extension to be compiled outside of the
   108409 ** amalgamation.
   108410 */
   108411 #ifndef SQLITE_AMALGAMATION
   108412 /*
   108413 ** Macros indicating that conditional expressions are always true or
   108414 ** false.
   108415 */
   108416 #ifdef SQLITE_COVERAGE_TEST
   108417 # define ALWAYS(x) (1)
   108418 # define NEVER(X)  (0)
   108419 #else
   108420 # define ALWAYS(x) (x)
   108421 # define NEVER(X)  (x)
   108422 #endif
   108423 
   108424 /*
   108425 ** Internal types used by SQLite.
   108426 */
   108427 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
   108428 typedef short int i16;            /* 2-byte (or larger) signed integer */
   108429 typedef unsigned int u32;         /* 4-byte unsigned integer */
   108430 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
   108431 /*
   108432 ** Macro used to suppress compiler warnings for unused parameters.
   108433 */
   108434 #define UNUSED_PARAMETER(x) (void)(x)
   108435 #endif
   108436 
   108437 typedef struct Fts3Table Fts3Table;
   108438 typedef struct Fts3Cursor Fts3Cursor;
   108439 typedef struct Fts3Expr Fts3Expr;
   108440 typedef struct Fts3Phrase Fts3Phrase;
   108441 typedef struct Fts3PhraseToken Fts3PhraseToken;
   108442 
   108443 typedef struct Fts3SegFilter Fts3SegFilter;
   108444 typedef struct Fts3DeferredToken Fts3DeferredToken;
   108445 typedef struct Fts3SegReader Fts3SegReader;
   108446 typedef struct Fts3SegReaderArray Fts3SegReaderArray;
   108447 
   108448 /*
   108449 ** A connection to a fulltext index is an instance of the following
   108450 ** structure. The xCreate and xConnect methods create an instance
   108451 ** of this structure and xDestroy and xDisconnect free that instance.
   108452 ** All other methods receive a pointer to the structure as one of their
   108453 ** arguments.
   108454 */
   108455 struct Fts3Table {
   108456   sqlite3_vtab base;              /* Base class used by SQLite core */
   108457   sqlite3 *db;                    /* The database connection */
   108458   const char *zDb;                /* logical database name */
   108459   const char *zName;              /* virtual table name */
   108460   int nColumn;                    /* number of named columns in virtual table */
   108461   char **azColumn;                /* column names.  malloced */
   108462   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
   108463 
   108464   /* Precompiled statements used by the implementation. Each of these
   108465   ** statements is run and reset within a single virtual table API call.
   108466   */
   108467   sqlite3_stmt *aStmt[24];
   108468 
   108469   int nNodeSize;                  /* Soft limit for node size */
   108470   u8 bHasStat;                    /* True if %_stat table exists */
   108471   u8 bHasDocsize;                 /* True if %_docsize table exists */
   108472   int nPgsz;                      /* Page size for host database */
   108473   char *zSegmentsTbl;             /* Name of %_segments table */
   108474   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
   108475 
   108476   /* The following hash table is used to buffer pending index updates during
   108477   ** transactions. Variable nPendingData estimates the memory size of the
   108478   ** pending data, including hash table overhead, but not malloc overhead.
   108479   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
   108480   ** automatically. Variable iPrevDocid is the docid of the most recently
   108481   ** inserted record.
   108482   */
   108483   int nMaxPendingData;
   108484   int nPendingData;
   108485   sqlite_int64 iPrevDocid;
   108486   Fts3Hash pendingTerms;
   108487 };
   108488 
   108489 /*
   108490 ** When the core wants to read from the virtual table, it creates a
   108491 ** virtual table cursor (an instance of the following structure) using
   108492 ** the xOpen method. Cursors are destroyed using the xClose method.
   108493 */
   108494 struct Fts3Cursor {
   108495   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
   108496   i16 eSearch;                    /* Search strategy (see below) */
   108497   u8 isEof;                       /* True if at End Of Results */
   108498   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
   108499   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
   108500   Fts3Expr *pExpr;                /* Parsed MATCH query string */
   108501   int nPhrase;                    /* Number of matchable phrases in query */
   108502   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
   108503   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
   108504   char *pNextId;                  /* Pointer into the body of aDoclist */
   108505   char *aDoclist;                 /* List of docids for full-text queries */
   108506   int nDoclist;                   /* Size of buffer at aDoclist */
   108507   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
   108508   int nRowAvg;                    /* Average size of database rows, in pages */
   108509 
   108510   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
   108511   u32 *aMatchinfo;                /* Information about most recent match */
   108512   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
   108513   char *zMatchinfo;               /* Matchinfo specification */
   108514 };
   108515 
   108516 #define FTS3_EVAL_FILTER    0
   108517 #define FTS3_EVAL_NEXT      1
   108518 #define FTS3_EVAL_MATCHINFO 2
   108519 
   108520 /*
   108521 ** The Fts3Cursor.eSearch member is always set to one of the following.
   108522 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
   108523 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
   108524 ** of the column to be searched.  For example, in
   108525 **
   108526 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
   108527 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
   108528 **
   108529 ** Because the LHS of the MATCH operator is 2nd column "b",
   108530 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
   108531 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
   108532 ** indicating that all columns should be searched,
   108533 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
   108534 */
   108535 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
   108536 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
   108537 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
   108538 
   108539 /*
   108540 ** A "phrase" is a sequence of one or more tokens that must match in
   108541 ** sequence.  A single token is the base case and the most common case.
   108542 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
   108543 ** nToken will be the number of tokens in the string.
   108544 **
   108545 ** The nDocMatch and nMatch variables contain data that may be used by the
   108546 ** matchinfo() function. They are populated when the full-text index is
   108547 ** queried for hits on the phrase. If one or more tokens in the phrase
   108548 ** are deferred, the nDocMatch and nMatch variables are populated based
   108549 ** on the assumption that the
   108550 */
   108551 struct Fts3PhraseToken {
   108552   char *z;                        /* Text of the token */
   108553   int n;                          /* Number of bytes in buffer z */
   108554   int isPrefix;                   /* True if token ends with a "*" character */
   108555   int bFulltext;                  /* True if full-text index was used */
   108556   Fts3SegReaderArray *pArray;     /* Segment-reader for this token */
   108557   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
   108558 };
   108559 
   108560 struct Fts3Phrase {
   108561   /* Variables populated by fts3_expr.c when parsing a MATCH expression */
   108562   int nToken;                /* Number of tokens in the phrase */
   108563   int iColumn;               /* Index of column this phrase must match */
   108564   int isNot;                 /* Phrase prefixed by unary not (-) operator */
   108565   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
   108566 };
   108567 
   108568 /*
   108569 ** A tree of these objects forms the RHS of a MATCH operator.
   108570 **
   108571 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
   108572 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
   108573 ** containing the results of the NEAR or phrase query in FTS3 doclist
   108574 ** format. As usual, the initial "Length" field found in doclists stored
   108575 ** on disk is omitted from this buffer.
   108576 **
   108577 ** Variable pCurrent always points to the start of a docid field within
   108578 ** aDoclist. Since the doclist is usually scanned in docid order, this can
   108579 ** be used to accelerate seeking to the required docid within the doclist.
   108580 */
   108581 struct Fts3Expr {
   108582   int eType;                 /* One of the FTSQUERY_XXX values defined below */
   108583   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
   108584   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
   108585   Fts3Expr *pLeft;           /* Left operand */
   108586   Fts3Expr *pRight;          /* Right operand */
   108587   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
   108588 
   108589   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
   108590   char *aDoclist;            /* Buffer containing doclist */
   108591   int nDoclist;              /* Size of aDoclist in bytes */
   108592 
   108593   sqlite3_int64 iCurrent;
   108594   char *pCurrent;
   108595 };
   108596 
   108597 /*
   108598 ** Candidate values for Fts3Query.eType. Note that the order of the first
   108599 ** four values is in order of precedence when parsing expressions. For
   108600 ** example, the following:
   108601 **
   108602 **   "a OR b AND c NOT d NEAR e"
   108603 **
   108604 ** is equivalent to:
   108605 **
   108606 **   "a OR (b AND (c NOT (d NEAR e)))"
   108607 */
   108608 #define FTSQUERY_NEAR   1
   108609 #define FTSQUERY_NOT    2
   108610 #define FTSQUERY_AND    3
   108611 #define FTSQUERY_OR     4
   108612 #define FTSQUERY_PHRASE 5
   108613 
   108614 
   108615 /* fts3_write.c */
   108616 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
   108617 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
   108618 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
   108619 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
   108620 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
   108621   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
   108622 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
   108623 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
   108624 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
   108625   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
   108626   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
   108627 );
   108628 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
   108629 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
   108630 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
   108631 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
   108632 
   108633 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
   108634 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
   108635 
   108636 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
   108637 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
   108638 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
   108639 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
   108640 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
   108641 
   108642 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
   108643 
   108644 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
   108645 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
   108646 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
   108647 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
   108648 #define FTS3_SEGMENT_PREFIX        0x00000008
   108649 
   108650 /* Type passed as 4th argument to SegmentReaderIterate() */
   108651 struct Fts3SegFilter {
   108652   const char *zTerm;
   108653   int nTerm;
   108654   int iCol;
   108655   int flags;
   108656 };
   108657 
   108658 /* fts3.c */
   108659 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
   108660 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
   108661 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
   108662 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
   108663 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
   108664 
   108665 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
   108666 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
   108667 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
   108668 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
   108669 
   108670 /* fts3_tokenizer.c */
   108671 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
   108672 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
   108673 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
   108674     sqlite3_tokenizer **, char **
   108675 );
   108676 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
   108677 
   108678 /* fts3_snippet.c */
   108679 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
   108680 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
   108681   const char *, const char *, int, int
   108682 );
   108683 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
   108684 
   108685 /* fts3_expr.c */
   108686 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
   108687   char **, int, int, const char *, int, Fts3Expr **
   108688 );
   108689 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
   108690 #ifdef SQLITE_TEST
   108691 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
   108692 #endif
   108693 
   108694 #endif /* _FTSINT_H */
   108695 
   108696 /************** End of fts3Int.h *********************************************/
   108697 /************** Continuing where we left off in fts3.c ***********************/
   108698 
   108699 
   108700 #ifndef SQLITE_CORE
   108701   SQLITE_EXTENSION_INIT1
   108702 #endif
   108703 
   108704 /*
   108705 ** Write a 64-bit variable-length integer to memory starting at p[0].
   108706 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
   108707 ** The number of bytes written is returned.
   108708 */
   108709 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   108710   unsigned char *q = (unsigned char *) p;
   108711   sqlite_uint64 vu = v;
   108712   do{
   108713     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
   108714     vu >>= 7;
   108715   }while( vu!=0 );
   108716   q[-1] &= 0x7f;  /* turn off high bit in final byte */
   108717   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
   108718   return (int) (q - (unsigned char *)p);
   108719 }
   108720 
   108721 /*
   108722 ** Read a 64-bit variable-length integer from memory starting at p[0].
   108723 ** Return the number of bytes read, or 0 on error.
   108724 ** The value is stored in *v.
   108725 */
   108726 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
   108727   const unsigned char *q = (const unsigned char *) p;
   108728   sqlite_uint64 x = 0, y = 1;
   108729   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
   108730     x += y * (*q++ & 0x7f);
   108731     y <<= 7;
   108732   }
   108733   x += y * (*q++);
   108734   *v = (sqlite_int64) x;
   108735   return (int) (q - (unsigned char *)p);
   108736 }
   108737 
   108738 /*
   108739 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
   108740 ** 32-bit integer before it is returned.
   108741 */
   108742 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
   108743  sqlite_int64 i;
   108744  int ret = sqlite3Fts3GetVarint(p, &i);
   108745  *pi = (int) i;
   108746  return ret;
   108747 }
   108748 
   108749 /*
   108750 ** Return the number of bytes required to encode v as a varint
   108751 */
   108752 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
   108753   int i = 0;
   108754   do{
   108755     i++;
   108756     v >>= 7;
   108757   }while( v!=0 );
   108758   return i;
   108759 }
   108760 
   108761 /*
   108762 ** Convert an SQL-style quoted string into a normal string by removing
   108763 ** the quote characters.  The conversion is done in-place.  If the
   108764 ** input does not begin with a quote character, then this routine
   108765 ** is a no-op.
   108766 **
   108767 ** Examples:
   108768 **
   108769 **     "abc"   becomes   abc
   108770 **     'xyz'   becomes   xyz
   108771 **     [pqr]   becomes   pqr
   108772 **     `mno`   becomes   mno
   108773 **
   108774 */
   108775 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
   108776   char quote;                     /* Quote character (if any ) */
   108777 
   108778   quote = z[0];
   108779   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
   108780     int iIn = 1;                  /* Index of next byte to read from input */
   108781     int iOut = 0;                 /* Index of next byte to write to output */
   108782 
   108783     /* If the first byte was a '[', then the close-quote character is a ']' */
   108784     if( quote=='[' ) quote = ']';
   108785 
   108786     while( ALWAYS(z[iIn]) ){
   108787       if( z[iIn]==quote ){
   108788         if( z[iIn+1]!=quote ) break;
   108789         z[iOut++] = quote;
   108790         iIn += 2;
   108791       }else{
   108792         z[iOut++] = z[iIn++];
   108793       }
   108794     }
   108795     z[iOut] = '\0';
   108796   }
   108797 }
   108798 
   108799 /*
   108800 ** Read a single varint from the doclist at *pp and advance *pp to point
   108801 ** to the first byte past the end of the varint.  Add the value of the varint
   108802 ** to *pVal.
   108803 */
   108804 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
   108805   sqlite3_int64 iVal;
   108806   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
   108807   *pVal += iVal;
   108808 }
   108809 
   108810 /*
   108811 ** As long as *pp has not reached its end (pEnd), then do the same
   108812 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
   108813 ** But if we have reached the end of the varint, just set *pp=0 and
   108814 ** leave *pVal unchanged.
   108815 */
   108816 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
   108817   if( *pp>=pEnd ){
   108818     *pp = 0;
   108819   }else{
   108820     fts3GetDeltaVarint(pp, pVal);
   108821   }
   108822 }
   108823 
   108824 /*
   108825 ** The xDisconnect() virtual table method.
   108826 */
   108827 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
   108828   Fts3Table *p = (Fts3Table *)pVtab;
   108829   int i;
   108830 
   108831   assert( p->nPendingData==0 );
   108832   assert( p->pSegments==0 );
   108833 
   108834   /* Free any prepared statements held */
   108835   for(i=0; i<SizeofArray(p->aStmt); i++){
   108836     sqlite3_finalize(p->aStmt[i]);
   108837   }
   108838   sqlite3_free(p->zSegmentsTbl);
   108839 
   108840   /* Invoke the tokenizer destructor to free the tokenizer. */
   108841   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
   108842 
   108843   sqlite3_free(p);
   108844   return SQLITE_OK;
   108845 }
   108846 
   108847 /*
   108848 ** Construct one or more SQL statements from the format string given
   108849 ** and then evaluate those statements. The success code is written
   108850 ** into *pRc.
   108851 **
   108852 ** If *pRc is initially non-zero then this routine is a no-op.
   108853 */
   108854 static void fts3DbExec(
   108855   int *pRc,              /* Success code */
   108856   sqlite3 *db,           /* Database in which to run SQL */
   108857   const char *zFormat,   /* Format string for SQL */
   108858   ...                    /* Arguments to the format string */
   108859 ){
   108860   va_list ap;
   108861   char *zSql;
   108862   if( *pRc ) return;
   108863   va_start(ap, zFormat);
   108864   zSql = sqlite3_vmprintf(zFormat, ap);
   108865   va_end(ap);
   108866   if( zSql==0 ){
   108867     *pRc = SQLITE_NOMEM;
   108868   }else{
   108869     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
   108870     sqlite3_free(zSql);
   108871   }
   108872 }
   108873 
   108874 /*
   108875 ** The xDestroy() virtual table method.
   108876 */
   108877 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   108878   int rc = SQLITE_OK;              /* Return code */
   108879   Fts3Table *p = (Fts3Table *)pVtab;
   108880   sqlite3 *db = p->db;
   108881 
   108882   /* Drop the shadow tables */
   108883   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
   108884   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
   108885   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
   108886   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
   108887   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
   108888 
   108889   /* If everything has worked, invoke fts3DisconnectMethod() to free the
   108890   ** memory associated with the Fts3Table structure and return SQLITE_OK.
   108891   ** Otherwise, return an SQLite error code.
   108892   */
   108893   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
   108894 }
   108895 
   108896 
   108897 /*
   108898 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
   108899 ** passed as the first argument. This is done as part of the xConnect()
   108900 ** and xCreate() methods.
   108901 **
   108902 ** If *pRc is non-zero when this function is called, it is a no-op.
   108903 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   108904 ** before returning.
   108905 */
   108906 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
   108907   if( *pRc==SQLITE_OK ){
   108908     int i;                        /* Iterator variable */
   108909     int rc;                       /* Return code */
   108910     char *zSql;                   /* SQL statement passed to declare_vtab() */
   108911     char *zCols;                  /* List of user defined columns */
   108912 
   108913     /* Create a list of user columns for the virtual table */
   108914     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
   108915     for(i=1; zCols && i<p->nColumn; i++){
   108916       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
   108917     }
   108918 
   108919     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
   108920     zSql = sqlite3_mprintf(
   108921         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
   108922     );
   108923     if( !zCols || !zSql ){
   108924       rc = SQLITE_NOMEM;
   108925     }else{
   108926       rc = sqlite3_declare_vtab(p->db, zSql);
   108927     }
   108928 
   108929     sqlite3_free(zSql);
   108930     sqlite3_free(zCols);
   108931     *pRc = rc;
   108932   }
   108933 }
   108934 
   108935 /*
   108936 ** Create the backing store tables (%_content, %_segments and %_segdir)
   108937 ** required by the FTS3 table passed as the only argument. This is done
   108938 ** as part of the vtab xCreate() method.
   108939 **
   108940 ** If the p->bHasDocsize boolean is true (indicating that this is an
   108941 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
   108942 ** %_stat tables required by FTS4.
   108943 */
   108944 static int fts3CreateTables(Fts3Table *p){
   108945   int rc = SQLITE_OK;             /* Return code */
   108946   int i;                          /* Iterator variable */
   108947   char *zContentCols;             /* Columns of %_content table */
   108948   sqlite3 *db = p->db;            /* The database connection */
   108949 
   108950   /* Create a list of user columns for the content table */
   108951   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
   108952   for(i=0; zContentCols && i<p->nColumn; i++){
   108953     char *z = p->azColumn[i];
   108954     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
   108955   }
   108956   if( zContentCols==0 ) rc = SQLITE_NOMEM;
   108957 
   108958   /* Create the content table */
   108959   fts3DbExec(&rc, db,
   108960      "CREATE TABLE %Q.'%q_content'(%s)",
   108961      p->zDb, p->zName, zContentCols
   108962   );
   108963   sqlite3_free(zContentCols);
   108964   /* Create other tables */
   108965   fts3DbExec(&rc, db,
   108966       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
   108967       p->zDb, p->zName
   108968   );
   108969   fts3DbExec(&rc, db,
   108970       "CREATE TABLE %Q.'%q_segdir'("
   108971         "level INTEGER,"
   108972         "idx INTEGER,"
   108973         "start_block INTEGER,"
   108974         "leaves_end_block INTEGER,"
   108975         "end_block INTEGER,"
   108976         "root BLOB,"
   108977         "PRIMARY KEY(level, idx)"
   108978       ");",
   108979       p->zDb, p->zName
   108980   );
   108981   if( p->bHasDocsize ){
   108982     fts3DbExec(&rc, db,
   108983         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
   108984         p->zDb, p->zName
   108985     );
   108986   }
   108987   if( p->bHasStat ){
   108988     fts3DbExec(&rc, db,
   108989         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
   108990         p->zDb, p->zName
   108991     );
   108992   }
   108993   return rc;
   108994 }
   108995 
   108996 /*
   108997 ** Store the current database page-size in bytes in p->nPgsz.
   108998 **
   108999 ** If *pRc is non-zero when this function is called, it is a no-op.
   109000 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
   109001 ** before returning.
   109002 */
   109003 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
   109004   if( *pRc==SQLITE_OK ){
   109005     int rc;                       /* Return code */
   109006     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
   109007     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
   109008 
   109009     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
   109010     if( !zSql ){
   109011       rc = SQLITE_NOMEM;
   109012     }else{
   109013       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
   109014       if( rc==SQLITE_OK ){
   109015         sqlite3_step(pStmt);
   109016         p->nPgsz = sqlite3_column_int(pStmt, 0);
   109017         rc = sqlite3_finalize(pStmt);
   109018       }
   109019     }
   109020     assert( p->nPgsz>0 || rc!=SQLITE_OK );
   109021     sqlite3_free(zSql);
   109022     *pRc = rc;
   109023   }
   109024 }
   109025 
   109026 /*
   109027 ** "Special" FTS4 arguments are column specifications of the following form:
   109028 **
   109029 **   <key> = <value>
   109030 **
   109031 ** There may not be whitespace surrounding the "=" character. The <value>
   109032 ** term may be quoted, but the <key> may not.
   109033 */
   109034 static int fts3IsSpecialColumn(
   109035   const char *z,
   109036   int *pnKey,
   109037   char **pzValue
   109038 ){
   109039   char *zValue;
   109040   const char *zCsr = z;
   109041 
   109042   while( *zCsr!='=' ){
   109043     if( *zCsr=='\0' ) return 0;
   109044     zCsr++;
   109045   }
   109046 
   109047   *pnKey = (int)(zCsr-z);
   109048   zValue = sqlite3_mprintf("%s", &zCsr[1]);
   109049   if( zValue ){
   109050     sqlite3Fts3Dequote(zValue);
   109051   }
   109052   *pzValue = zValue;
   109053   return 1;
   109054 }
   109055 
   109056 /*
   109057 ** This function is the implementation of both the xConnect and xCreate
   109058 ** methods of the FTS3 virtual table.
   109059 **
   109060 ** The argv[] array contains the following:
   109061 **
   109062 **   argv[0]   -> module name  ("fts3" or "fts4")
   109063 **   argv[1]   -> database name
   109064 **   argv[2]   -> table name
   109065 **   argv[...] -> "column name" and other module argument fields.
   109066 */
   109067 static int fts3InitVtab(
   109068   int isCreate,                   /* True for xCreate, false for xConnect */
   109069   sqlite3 *db,                    /* The SQLite database connection */
   109070   void *pAux,                     /* Hash table containing tokenizers */
   109071   int argc,                       /* Number of elements in argv array */
   109072   const char * const *argv,       /* xCreate/xConnect argument array */
   109073   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
   109074   char **pzErr                    /* Write any error message here */
   109075 ){
   109076   Fts3Hash *pHash = (Fts3Hash *)pAux;
   109077   Fts3Table *p = 0;               /* Pointer to allocated vtab */
   109078   int rc = SQLITE_OK;             /* Return code */
   109079   int i;                          /* Iterator variable */
   109080   int nByte;                      /* Size of allocation used for *p */
   109081   int iCol;                       /* Column index */
   109082   int nString = 0;                /* Bytes required to hold all column names */
   109083   int nCol = 0;                   /* Number of columns in the FTS table */
   109084   char *zCsr;                     /* Space for holding column names */
   109085   int nDb;                        /* Bytes required to hold database name */
   109086   int nName;                      /* Bytes required to hold table name */
   109087   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
   109088   int bNoDocsize = 0;             /* True to omit %_docsize table */
   109089   const char **aCol;              /* Array of column names */
   109090   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
   109091 
   109092   assert( strlen(argv[0])==4 );
   109093   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
   109094        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
   109095   );
   109096 
   109097   nDb = (int)strlen(argv[1]) + 1;
   109098   nName = (int)strlen(argv[2]) + 1;
   109099 
   109100   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
   109101   if( !aCol ) return SQLITE_NOMEM;
   109102   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
   109103 
   109104   /* Loop through all of the arguments passed by the user to the FTS3/4
   109105   ** module (i.e. all the column names and special arguments). This loop
   109106   ** does the following:
   109107   **
   109108   **   + Figures out the number of columns the FTSX table will have, and
   109109   **     the number of bytes of space that must be allocated to store copies
   109110   **     of the column names.
   109111   **
   109112   **   + If there is a tokenizer specification included in the arguments,
   109113   **     initializes the tokenizer pTokenizer.
   109114   */
   109115   for(i=3; rc==SQLITE_OK && i<argc; i++){
   109116     char const *z = argv[i];
   109117     int nKey;
   109118     char *zVal;
   109119 
   109120     /* Check if this is a tokenizer specification */
   109121     if( !pTokenizer
   109122      && strlen(z)>8
   109123      && 0==sqlite3_strnicmp(z, "tokenize", 8)
   109124      && 0==sqlite3Fts3IsIdChar(z[8])
   109125     ){
   109126       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
   109127     }
   109128 
   109129     /* Check if it is an FTS4 special argument. */
   109130     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
   109131       if( !zVal ){
   109132         rc = SQLITE_NOMEM;
   109133         goto fts3_init_out;
   109134       }
   109135       if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
   109136         if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
   109137           bNoDocsize = 1;
   109138         }else{
   109139           *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
   109140           rc = SQLITE_ERROR;
   109141         }
   109142       }else{
   109143         *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
   109144         rc = SQLITE_ERROR;
   109145       }
   109146       sqlite3_free(zVal);
   109147     }
   109148 
   109149     /* Otherwise, the argument is a column name. */
   109150     else {
   109151       nString += (int)(strlen(z) + 1);
   109152       aCol[nCol++] = z;
   109153     }
   109154   }
   109155   if( rc!=SQLITE_OK ) goto fts3_init_out;
   109156 
   109157   if( nCol==0 ){
   109158     assert( nString==0 );
   109159     aCol[0] = "content";
   109160     nString = 8;
   109161     nCol = 1;
   109162   }
   109163 
   109164   if( pTokenizer==0 ){
   109165     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
   109166     if( rc!=SQLITE_OK ) goto fts3_init_out;
   109167   }
   109168   assert( pTokenizer );
   109169 
   109170 
   109171   /* Allocate and populate the Fts3Table structure. */
   109172   nByte = sizeof(Fts3Table) +              /* Fts3Table */
   109173           nCol * sizeof(char *) +              /* azColumn */
   109174           nName +                              /* zName */
   109175           nDb +                                /* zDb */
   109176           nString;                             /* Space for azColumn strings */
   109177   p = (Fts3Table*)sqlite3_malloc(nByte);
   109178   if( p==0 ){
   109179     rc = SQLITE_NOMEM;
   109180     goto fts3_init_out;
   109181   }
   109182   memset(p, 0, nByte);
   109183   p->db = db;
   109184   p->nColumn = nCol;
   109185   p->nPendingData = 0;
   109186   p->azColumn = (char **)&p[1];
   109187   p->pTokenizer = pTokenizer;
   109188   p->nNodeSize = 1000;
   109189   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
   109190   p->bHasDocsize = (isFts4 && bNoDocsize==0);
   109191   p->bHasStat = isFts4;
   109192   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
   109193 
   109194   /* Fill in the zName and zDb fields of the vtab structure. */
   109195   zCsr = (char *)&p->azColumn[nCol];
   109196   p->zName = zCsr;
   109197   memcpy(zCsr, argv[2], nName);
   109198   zCsr += nName;
   109199   p->zDb = zCsr;
   109200   memcpy(zCsr, argv[1], nDb);
   109201   zCsr += nDb;
   109202 
   109203   /* Fill in the azColumn array */
   109204   for(iCol=0; iCol<nCol; iCol++){
   109205     char *z;
   109206     int n;
   109207     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
   109208     memcpy(zCsr, z, n);
   109209     zCsr[n] = '\0';
   109210     sqlite3Fts3Dequote(zCsr);
   109211     p->azColumn[iCol] = zCsr;
   109212     zCsr += n+1;
   109213     assert( zCsr <= &((char *)p)[nByte] );
   109214   }
   109215 
   109216   /* If this is an xCreate call, create the underlying tables in the
   109217   ** database. TODO: For xConnect(), it could verify that said tables exist.
   109218   */
   109219   if( isCreate ){
   109220     rc = fts3CreateTables(p);
   109221   }
   109222 
   109223   /* Figure out the page-size for the database. This is required in order to
   109224   ** estimate the cost of loading large doclists from the database (see
   109225   ** function sqlite3Fts3SegReaderCost() for details).
   109226   */
   109227   fts3DatabasePageSize(&rc, p);
   109228 
   109229   /* Declare the table schema to SQLite. */
   109230   fts3DeclareVtab(&rc, p);
   109231 
   109232 fts3_init_out:
   109233 
   109234   sqlite3_free((void *)aCol);
   109235   if( rc!=SQLITE_OK ){
   109236     if( p ){
   109237       fts3DisconnectMethod((sqlite3_vtab *)p);
   109238     }else if( pTokenizer ){
   109239       pTokenizer->pModule->xDestroy(pTokenizer);
   109240     }
   109241   }else{
   109242     *ppVTab = &p->base;
   109243   }
   109244   return rc;
   109245 }
   109246 
   109247 /*
   109248 ** The xConnect() and xCreate() methods for the virtual table. All the
   109249 ** work is done in function fts3InitVtab().
   109250 */
   109251 static int fts3ConnectMethod(
   109252   sqlite3 *db,                    /* Database connection */
   109253   void *pAux,                     /* Pointer to tokenizer hash table */
   109254   int argc,                       /* Number of elements in argv array */
   109255   const char * const *argv,       /* xCreate/xConnect argument array */
   109256   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   109257   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   109258 ){
   109259   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
   109260 }
   109261 static int fts3CreateMethod(
   109262   sqlite3 *db,                    /* Database connection */
   109263   void *pAux,                     /* Pointer to tokenizer hash table */
   109264   int argc,                       /* Number of elements in argv array */
   109265   const char * const *argv,       /* xCreate/xConnect argument array */
   109266   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
   109267   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
   109268 ){
   109269   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
   109270 }
   109271 
   109272 /*
   109273 ** Implementation of the xBestIndex method for FTS3 tables. There
   109274 ** are three possible strategies, in order of preference:
   109275 **
   109276 **   1. Direct lookup by rowid or docid.
   109277 **   2. Full-text search using a MATCH operator on a non-docid column.
   109278 **   3. Linear scan of %_content table.
   109279 */
   109280 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   109281   Fts3Table *p = (Fts3Table *)pVTab;
   109282   int i;                          /* Iterator variable */
   109283   int iCons = -1;                 /* Index of constraint to use */
   109284 
   109285   /* By default use a full table scan. This is an expensive option,
   109286   ** so search through the constraints to see if a more efficient
   109287   ** strategy is possible.
   109288   */
   109289   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
   109290   pInfo->estimatedCost = 500000;
   109291   for(i=0; i<pInfo->nConstraint; i++){
   109292     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
   109293     if( pCons->usable==0 ) continue;
   109294 
   109295     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
   109296     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
   109297      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
   109298     ){
   109299       pInfo->idxNum = FTS3_DOCID_SEARCH;
   109300       pInfo->estimatedCost = 1.0;
   109301       iCons = i;
   109302     }
   109303 
   109304     /* A MATCH constraint. Use a full-text search.
   109305     **
   109306     ** If there is more than one MATCH constraint available, use the first
   109307     ** one encountered. If there is both a MATCH constraint and a direct
   109308     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
   109309     ** though the rowid/docid lookup is faster than a MATCH query, selecting
   109310     ** it would lead to an "unable to use function MATCH in the requested
   109311     ** context" error.
   109312     */
   109313     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
   109314      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
   109315     ){
   109316       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
   109317       pInfo->estimatedCost = 2.0;
   109318       iCons = i;
   109319       break;
   109320     }
   109321   }
   109322 
   109323   if( iCons>=0 ){
   109324     pInfo->aConstraintUsage[iCons].argvIndex = 1;
   109325     pInfo->aConstraintUsage[iCons].omit = 1;
   109326   }
   109327   return SQLITE_OK;
   109328 }
   109329 
   109330 /*
   109331 ** Implementation of xOpen method.
   109332 */
   109333 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   109334   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
   109335 
   109336   UNUSED_PARAMETER(pVTab);
   109337 
   109338   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
   109339   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   109340   ** if the allocation fails, return SQLITE_NOMEM.
   109341   */
   109342   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
   109343   if( !pCsr ){
   109344     return SQLITE_NOMEM;
   109345   }
   109346   memset(pCsr, 0, sizeof(Fts3Cursor));
   109347   return SQLITE_OK;
   109348 }
   109349 
   109350 /*
   109351 ** Close the cursor.  For additional information see the documentation
   109352 ** on the xClose method of the virtual table interface.
   109353 */
   109354 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
   109355   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   109356   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
   109357   sqlite3_finalize(pCsr->pStmt);
   109358   sqlite3Fts3ExprFree(pCsr->pExpr);
   109359   sqlite3Fts3FreeDeferredTokens(pCsr);
   109360   sqlite3_free(pCsr->aDoclist);
   109361   sqlite3_free(pCsr->aMatchinfo);
   109362   sqlite3_free(pCsr);
   109363   return SQLITE_OK;
   109364 }
   109365 
   109366 /*
   109367 ** Position the pCsr->pStmt statement so that it is on the row
   109368 ** of the %_content table that contains the last match.  Return
   109369 ** SQLITE_OK on success.
   109370 */
   109371 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   109372   if( pCsr->isRequireSeek ){
   109373     pCsr->isRequireSeek = 0;
   109374     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
   109375     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
   109376       return SQLITE_OK;
   109377     }else{
   109378       int rc = sqlite3_reset(pCsr->pStmt);
   109379       if( rc==SQLITE_OK ){
   109380         /* If no row was found and no error has occured, then the %_content
   109381         ** table is missing a row that is present in the full-text index.
   109382         ** The data structures are corrupt.
   109383         */
   109384         rc = SQLITE_CORRUPT;
   109385       }
   109386       pCsr->isEof = 1;
   109387       if( pContext ){
   109388         sqlite3_result_error_code(pContext, rc);
   109389       }
   109390       return rc;
   109391     }
   109392   }else{
   109393     return SQLITE_OK;
   109394   }
   109395 }
   109396 
   109397 /*
   109398 ** This function is used to process a single interior node when searching
   109399 ** a b-tree for a term or term prefix. The node data is passed to this
   109400 ** function via the zNode/nNode parameters. The term to search for is
   109401 ** passed in zTerm/nTerm.
   109402 **
   109403 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
   109404 ** of the child node that heads the sub-tree that may contain the term.
   109405 **
   109406 ** If piLast is not NULL, then *piLast is set to the right-most child node
   109407 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
   109408 ** a prefix.
   109409 **
   109410 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   109411 */
   109412 static int fts3ScanInteriorNode(
   109413   const char *zTerm,              /* Term to select leaves for */
   109414   int nTerm,                      /* Size of term zTerm in bytes */
   109415   const char *zNode,              /* Buffer containing segment interior node */
   109416   int nNode,                      /* Size of buffer at zNode */
   109417   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
   109418   sqlite3_int64 *piLast           /* OUT: Selected child node */
   109419 ){
   109420   int rc = SQLITE_OK;             /* Return code */
   109421   const char *zCsr = zNode;       /* Cursor to iterate through node */
   109422   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
   109423   char *zBuffer = 0;              /* Buffer to load terms into */
   109424   int nAlloc = 0;                 /* Size of allocated buffer */
   109425   int isFirstTerm = 1;            /* True when processing first term on page */
   109426   sqlite3_int64 iChild;           /* Block id of child node to descend to */
   109427 
   109428   /* Skip over the 'height' varint that occurs at the start of every
   109429   ** interior node. Then load the blockid of the left-child of the b-tree
   109430   ** node into variable iChild.
   109431   **
   109432   ** Even if the data structure on disk is corrupted, this (reading two
   109433   ** varints from the buffer) does not risk an overread. If zNode is a
   109434   ** root node, then the buffer comes from a SELECT statement. SQLite does
   109435   ** not make this guarantee explicitly, but in practice there are always
   109436   ** either more than 20 bytes of allocated space following the nNode bytes of
   109437   ** contents, or two zero bytes. Or, if the node is read from the %_segments
   109438   ** table, then there are always 20 bytes of zeroed padding following the
   109439   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
   109440   */
   109441   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   109442   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
   109443   if( zCsr>zEnd ){
   109444     return SQLITE_CORRUPT;
   109445   }
   109446 
   109447   while( zCsr<zEnd && (piFirst || piLast) ){
   109448     int cmp;                      /* memcmp() result */
   109449     int nSuffix;                  /* Size of term suffix */
   109450     int nPrefix = 0;              /* Size of term prefix */
   109451     int nBuffer;                  /* Total term size */
   109452 
   109453     /* Load the next term on the node into zBuffer. Use realloc() to expand
   109454     ** the size of zBuffer if required.  */
   109455     if( !isFirstTerm ){
   109456       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
   109457     }
   109458     isFirstTerm = 0;
   109459     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
   109460 
   109461     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
   109462       rc = SQLITE_CORRUPT;
   109463       goto finish_scan;
   109464     }
   109465     if( nPrefix+nSuffix>nAlloc ){
   109466       char *zNew;
   109467       nAlloc = (nPrefix+nSuffix) * 2;
   109468       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
   109469       if( !zNew ){
   109470         rc = SQLITE_NOMEM;
   109471         goto finish_scan;
   109472       }
   109473       zBuffer = zNew;
   109474     }
   109475     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
   109476     nBuffer = nPrefix + nSuffix;
   109477     zCsr += nSuffix;
   109478 
   109479     /* Compare the term we are searching for with the term just loaded from
   109480     ** the interior node. If the specified term is greater than or equal
   109481     ** to the term from the interior node, then all terms on the sub-tree
   109482     ** headed by node iChild are smaller than zTerm. No need to search
   109483     ** iChild.
   109484     **
   109485     ** If the interior node term is larger than the specified term, then
   109486     ** the tree headed by iChild may contain the specified term.
   109487     */
   109488     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
   109489     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
   109490       *piFirst = iChild;
   109491       piFirst = 0;
   109492     }
   109493 
   109494     if( piLast && cmp<0 ){
   109495       *piLast = iChild;
   109496       piLast = 0;
   109497     }
   109498 
   109499     iChild++;
   109500   };
   109501 
   109502   if( piFirst ) *piFirst = iChild;
   109503   if( piLast ) *piLast = iChild;
   109504 
   109505  finish_scan:
   109506   sqlite3_free(zBuffer);
   109507   return rc;
   109508 }
   109509 
   109510 
   109511 /*
   109512 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
   109513 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
   109514 ** contains a term. This function searches the sub-tree headed by the zNode
   109515 ** node for the range of leaf nodes that may contain the specified term
   109516 ** or terms for which the specified term is a prefix.
   109517 **
   109518 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
   109519 ** left-most leaf node in the tree that may contain the specified term.
   109520 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
   109521 ** right-most leaf node that may contain a term for which the specified
   109522 ** term is a prefix.
   109523 **
   109524 ** It is possible that the range of returned leaf nodes does not contain
   109525 ** the specified term or any terms for which it is a prefix. However, if the
   109526 ** segment does contain any such terms, they are stored within the identified
   109527 ** range. Because this function only inspects interior segment nodes (and
   109528 ** never loads leaf nodes into memory), it is not possible to be sure.
   109529 **
   109530 ** If an error occurs, an error code other than SQLITE_OK is returned.
   109531 */
   109532 static int fts3SelectLeaf(
   109533   Fts3Table *p,                   /* Virtual table handle */
   109534   const char *zTerm,              /* Term to select leaves for */
   109535   int nTerm,                      /* Size of term zTerm in bytes */
   109536   const char *zNode,              /* Buffer containing segment interior node */
   109537   int nNode,                      /* Size of buffer at zNode */
   109538   sqlite3_int64 *piLeaf,          /* Selected leaf node */
   109539   sqlite3_int64 *piLeaf2          /* Selected leaf node */
   109540 ){
   109541   int rc;                         /* Return code */
   109542   int iHeight;                    /* Height of this node in tree */
   109543 
   109544   assert( piLeaf || piLeaf2 );
   109545 
   109546   sqlite3Fts3GetVarint32(zNode, &iHeight);
   109547   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
   109548   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
   109549 
   109550   if( rc==SQLITE_OK && iHeight>1 ){
   109551     char *zBlob = 0;              /* Blob read from %_segments table */
   109552     int nBlob;                    /* Size of zBlob in bytes */
   109553 
   109554     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
   109555       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
   109556       if( rc==SQLITE_OK ){
   109557         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
   109558       }
   109559       sqlite3_free(zBlob);
   109560       piLeaf = 0;
   109561       zBlob = 0;
   109562     }
   109563 
   109564     if( rc==SQLITE_OK ){
   109565       rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
   109566     }
   109567     if( rc==SQLITE_OK ){
   109568       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
   109569     }
   109570     sqlite3_free(zBlob);
   109571   }
   109572 
   109573   return rc;
   109574 }
   109575 
   109576 /*
   109577 ** This function is used to create delta-encoded serialized lists of FTS3
   109578 ** varints. Each call to this function appends a single varint to a list.
   109579 */
   109580 static void fts3PutDeltaVarint(
   109581   char **pp,                      /* IN/OUT: Output pointer */
   109582   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   109583   sqlite3_int64 iVal              /* Write this value to the list */
   109584 ){
   109585   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   109586   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   109587   *piPrev = iVal;
   109588 }
   109589 
   109590 /*
   109591 ** When this function is called, *ppPoslist is assumed to point to the
   109592 ** start of a position-list. After it returns, *ppPoslist points to the
   109593 ** first byte after the position-list.
   109594 **
   109595 ** A position list is list of positions (delta encoded) and columns for
   109596 ** a single document record of a doclist.  So, in other words, this
   109597 ** routine advances *ppPoslist so that it points to the next docid in
   109598 ** the doclist, or to the first byte past the end of the doclist.
   109599 **
   109600 ** If pp is not NULL, then the contents of the position list are copied
   109601 ** to *pp. *pp is set to point to the first byte past the last byte copied
   109602 ** before this function returns.
   109603 */
   109604 static void fts3PoslistCopy(char **pp, char **ppPoslist){
   109605   char *pEnd = *ppPoslist;
   109606   char c = 0;
   109607 
   109608   /* The end of a position list is marked by a zero encoded as an FTS3
   109609   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   109610   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   109611   ** of some other, multi-byte, value.
   109612   **
   109613   ** The following while-loop moves pEnd to point to the first byte that is not
   109614   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   109615   ** pEnd once more so that it points to the byte immediately following the
   109616   ** last byte in the position-list.
   109617   */
   109618   while( *pEnd | c ){
   109619     c = *pEnd++ & 0x80;
   109620     testcase( c!=0 && (*pEnd)==0 );
   109621   }
   109622   pEnd++;  /* Advance past the POS_END terminator byte */
   109623 
   109624   if( pp ){
   109625     int n = (int)(pEnd - *ppPoslist);
   109626     char *p = *pp;
   109627     memcpy(p, *ppPoslist, n);
   109628     p += n;
   109629     *pp = p;
   109630   }
   109631   *ppPoslist = pEnd;
   109632 }
   109633 
   109634 /*
   109635 ** When this function is called, *ppPoslist is assumed to point to the
   109636 ** start of a column-list. After it returns, *ppPoslist points to the
   109637 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
   109638 **
   109639 ** A column-list is list of delta-encoded positions for a single column
   109640 ** within a single document within a doclist.
   109641 **
   109642 ** The column-list is terminated either by a POS_COLUMN varint (1) or
   109643 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
   109644 ** the POS_COLUMN or POS_END that terminates the column-list.
   109645 **
   109646 ** If pp is not NULL, then the contents of the column-list are copied
   109647 ** to *pp. *pp is set to point to the first byte past the last byte copied
   109648 ** before this function returns.  The POS_COLUMN or POS_END terminator
   109649 ** is not copied into *pp.
   109650 */
   109651 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
   109652   char *pEnd = *ppPoslist;
   109653   char c = 0;
   109654 
   109655   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
   109656   ** not part of a multi-byte varint.
   109657   */
   109658   while( 0xFE & (*pEnd | c) ){
   109659     c = *pEnd++ & 0x80;
   109660     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
   109661   }
   109662   if( pp ){
   109663     int n = (int)(pEnd - *ppPoslist);
   109664     char *p = *pp;
   109665     memcpy(p, *ppPoslist, n);
   109666     p += n;
   109667     *pp = p;
   109668   }
   109669   *ppPoslist = pEnd;
   109670 }
   109671 
   109672 /*
   109673 ** Value used to signify the end of an position-list. This is safe because
   109674 ** it is not possible to have a document with 2^31 terms.
   109675 */
   109676 #define POSITION_LIST_END 0x7fffffff
   109677 
   109678 /*
   109679 ** This function is used to help parse position-lists. When this function is
   109680 ** called, *pp may point to the start of the next varint in the position-list
   109681 ** being parsed, or it may point to 1 byte past the end of the position-list
   109682 ** (in which case **pp will be a terminator bytes POS_END (0) or
   109683 ** (1)).
   109684 **
   109685 ** If *pp points past the end of the current position-list, set *pi to
   109686 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
   109687 ** increment the current value of *pi by the value read, and set *pp to
   109688 ** point to the next value before returning.
   109689 **
   109690 ** Before calling this routine *pi must be initialized to the value of
   109691 ** the previous position, or zero if we are reading the first position
   109692 ** in the position-list.  Because positions are delta-encoded, the value
   109693 ** of the previous position is needed in order to compute the value of
   109694 ** the next position.
   109695 */
   109696 static void fts3ReadNextPos(
   109697   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
   109698   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
   109699 ){
   109700   if( (**pp)&0xFE ){
   109701     fts3GetDeltaVarint(pp, pi);
   109702     *pi -= 2;
   109703   }else{
   109704     *pi = POSITION_LIST_END;
   109705   }
   109706 }
   109707 
   109708 /*
   109709 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
   109710 ** the value of iCol encoded as a varint to *pp.   This will start a new
   109711 ** column list.
   109712 **
   109713 ** Set *pp to point to the byte just after the last byte written before
   109714 ** returning (do not modify it if iCol==0). Return the total number of bytes
   109715 ** written (0 if iCol==0).
   109716 */
   109717 static int fts3PutColNumber(char **pp, int iCol){
   109718   int n = 0;                      /* Number of bytes written */
   109719   if( iCol ){
   109720     char *p = *pp;                /* Output pointer */
   109721     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
   109722     *p = 0x01;
   109723     *pp = &p[n];
   109724   }
   109725   return n;
   109726 }
   109727 
   109728 /*
   109729 ** Compute the union of two position lists.  The output written
   109730 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
   109731 ** order and with any duplicates removed.  All pointers are
   109732 ** updated appropriately.   The caller is responsible for insuring
   109733 ** that there is enough space in *pp to hold the complete output.
   109734 */
   109735 static void fts3PoslistMerge(
   109736   char **pp,                      /* Output buffer */
   109737   char **pp1,                     /* Left input list */
   109738   char **pp2                      /* Right input list */
   109739 ){
   109740   char *p = *pp;
   109741   char *p1 = *pp1;
   109742   char *p2 = *pp2;
   109743 
   109744   while( *p1 || *p2 ){
   109745     int iCol1;         /* The current column index in pp1 */
   109746     int iCol2;         /* The current column index in pp2 */
   109747 
   109748     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
   109749     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
   109750     else iCol1 = 0;
   109751 
   109752     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
   109753     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
   109754     else iCol2 = 0;
   109755 
   109756     if( iCol1==iCol2 ){
   109757       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
   109758       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
   109759       sqlite3_int64 iPrev = 0;
   109760       int n = fts3PutColNumber(&p, iCol1);
   109761       p1 += n;
   109762       p2 += n;
   109763 
   109764       /* At this point, both p1 and p2 point to the start of column-lists
   109765       ** for the same column (the column with index iCol1 and iCol2).
   109766       ** A column-list is a list of non-negative delta-encoded varints, each
   109767       ** incremented by 2 before being stored. Each list is terminated by a
   109768       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
   109769       ** and writes the results to buffer p. p is left pointing to the byte
   109770       ** after the list written. No terminator (POS_END or POS_COLUMN) is
   109771       ** written to the output.
   109772       */
   109773       fts3GetDeltaVarint(&p1, &i1);
   109774       fts3GetDeltaVarint(&p2, &i2);
   109775       do {
   109776         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
   109777         iPrev -= 2;
   109778         if( i1==i2 ){
   109779           fts3ReadNextPos(&p1, &i1);
   109780           fts3ReadNextPos(&p2, &i2);
   109781         }else if( i1<i2 ){
   109782           fts3ReadNextPos(&p1, &i1);
   109783         }else{
   109784           fts3ReadNextPos(&p2, &i2);
   109785         }
   109786       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
   109787     }else if( iCol1<iCol2 ){
   109788       p1 += fts3PutColNumber(&p, iCol1);
   109789       fts3ColumnlistCopy(&p, &p1);
   109790     }else{
   109791       p2 += fts3PutColNumber(&p, iCol2);
   109792       fts3ColumnlistCopy(&p, &p2);
   109793     }
   109794   }
   109795 
   109796   *p++ = POS_END;
   109797   *pp = p;
   109798   *pp1 = p1 + 1;
   109799   *pp2 = p2 + 1;
   109800 }
   109801 
   109802 /*
   109803 ** nToken==1 searches for adjacent positions.
   109804 **
   109805 ** This function is used to merge two position lists into one. When it is
   109806 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
   109807 ** the part of a doclist that follows each document id. For example, if a row
   109808 ** contains:
   109809 **
   109810 **     'a b c'|'x y z'|'a b b a'
   109811 **
   109812 ** Then the position list for this row for token 'b' would consist of:
   109813 **
   109814 **     0x02 0x01 0x02 0x03 0x03 0x00
   109815 **
   109816 ** When this function returns, both *pp1 and *pp2 are left pointing to the
   109817 ** byte following the 0x00 terminator of their respective position lists.
   109818 **
   109819 ** If isSaveLeft is 0, an entry is added to the output position list for
   109820 ** each position in *pp2 for which there exists one or more positions in
   109821 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
   109822 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
   109823 ** slots before it.
   109824 */
   109825 static int fts3PoslistPhraseMerge(
   109826   char **pp,                      /* IN/OUT: Preallocated output buffer */
   109827   int nToken,                     /* Maximum difference in token positions */
   109828   int isSaveLeft,                 /* Save the left position */
   109829   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
   109830   char **pp1,                     /* IN/OUT: Left input list */
   109831   char **pp2                      /* IN/OUT: Right input list */
   109832 ){
   109833   char *p = (pp ? *pp : 0);
   109834   char *p1 = *pp1;
   109835   char *p2 = *pp2;
   109836   int iCol1 = 0;
   109837   int iCol2 = 0;
   109838 
   109839   /* Never set both isSaveLeft and isExact for the same invocation. */
   109840   assert( isSaveLeft==0 || isExact==0 );
   109841 
   109842   assert( *p1!=0 && *p2!=0 );
   109843   if( *p1==POS_COLUMN ){
   109844     p1++;
   109845     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   109846   }
   109847   if( *p2==POS_COLUMN ){
   109848     p2++;
   109849     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   109850   }
   109851 
   109852   while( 1 ){
   109853     if( iCol1==iCol2 ){
   109854       char *pSave = p;
   109855       sqlite3_int64 iPrev = 0;
   109856       sqlite3_int64 iPos1 = 0;
   109857       sqlite3_int64 iPos2 = 0;
   109858 
   109859       if( pp && iCol1 ){
   109860         *p++ = POS_COLUMN;
   109861         p += sqlite3Fts3PutVarint(p, iCol1);
   109862       }
   109863 
   109864       assert( *p1!=POS_END && *p1!=POS_COLUMN );
   109865       assert( *p2!=POS_END && *p2!=POS_COLUMN );
   109866       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   109867       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   109868 
   109869       while( 1 ){
   109870         if( iPos2==iPos1+nToken
   109871          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
   109872         ){
   109873           sqlite3_int64 iSave;
   109874           if( !pp ){
   109875             fts3PoslistCopy(0, &p2);
   109876             fts3PoslistCopy(0, &p1);
   109877             *pp1 = p1;
   109878             *pp2 = p2;
   109879             return 1;
   109880           }
   109881           iSave = isSaveLeft ? iPos1 : iPos2;
   109882           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
   109883           pSave = 0;
   109884         }
   109885         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
   109886           if( (*p2&0xFE)==0 ) break;
   109887           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
   109888         }else{
   109889           if( (*p1&0xFE)==0 ) break;
   109890           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
   109891         }
   109892       }
   109893 
   109894       if( pSave ){
   109895         assert( pp && p );
   109896         p = pSave;
   109897       }
   109898 
   109899       fts3ColumnlistCopy(0, &p1);
   109900       fts3ColumnlistCopy(0, &p2);
   109901       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
   109902       if( 0==*p1 || 0==*p2 ) break;
   109903 
   109904       p1++;
   109905       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   109906       p2++;
   109907       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   109908     }
   109909 
   109910     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
   109911     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
   109912     ** end of the position list, or the 0x01 that precedes the next
   109913     ** column-number in the position list.
   109914     */
   109915     else if( iCol1<iCol2 ){
   109916       fts3ColumnlistCopy(0, &p1);
   109917       if( 0==*p1 ) break;
   109918       p1++;
   109919       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
   109920     }else{
   109921       fts3ColumnlistCopy(0, &p2);
   109922       if( 0==*p2 ) break;
   109923       p2++;
   109924       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
   109925     }
   109926   }
   109927 
   109928   fts3PoslistCopy(0, &p2);
   109929   fts3PoslistCopy(0, &p1);
   109930   *pp1 = p1;
   109931   *pp2 = p2;
   109932   if( !pp || *pp==p ){
   109933     return 0;
   109934   }
   109935   *p++ = 0x00;
   109936   *pp = p;
   109937   return 1;
   109938 }
   109939 
   109940 /*
   109941 ** Merge two position-lists as required by the NEAR operator.
   109942 */
   109943 static int fts3PoslistNearMerge(
   109944   char **pp,                      /* Output buffer */
   109945   char *aTmp,                     /* Temporary buffer space */
   109946   int nRight,                     /* Maximum difference in token positions */
   109947   int nLeft,                      /* Maximum difference in token positions */
   109948   char **pp1,                     /* IN/OUT: Left input list */
   109949   char **pp2                      /* IN/OUT: Right input list */
   109950 ){
   109951   char *p1 = *pp1;
   109952   char *p2 = *pp2;
   109953 
   109954   if( !pp ){
   109955     if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
   109956     *pp1 = p1;
   109957     *pp2 = p2;
   109958     return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
   109959   }else{
   109960     char *pTmp1 = aTmp;
   109961     char *pTmp2;
   109962     char *aTmp2;
   109963     int res = 1;
   109964 
   109965     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
   109966     aTmp2 = pTmp2 = pTmp1;
   109967     *pp1 = p1;
   109968     *pp2 = p2;
   109969     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
   109970     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
   109971       fts3PoslistMerge(pp, &aTmp, &aTmp2);
   109972     }else if( pTmp1!=aTmp ){
   109973       fts3PoslistCopy(pp, &aTmp);
   109974     }else if( pTmp2!=aTmp2 ){
   109975       fts3PoslistCopy(pp, &aTmp2);
   109976     }else{
   109977       res = 0;
   109978     }
   109979 
   109980     return res;
   109981   }
   109982 }
   109983 
   109984 /*
   109985 ** Values that may be used as the first parameter to fts3DoclistMerge().
   109986 */
   109987 #define MERGE_NOT        2        /* D + D -> D */
   109988 #define MERGE_AND        3        /* D + D -> D */
   109989 #define MERGE_OR         4        /* D + D -> D */
   109990 #define MERGE_POS_OR     5        /* P + P -> P */
   109991 #define MERGE_PHRASE     6        /* P + P -> D */
   109992 #define MERGE_POS_PHRASE 7        /* P + P -> P */
   109993 #define MERGE_NEAR       8        /* P + P -> D */
   109994 #define MERGE_POS_NEAR   9        /* P + P -> P */
   109995 
   109996 /*
   109997 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
   109998 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
   109999 ** which is guaranteed to be large enough to hold the results. The number
   110000 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
   110001 **
   110002 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
   110003 ** occurs while allocating a temporary buffer as part of the merge operation,
   110004 ** SQLITE_NOMEM is returned.
   110005 */
   110006 static int fts3DoclistMerge(
   110007   int mergetype,                  /* One of the MERGE_XXX constants */
   110008   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
   110009   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
   110010   char *aBuffer,                  /* Pre-allocated output buffer */
   110011   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
   110012   char *a1,                       /* Buffer containing first doclist */
   110013   int n1,                         /* Size of buffer a1 */
   110014   char *a2,                       /* Buffer containing second doclist */
   110015   int n2,                         /* Size of buffer a2 */
   110016   int *pnDoc                      /* OUT: Number of docids in output */
   110017 ){
   110018   sqlite3_int64 i1 = 0;
   110019   sqlite3_int64 i2 = 0;
   110020   sqlite3_int64 iPrev = 0;
   110021 
   110022   char *p = aBuffer;
   110023   char *p1 = a1;
   110024   char *p2 = a2;
   110025   char *pEnd1 = &a1[n1];
   110026   char *pEnd2 = &a2[n2];
   110027   int nDoc = 0;
   110028 
   110029   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
   110030        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
   110031        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
   110032        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
   110033   );
   110034 
   110035   if( !aBuffer ){
   110036     *pnBuffer = 0;
   110037     return SQLITE_NOMEM;
   110038   }
   110039 
   110040   /* Read the first docid from each doclist */
   110041   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110042   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110043 
   110044   switch( mergetype ){
   110045     case MERGE_OR:
   110046     case MERGE_POS_OR:
   110047       while( p1 || p2 ){
   110048         if( p2 && p1 && i1==i2 ){
   110049           fts3PutDeltaVarint(&p, &iPrev, i1);
   110050           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
   110051           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110052           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110053         }else if( !p2 || (p1 && i1<i2) ){
   110054           fts3PutDeltaVarint(&p, &iPrev, i1);
   110055           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
   110056           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110057         }else{
   110058           fts3PutDeltaVarint(&p, &iPrev, i2);
   110059           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
   110060           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110061         }
   110062       }
   110063       break;
   110064 
   110065     case MERGE_AND:
   110066       while( p1 && p2 ){
   110067         if( i1==i2 ){
   110068           fts3PutDeltaVarint(&p, &iPrev, i1);
   110069           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110070           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110071           nDoc++;
   110072         }else if( i1<i2 ){
   110073           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110074         }else{
   110075           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110076         }
   110077       }
   110078       break;
   110079 
   110080     case MERGE_NOT:
   110081       while( p1 ){
   110082         if( p2 && i1==i2 ){
   110083           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110084           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110085         }else if( !p2 || i1<i2 ){
   110086           fts3PutDeltaVarint(&p, &iPrev, i1);
   110087           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110088         }else{
   110089           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110090         }
   110091       }
   110092       break;
   110093 
   110094     case MERGE_POS_PHRASE:
   110095     case MERGE_PHRASE: {
   110096       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
   110097       while( p1 && p2 ){
   110098         if( i1==i2 ){
   110099           char *pSave = p;
   110100           sqlite3_int64 iPrevSave = iPrev;
   110101           fts3PutDeltaVarint(&p, &iPrev, i1);
   110102           if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
   110103             p = pSave;
   110104             iPrev = iPrevSave;
   110105           }else{
   110106             nDoc++;
   110107           }
   110108           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110109           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110110         }else if( i1<i2 ){
   110111           fts3PoslistCopy(0, &p1);
   110112           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110113         }else{
   110114           fts3PoslistCopy(0, &p2);
   110115           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110116         }
   110117       }
   110118       break;
   110119     }
   110120 
   110121     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
   110122       char *aTmp = 0;
   110123       char **ppPos = 0;
   110124 
   110125       if( mergetype==MERGE_POS_NEAR ){
   110126         ppPos = &p;
   110127         aTmp = sqlite3_malloc(2*(n1+n2+1));
   110128         if( !aTmp ){
   110129           return SQLITE_NOMEM;
   110130         }
   110131       }
   110132 
   110133       while( p1 && p2 ){
   110134         if( i1==i2 ){
   110135           char *pSave = p;
   110136           sqlite3_int64 iPrevSave = iPrev;
   110137           fts3PutDeltaVarint(&p, &iPrev, i1);
   110138 
   110139           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
   110140             iPrev = iPrevSave;
   110141             p = pSave;
   110142           }
   110143 
   110144           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110145           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110146         }else if( i1<i2 ){
   110147           fts3PoslistCopy(0, &p1);
   110148           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
   110149         }else{
   110150           fts3PoslistCopy(0, &p2);
   110151           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
   110152         }
   110153       }
   110154       sqlite3_free(aTmp);
   110155       break;
   110156     }
   110157   }
   110158 
   110159   if( pnDoc ) *pnDoc = nDoc;
   110160   *pnBuffer = (int)(p-aBuffer);
   110161   return SQLITE_OK;
   110162 }
   110163 
   110164 /*
   110165 ** A pointer to an instance of this structure is used as the context
   110166 ** argument to sqlite3Fts3SegReaderIterate()
   110167 */
   110168 typedef struct TermSelect TermSelect;
   110169 struct TermSelect {
   110170   int isReqPos;
   110171   char *aaOutput[16];             /* Malloc'd output buffer */
   110172   int anOutput[16];               /* Size of output in bytes */
   110173 };
   110174 
   110175 /*
   110176 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
   110177 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
   110178 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
   110179 **
   110180 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
   110181 ** the responsibility of the caller to free any doclists left in the
   110182 ** TermSelect.aaOutput[] array.
   110183 */
   110184 static int fts3TermSelectMerge(TermSelect *pTS){
   110185   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
   110186   char *aOut = 0;
   110187   int nOut = 0;
   110188   int i;
   110189 
   110190   /* Loop through the doclists in the aaOutput[] array. Merge them all
   110191   ** into a single doclist.
   110192   */
   110193   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
   110194     if( pTS->aaOutput[i] ){
   110195       if( !aOut ){
   110196         aOut = pTS->aaOutput[i];
   110197         nOut = pTS->anOutput[i];
   110198         pTS->aaOutput[i] = 0;
   110199       }else{
   110200         int nNew = nOut + pTS->anOutput[i];
   110201         char *aNew = sqlite3_malloc(nNew);
   110202         if( !aNew ){
   110203           sqlite3_free(aOut);
   110204           return SQLITE_NOMEM;
   110205         }
   110206         fts3DoclistMerge(mergetype, 0, 0,
   110207             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
   110208         );
   110209         sqlite3_free(pTS->aaOutput[i]);
   110210         sqlite3_free(aOut);
   110211         pTS->aaOutput[i] = 0;
   110212         aOut = aNew;
   110213         nOut = nNew;
   110214       }
   110215     }
   110216   }
   110217 
   110218   pTS->aaOutput[0] = aOut;
   110219   pTS->anOutput[0] = nOut;
   110220   return SQLITE_OK;
   110221 }
   110222 
   110223 /*
   110224 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
   110225 ** querying the full-text index for a doclist associated with a term or
   110226 ** term-prefix.
   110227 */
   110228 static int fts3TermSelectCb(
   110229   Fts3Table *p,                   /* Virtual table object */
   110230   void *pContext,                 /* Pointer to TermSelect structure */
   110231   char *zTerm,
   110232   int nTerm,
   110233   char *aDoclist,
   110234   int nDoclist
   110235 ){
   110236   TermSelect *pTS = (TermSelect *)pContext;
   110237 
   110238   UNUSED_PARAMETER(p);
   110239   UNUSED_PARAMETER(zTerm);
   110240   UNUSED_PARAMETER(nTerm);
   110241 
   110242   if( pTS->aaOutput[0]==0 ){
   110243     /* If this is the first term selected, copy the doclist to the output
   110244     ** buffer using memcpy(). TODO: Add a way to transfer control of the
   110245     ** aDoclist buffer from the caller so as to avoid the memcpy().
   110246     */
   110247     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
   110248     pTS->anOutput[0] = nDoclist;
   110249     if( pTS->aaOutput[0] ){
   110250       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
   110251     }else{
   110252       return SQLITE_NOMEM;
   110253     }
   110254   }else{
   110255     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
   110256     char *aMerge = aDoclist;
   110257     int nMerge = nDoclist;
   110258     int iOut;
   110259 
   110260     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
   110261       char *aNew;
   110262       int nNew;
   110263       if( pTS->aaOutput[iOut]==0 ){
   110264         assert( iOut>0 );
   110265         pTS->aaOutput[iOut] = aMerge;
   110266         pTS->anOutput[iOut] = nMerge;
   110267         break;
   110268       }
   110269 
   110270       nNew = nMerge + pTS->anOutput[iOut];
   110271       aNew = sqlite3_malloc(nNew);
   110272       if( !aNew ){
   110273         if( aMerge!=aDoclist ){
   110274           sqlite3_free(aMerge);
   110275         }
   110276         return SQLITE_NOMEM;
   110277       }
   110278       fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew,
   110279           pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
   110280       );
   110281 
   110282       if( iOut>0 ) sqlite3_free(aMerge);
   110283       sqlite3_free(pTS->aaOutput[iOut]);
   110284       pTS->aaOutput[iOut] = 0;
   110285 
   110286       aMerge = aNew;
   110287       nMerge = nNew;
   110288       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
   110289         pTS->aaOutput[iOut] = aMerge;
   110290         pTS->anOutput[iOut] = nMerge;
   110291       }
   110292     }
   110293   }
   110294   return SQLITE_OK;
   110295 }
   110296 
   110297 static int fts3DeferredTermSelect(
   110298   Fts3DeferredToken *pToken,      /* Phrase token */
   110299   int isTermPos,                  /* True to include positions */
   110300   int *pnOut,                     /* OUT: Size of list */
   110301   char **ppOut                    /* OUT: Body of list */
   110302 ){
   110303   char *aSource;
   110304   int nSource;
   110305 
   110306   aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
   110307   if( !aSource ){
   110308     *pnOut = 0;
   110309     *ppOut = 0;
   110310   }else if( isTermPos ){
   110311     *ppOut = sqlite3_malloc(nSource);
   110312     if( !*ppOut ) return SQLITE_NOMEM;
   110313     memcpy(*ppOut, aSource, nSource);
   110314     *pnOut = nSource;
   110315   }else{
   110316     sqlite3_int64 docid;
   110317     *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
   110318     *ppOut = sqlite3_malloc(*pnOut);
   110319     if( !*ppOut ) return SQLITE_NOMEM;
   110320     sqlite3Fts3PutVarint(*ppOut, docid);
   110321   }
   110322 
   110323   return SQLITE_OK;
   110324 }
   110325 
   110326 /*
   110327 ** An Fts3SegReaderArray is used to store an array of Fts3SegReader objects.
   110328 ** Elements are added to the array using fts3SegReaderArrayAdd().
   110329 */
   110330 struct Fts3SegReaderArray {
   110331   int nSegment;                   /* Number of valid entries in apSegment[] */
   110332   int nAlloc;                     /* Allocated size of apSegment[] */
   110333   int nCost;                      /* The cost of executing SegReaderIterate() */
   110334   Fts3SegReader *apSegment[1];    /* Array of seg-reader objects */
   110335 };
   110336 
   110337 
   110338 /*
   110339 ** Free an Fts3SegReaderArray object. Also free all seg-readers in the
   110340 ** array (using sqlite3Fts3SegReaderFree()).
   110341 */
   110342 static void fts3SegReaderArrayFree(Fts3SegReaderArray *pArray){
   110343   if( pArray ){
   110344     int i;
   110345     for(i=0; i<pArray->nSegment; i++){
   110346       sqlite3Fts3SegReaderFree(pArray->apSegment[i]);
   110347     }
   110348     sqlite3_free(pArray);
   110349   }
   110350 }
   110351 
   110352 static int fts3SegReaderArrayAdd(
   110353   Fts3SegReaderArray **ppArray,
   110354   Fts3SegReader *pNew
   110355 ){
   110356   Fts3SegReaderArray *pArray = *ppArray;
   110357 
   110358   if( !pArray || pArray->nAlloc==pArray->nSegment ){
   110359     int nNew = (pArray ? pArray->nAlloc+16 : 16);
   110360     pArray = (Fts3SegReaderArray *)sqlite3_realloc(pArray,
   110361         sizeof(Fts3SegReaderArray) + (nNew-1) * sizeof(Fts3SegReader*)
   110362     );
   110363     if( !pArray ){
   110364       sqlite3Fts3SegReaderFree(pNew);
   110365       return SQLITE_NOMEM;
   110366     }
   110367     if( nNew==16 ){
   110368       pArray->nSegment = 0;
   110369       pArray->nCost = 0;
   110370     }
   110371     pArray->nAlloc = nNew;
   110372     *ppArray = pArray;
   110373   }
   110374 
   110375   pArray->apSegment[pArray->nSegment++] = pNew;
   110376   return SQLITE_OK;
   110377 }
   110378 
   110379 static int fts3TermSegReaderArray(
   110380   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   110381   const char *zTerm,              /* Term to query for */
   110382   int nTerm,                      /* Size of zTerm in bytes */
   110383   int isPrefix,                   /* True for a prefix search */
   110384   Fts3SegReaderArray **ppArray    /* OUT: Allocated seg-reader array */
   110385 ){
   110386   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   110387   int rc;                         /* Return code */
   110388   Fts3SegReaderArray *pArray = 0; /* Array object to build */
   110389   Fts3SegReader *pReader = 0;     /* Seg-reader to add to pArray */
   110390   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
   110391   int iAge = 0;                   /* Used to assign ages to segments */
   110392 
   110393   /* Allocate a seg-reader to scan the pending terms, if any. */
   110394   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pReader);
   110395   if( rc==SQLITE_OK && pReader ) {
   110396     rc = fts3SegReaderArrayAdd(&pArray, pReader);
   110397   }
   110398 
   110399   /* Loop through the entire %_segdir table. For each segment, create a
   110400   ** Fts3SegReader to iterate through the subset of the segment leaves
   110401   ** that may contain a term that matches zTerm/nTerm. For non-prefix
   110402   ** searches, this is always a single leaf. For prefix searches, this
   110403   ** may be a contiguous block of leaves.
   110404   */
   110405   if( rc==SQLITE_OK ){
   110406     rc = sqlite3Fts3AllSegdirs(p, &pStmt);
   110407   }
   110408   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
   110409     Fts3SegReader *pNew = 0;
   110410     int nRoot = sqlite3_column_bytes(pStmt, 4);
   110411     char const *zRoot = sqlite3_column_blob(pStmt, 4);
   110412     if( sqlite3_column_int64(pStmt, 1)==0 ){
   110413       /* The entire segment is stored on the root node (which must be a
   110414       ** leaf). Do not bother inspecting any data in this case, just
   110415       ** create a Fts3SegReader to scan the single leaf.
   110416       */
   110417       rc = sqlite3Fts3SegReaderNew(iAge, 0, 0, 0, zRoot, nRoot, &pNew);
   110418     }else{
   110419       sqlite3_int64 i1;           /* First leaf that may contain zTerm */
   110420       sqlite3_int64 i2;           /* Final leaf that may contain zTerm */
   110421       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1, (isPrefix?&i2:0));
   110422       if( isPrefix==0 ) i2 = i1;
   110423       if( rc==SQLITE_OK ){
   110424         rc = sqlite3Fts3SegReaderNew(iAge, i1, i2, 0, 0, 0, &pNew);
   110425       }
   110426     }
   110427     assert( (pNew==0)==(rc!=SQLITE_OK) );
   110428 
   110429     /* If a new Fts3SegReader was allocated, add it to the array. */
   110430     if( rc==SQLITE_OK ){
   110431       rc = fts3SegReaderArrayAdd(&pArray, pNew);
   110432     }
   110433     if( rc==SQLITE_OK ){
   110434       rc = sqlite3Fts3SegReaderCost(pCsr, pNew, &pArray->nCost);
   110435     }
   110436     iAge++;
   110437   }
   110438 
   110439   if( rc==SQLITE_DONE ){
   110440     rc = sqlite3_reset(pStmt);
   110441   }else{
   110442     sqlite3_reset(pStmt);
   110443   }
   110444   if( rc!=SQLITE_OK ){
   110445     fts3SegReaderArrayFree(pArray);
   110446     pArray = 0;
   110447   }
   110448   *ppArray = pArray;
   110449   return rc;
   110450 }
   110451 
   110452 /*
   110453 ** This function retreives the doclist for the specified term (or term
   110454 ** prefix) from the database.
   110455 **
   110456 ** The returned doclist may be in one of two formats, depending on the
   110457 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
   110458 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
   110459 ** is non-zero, then the returned list is in the same format as is stored
   110460 ** in the database without the found length specifier at the start of on-disk
   110461 ** doclists.
   110462 */
   110463 static int fts3TermSelect(
   110464   Fts3Table *p,                   /* Virtual table handle */
   110465   Fts3PhraseToken *pTok,          /* Token to query for */
   110466   int iColumn,                    /* Column to query (or -ve for all columns) */
   110467   int isReqPos,                   /* True to include position lists in output */
   110468   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
   110469   char **ppOut                    /* OUT: Malloced result buffer */
   110470 ){
   110471   int rc;                         /* Return code */
   110472   Fts3SegReaderArray *pArray;     /* Seg-reader array for this term */
   110473   TermSelect tsc;               /* Context object for fts3TermSelectCb() */
   110474   Fts3SegFilter filter;         /* Segment term filter configuration */
   110475 
   110476   pArray = pTok->pArray;
   110477   memset(&tsc, 0, sizeof(TermSelect));
   110478   tsc.isReqPos = isReqPos;
   110479 
   110480   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
   110481         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
   110482         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
   110483         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
   110484   filter.iCol = iColumn;
   110485   filter.zTerm = pTok->z;
   110486   filter.nTerm = pTok->n;
   110487 
   110488   rc = sqlite3Fts3SegReaderIterate(p, pArray->apSegment, pArray->nSegment,
   110489       &filter, fts3TermSelectCb, (void *)&tsc
   110490   );
   110491   if( rc==SQLITE_OK ){
   110492     rc = fts3TermSelectMerge(&tsc);
   110493   }
   110494 
   110495   if( rc==SQLITE_OK ){
   110496     *ppOut = tsc.aaOutput[0];
   110497     *pnOut = tsc.anOutput[0];
   110498   }else{
   110499     int i;
   110500     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
   110501       sqlite3_free(tsc.aaOutput[i]);
   110502     }
   110503   }
   110504 
   110505   fts3SegReaderArrayFree(pArray);
   110506   pTok->pArray = 0;
   110507   return rc;
   110508 }
   110509 
   110510 /*
   110511 ** This function counts the total number of docids in the doclist stored
   110512 ** in buffer aList[], size nList bytes.
   110513 **
   110514 ** If the isPoslist argument is true, then it is assumed that the doclist
   110515 ** contains a position-list following each docid. Otherwise, it is assumed
   110516 ** that the doclist is simply a list of docids stored as delta encoded
   110517 ** varints.
   110518 */
   110519 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
   110520   int nDoc = 0;                   /* Return value */
   110521   if( aList ){
   110522     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
   110523     char *p = aList;              /* Cursor */
   110524     if( !isPoslist ){
   110525       /* The number of docids in the list is the same as the number of
   110526       ** varints. In FTS3 a varint consists of a single byte with the 0x80
   110527       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
   110528       ** count the varints in the buffer, just count the number of bytes
   110529       ** with the 0x80 bit clear.  */
   110530       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
   110531     }else{
   110532       while( p<aEnd ){
   110533         nDoc++;
   110534         while( (*p++)&0x80 );     /* Skip docid varint */
   110535         fts3PoslistCopy(0, &p);   /* Skip over position list */
   110536       }
   110537     }
   110538   }
   110539 
   110540   return nDoc;
   110541 }
   110542 
   110543 /*
   110544 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
   110545 */
   110546 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
   110547   int rc = SQLITE_OK;
   110548   if( pExpr ){
   110549     rc = fts3DeferExpression(pCsr, pExpr->pLeft);
   110550     if( rc==SQLITE_OK ){
   110551       rc = fts3DeferExpression(pCsr, pExpr->pRight);
   110552     }
   110553     if( pExpr->eType==FTSQUERY_PHRASE ){
   110554       int iCol = pExpr->pPhrase->iColumn;
   110555       int i;
   110556       for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
   110557         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
   110558         if( pToken->pDeferred==0 ){
   110559           rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
   110560         }
   110561       }
   110562     }
   110563   }
   110564   return rc;
   110565 }
   110566 
   110567 /*
   110568 ** This function removes the position information from a doclist. When
   110569 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
   110570 ** position information. This function removes the position information so
   110571 ** that aList contains only docids, and adjusts *pnList to reflect the new
   110572 ** (possibly reduced) size of the doclist.
   110573 */
   110574 static void fts3DoclistStripPositions(
   110575   char *aList,                    /* IN/OUT: Buffer containing doclist */
   110576   int *pnList                     /* IN/OUT: Size of doclist in bytes */
   110577 ){
   110578   if( aList ){
   110579     char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
   110580     char *p = aList;              /* Input cursor */
   110581     char *pOut = aList;           /* Output cursor */
   110582 
   110583     while( p<aEnd ){
   110584       sqlite3_int64 delta;
   110585       p += sqlite3Fts3GetVarint(p, &delta);
   110586       fts3PoslistCopy(0, &p);
   110587       pOut += sqlite3Fts3PutVarint(pOut, delta);
   110588     }
   110589 
   110590     *pnList = (int)(pOut - aList);
   110591   }
   110592 }
   110593 
   110594 /*
   110595 ** Return a DocList corresponding to the phrase *pPhrase.
   110596 **
   110597 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
   110598 ** then no tokens in the phrase were looked up in the full-text index. This
   110599 ** is only possible when this function is called from within xFilter(). The
   110600 ** caller should assume that all documents match the phrase. The actual
   110601 ** filtering will take place in xNext().
   110602 */
   110603 static int fts3PhraseSelect(
   110604   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
   110605   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
   110606   int isReqPos,                   /* True if output should contain positions */
   110607   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
   110608   int *pnOut                      /* OUT: Size of buffer at *paOut */
   110609 ){
   110610   char *pOut = 0;
   110611   int nOut = 0;
   110612   int rc = SQLITE_OK;
   110613   int ii;
   110614   int iCol = pPhrase->iColumn;
   110615   int isTermPos = (pPhrase->nToken>1 || isReqPos);
   110616   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   110617   int isFirst = 1;
   110618 
   110619   int iPrevTok = 0;
   110620   int nDoc = 0;
   110621 
   110622   /* If this is an xFilter() evaluation, create a segment-reader for each
   110623   ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
   110624   ** evaluation, only create segment-readers if there are no Fts3DeferredToken
   110625   ** objects attached to the phrase-tokens.
   110626   */
   110627   for(ii=0; ii<pPhrase->nToken; ii++){
   110628     Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
   110629     if( pTok->pArray==0 ){
   110630       if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
   110631        || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0)
   110632        || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext)
   110633       ){
   110634         rc = fts3TermSegReaderArray(
   110635             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
   110636         );
   110637         if( rc!=SQLITE_OK ) return rc;
   110638       }
   110639     }
   110640   }
   110641 
   110642   for(ii=0; ii<pPhrase->nToken; ii++){
   110643     Fts3PhraseToken *pTok;        /* Token to find doclist for */
   110644     int iTok = 0;                 /* The token being queried this iteration */
   110645     char *pList = 0;              /* Pointer to token doclist */
   110646     int nList = 0;                /* Size of buffer at pList */
   110647 
   110648     /* Select a token to process. If this is an xFilter() call, then tokens
   110649     ** are processed in order from least to most costly. Otherwise, tokens
   110650     ** are processed in the order in which they occur in the phrase.
   110651     */
   110652     if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
   110653       assert( isReqPos );
   110654       iTok = ii;
   110655       pTok = &pPhrase->aToken[iTok];
   110656       if( pTok->bFulltext==0 ) continue;
   110657     }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
   110658       iTok = ii;
   110659       pTok = &pPhrase->aToken[iTok];
   110660     }else{
   110661       int nMinCost = 0x7FFFFFFF;
   110662       int jj;
   110663 
   110664       /* Find the remaining token with the lowest cost. */
   110665       for(jj=0; jj<pPhrase->nToken; jj++){
   110666         Fts3SegReaderArray *pArray = pPhrase->aToken[jj].pArray;
   110667         if( pArray && pArray->nCost<nMinCost ){
   110668           iTok = jj;
   110669           nMinCost = pArray->nCost;
   110670         }
   110671       }
   110672       pTok = &pPhrase->aToken[iTok];
   110673 
   110674       /* This branch is taken if it is determined that loading the doclist
   110675       ** for the next token would require more IO than loading all documents
   110676       ** currently identified by doclist pOut/nOut. No further doclists will
   110677       ** be loaded from the full-text index for this phrase.
   110678       */
   110679       if( nMinCost>nDoc && ii>0 ){
   110680         rc = fts3DeferExpression(pCsr, pCsr->pExpr);
   110681         break;
   110682       }
   110683     }
   110684 
   110685     if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
   110686       rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
   110687     }else{
   110688       if( pTok->pArray ){
   110689         rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
   110690       }
   110691       pTok->bFulltext = 1;
   110692     }
   110693     assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pArray==0 );
   110694     if( rc!=SQLITE_OK ) break;
   110695 
   110696     if( isFirst ){
   110697       pOut = pList;
   110698       nOut = nList;
   110699       if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
   110700         nDoc = fts3DoclistCountDocids(1, pOut, nOut);
   110701       }
   110702       isFirst = 0;
   110703       iPrevTok = iTok;
   110704     }else{
   110705       /* Merge the new term list and the current output. */
   110706       char *aLeft, *aRight;
   110707       int nLeft, nRight;
   110708       int nDist;
   110709       int mt;
   110710 
   110711       /* If this is the final token of the phrase, and positions were not
   110712       ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
   110713       ** This drops the position information from the output list.
   110714       */
   110715       mt = MERGE_POS_PHRASE;
   110716       if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
   110717 
   110718       assert( iPrevTok!=iTok );
   110719       if( iPrevTok<iTok ){
   110720         aLeft = pOut;
   110721         nLeft = nOut;
   110722         aRight = pList;
   110723         nRight = nList;
   110724         nDist = iTok-iPrevTok;
   110725         iPrevTok = iTok;
   110726       }else{
   110727         aRight = pOut;
   110728         nRight = nOut;
   110729         aLeft = pList;
   110730         nLeft = nList;
   110731         nDist = iPrevTok-iTok;
   110732       }
   110733       pOut = aRight;
   110734       fts3DoclistMerge(
   110735           mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
   110736       );
   110737       sqlite3_free(aLeft);
   110738     }
   110739     assert( nOut==0 || pOut!=0 );
   110740   }
   110741 
   110742   if( rc==SQLITE_OK ){
   110743     if( ii!=pPhrase->nToken ){
   110744       assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
   110745       fts3DoclistStripPositions(pOut, &nOut);
   110746     }
   110747     *paOut = pOut;
   110748     *pnOut = nOut;
   110749   }else{
   110750     sqlite3_free(pOut);
   110751   }
   110752   return rc;
   110753 }
   110754 
   110755 /*
   110756 ** This function merges two doclists according to the requirements of a
   110757 ** NEAR operator.
   110758 **
   110759 ** Both input doclists must include position information. The output doclist
   110760 ** includes position information if the first argument to this function
   110761 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
   110762 */
   110763 static int fts3NearMerge(
   110764   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
   110765   int nNear,                      /* Parameter to NEAR operator */
   110766   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
   110767   char *aLeft,                    /* Doclist for LHS (incl. positions) */
   110768   int nLeft,                      /* Size of LHS doclist in bytes */
   110769   int nTokenRight,                /* As nTokenLeft */
   110770   char *aRight,                   /* As aLeft */
   110771   int nRight,                     /* As nRight */
   110772   char **paOut,                   /* OUT: Results of merge (malloced) */
   110773   int *pnOut                      /* OUT: Sized of output buffer */
   110774 ){
   110775   char *aOut;                     /* Buffer to write output doclist to */
   110776   int rc;                         /* Return code */
   110777 
   110778   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
   110779 
   110780   aOut = sqlite3_malloc(nLeft+nRight+1);
   110781   if( aOut==0 ){
   110782     rc = SQLITE_NOMEM;
   110783   }else{
   110784     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
   110785       aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
   110786     );
   110787     if( rc!=SQLITE_OK ){
   110788       sqlite3_free(aOut);
   110789       aOut = 0;
   110790     }
   110791   }
   110792 
   110793   *paOut = aOut;
   110794   return rc;
   110795 }
   110796 
   110797 /*
   110798 ** This function is used as part of the processing for the snippet() and
   110799 ** offsets() functions.
   110800 **
   110801 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
   110802 ** have their respective doclists (including position information) loaded
   110803 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
   110804 ** each doclist that are not within nNear tokens of a corresponding entry
   110805 ** in the other doclist.
   110806 */
   110807 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
   110808   int rc;                         /* Return code */
   110809 
   110810   assert( pLeft->eType==FTSQUERY_PHRASE );
   110811   assert( pRight->eType==FTSQUERY_PHRASE );
   110812   assert( pLeft->isLoaded && pRight->isLoaded );
   110813 
   110814   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
   110815     sqlite3_free(pLeft->aDoclist);
   110816     sqlite3_free(pRight->aDoclist);
   110817     pRight->aDoclist = 0;
   110818     pLeft->aDoclist = 0;
   110819     rc = SQLITE_OK;
   110820   }else{
   110821     char *aOut;                   /* Buffer in which to assemble new doclist */
   110822     int nOut;                     /* Size of buffer aOut in bytes */
   110823 
   110824     rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
   110825         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
   110826         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
   110827         &aOut, &nOut
   110828     );
   110829     if( rc!=SQLITE_OK ) return rc;
   110830     sqlite3_free(pRight->aDoclist);
   110831     pRight->aDoclist = aOut;
   110832     pRight->nDoclist = nOut;
   110833 
   110834     rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
   110835         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
   110836         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
   110837         &aOut, &nOut
   110838     );
   110839     sqlite3_free(pLeft->aDoclist);
   110840     pLeft->aDoclist = aOut;
   110841     pLeft->nDoclist = nOut;
   110842   }
   110843   return rc;
   110844 }
   110845 
   110846 
   110847 /*
   110848 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr.
   110849 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
   110850 ** variables of each token structure.
   110851 */
   110852 static int fts3ExprAllocateSegReaders(
   110853   Fts3Cursor *pCsr,               /* FTS3 table */
   110854   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
   110855   int *pnExpr                     /* OUT: Number of AND'd expressions */
   110856 ){
   110857   int rc = SQLITE_OK;             /* Return code */
   110858 
   110859   assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
   110860   if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
   110861     (*pnExpr)++;
   110862     pnExpr = 0;
   110863   }
   110864 
   110865   if( pExpr->eType==FTSQUERY_PHRASE ){
   110866     Fts3Phrase *pPhrase = pExpr->pPhrase;
   110867     int ii;
   110868 
   110869     for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
   110870       Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
   110871       if( pTok->pArray==0 ){
   110872         rc = fts3TermSegReaderArray(
   110873             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
   110874         );
   110875       }
   110876     }
   110877   }else{
   110878     rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
   110879     if( rc==SQLITE_OK ){
   110880       rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
   110881     }
   110882   }
   110883   return rc;
   110884 }
   110885 
   110886 /*
   110887 ** Free the Fts3SegReaderArray objects associated with each token in the
   110888 ** expression pExpr. In other words, this function frees the resources
   110889 ** allocated by fts3ExprAllocateSegReaders().
   110890 */
   110891 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
   110892   if( pExpr ){
   110893     Fts3Phrase *pPhrase = pExpr->pPhrase;
   110894     if( pPhrase ){
   110895       int kk;
   110896       for(kk=0; kk<pPhrase->nToken; kk++){
   110897         fts3SegReaderArrayFree(pPhrase->aToken[kk].pArray);
   110898         pPhrase->aToken[kk].pArray = 0;
   110899       }
   110900     }
   110901     fts3ExprFreeSegReaders(pExpr->pLeft);
   110902     fts3ExprFreeSegReaders(pExpr->pRight);
   110903   }
   110904 }
   110905 
   110906 /*
   110907 ** Return the sum of the costs of all tokens in the expression pExpr. This
   110908 ** function must be called after Fts3SegReaderArrays have been allocated
   110909 ** for all tokens using fts3ExprAllocateSegReaders().
   110910 */
   110911 static int fts3ExprCost(Fts3Expr *pExpr){
   110912   int nCost;                      /* Return value */
   110913   if( pExpr->eType==FTSQUERY_PHRASE ){
   110914     Fts3Phrase *pPhrase = pExpr->pPhrase;
   110915     int ii;
   110916     nCost = 0;
   110917     for(ii=0; ii<pPhrase->nToken; ii++){
   110918       Fts3SegReaderArray *pArray = pPhrase->aToken[ii].pArray;
   110919       if( pArray ){
   110920         nCost += pPhrase->aToken[ii].pArray->nCost;
   110921       }
   110922     }
   110923   }else{
   110924     nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
   110925   }
   110926   return nCost;
   110927 }
   110928 
   110929 /*
   110930 ** The following is a helper function (and type) for fts3EvalExpr(). It
   110931 ** must be called after Fts3SegReaders have been allocated for every token
   110932 ** in the expression. See the context it is called from in fts3EvalExpr()
   110933 ** for further explanation.
   110934 */
   110935 typedef struct ExprAndCost ExprAndCost;
   110936 struct ExprAndCost {
   110937   Fts3Expr *pExpr;
   110938   int nCost;
   110939 };
   110940 static void fts3ExprAssignCosts(
   110941   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
   110942   ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
   110943 ){
   110944   if( pExpr->eType==FTSQUERY_AND ){
   110945     fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
   110946     fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
   110947   }else{
   110948     (*ppExprCost)->pExpr = pExpr;
   110949     (*ppExprCost)->nCost = fts3ExprCost(pExpr);
   110950     (*ppExprCost)++;
   110951   }
   110952 }
   110953 
   110954 /*
   110955 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
   110956 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
   110957 ** the space needed to store the output. The caller is responsible for
   110958 ** freeing the space when it has finished.
   110959 **
   110960 ** This function is called in two distinct contexts:
   110961 **
   110962 **   * From within the virtual table xFilter() method. In this case, the
   110963 **     output doclist contains entries for all rows in the table, based on
   110964 **     data read from the full-text index.
   110965 **
   110966 **     In this case, if the query expression contains one or more tokens that
   110967 **     are very common, then the returned doclist may contain a superset of
   110968 **     the documents that actually match the expression.
   110969 **
   110970 **   * From within the virtual table xNext() method. This call is only made
   110971 **     if the call from within xFilter() found that there were very common
   110972 **     tokens in the query expression and did return a superset of the
   110973 **     matching documents. In this case the returned doclist contains only
   110974 **     entries that correspond to the current row of the table. Instead of
   110975 **     reading the data for each token from the full-text index, the data is
   110976 **     already available in-memory in the Fts3PhraseToken.pDeferred structures.
   110977 **     See fts3EvalDeferred() for how it gets there.
   110978 **
   110979 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
   110980 ** required) Fts3Cursor.doDeferred==1.
   110981 **
   110982 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
   110983 ** as part of a SELECT on an FTS3 table, this function is called on each
   110984 ** individual phrase expression in the query. If there were very common tokens
   110985 ** found in the xFilter() call, then this function is called once for phrase
   110986 ** for each row visited, and the returned doclist contains entries for the
   110987 ** current row only. Otherwise, if there were no very common tokens, then this
   110988 ** function is called once only for each phrase in the query and the returned
   110989 ** doclist contains entries for all rows of the table.
   110990 **
   110991 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
   110992 ** result of a snippet(), offsets() or matchinfo() invocation.
   110993 */
   110994 static int fts3EvalExpr(
   110995   Fts3Cursor *p,                  /* Virtual table cursor handle */
   110996   Fts3Expr *pExpr,                /* Parsed fts3 expression */
   110997   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
   110998   int *pnOut,                     /* OUT: Size of buffer at *paOut */
   110999   int isReqPos                    /* Require positions in output buffer */
   111000 ){
   111001   int rc = SQLITE_OK;             /* Return code */
   111002 
   111003   /* Zero the output parameters. */
   111004   *paOut = 0;
   111005   *pnOut = 0;
   111006 
   111007   if( pExpr ){
   111008     assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR
   111009          || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
   111010          || pExpr->eType==FTSQUERY_PHRASE
   111011     );
   111012     assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
   111013 
   111014     if( pExpr->eType==FTSQUERY_PHRASE ){
   111015       rc = fts3PhraseSelect(p, pExpr->pPhrase,
   111016           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
   111017           paOut, pnOut
   111018       );
   111019       fts3ExprFreeSegReaders(pExpr);
   111020     }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
   111021       ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
   111022       int nExpr = 0;              /* Size of aExpr[] */
   111023       char *aRet = 0;             /* Doclist to return to caller */
   111024       int nRet = 0;               /* Length of aRet[] in bytes */
   111025       int nDoc = 0x7FFFFFFF;
   111026 
   111027       assert( !isReqPos );
   111028 
   111029       rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
   111030       if( rc==SQLITE_OK ){
   111031         assert( nExpr>1 );
   111032         aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
   111033         if( !aExpr ) rc = SQLITE_NOMEM;
   111034       }
   111035       if( rc==SQLITE_OK ){
   111036         int ii;                   /* Used to iterate through expressions */
   111037 
   111038         fts3ExprAssignCosts(pExpr, &aExpr);
   111039         aExpr -= nExpr;
   111040         for(ii=0; ii<nExpr; ii++){
   111041           char *aNew;
   111042           int nNew;
   111043           int jj;
   111044           ExprAndCost *pBest = 0;
   111045 
   111046           for(jj=0; jj<nExpr; jj++){
   111047             ExprAndCost *pCand = &aExpr[jj];
   111048             if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
   111049               pBest = pCand;
   111050             }
   111051           }
   111052 
   111053           if( pBest->nCost>nDoc ){
   111054             rc = fts3DeferExpression(p, p->pExpr);
   111055             break;
   111056           }else{
   111057             rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
   111058             if( rc!=SQLITE_OK ) break;
   111059             pBest->pExpr = 0;
   111060             if( ii==0 ){
   111061               aRet = aNew;
   111062               nRet = nNew;
   111063               nDoc = fts3DoclistCountDocids(0, aRet, nRet);
   111064             }else{
   111065               fts3DoclistMerge(
   111066                   MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
   111067               );
   111068               sqlite3_free(aNew);
   111069             }
   111070           }
   111071         }
   111072       }
   111073 
   111074       if( rc==SQLITE_OK ){
   111075         *paOut = aRet;
   111076         *pnOut = nRet;
   111077       }else{
   111078         assert( *paOut==0 );
   111079         sqlite3_free(aRet);
   111080       }
   111081       sqlite3_free(aExpr);
   111082       fts3ExprFreeSegReaders(pExpr);
   111083 
   111084     }else{
   111085       char *aLeft;
   111086       char *aRight;
   111087       int nLeft;
   111088       int nRight;
   111089 
   111090       assert( pExpr->eType==FTSQUERY_NEAR
   111091            || pExpr->eType==FTSQUERY_OR
   111092            || pExpr->eType==FTSQUERY_NOT
   111093            || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
   111094       );
   111095 
   111096       if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
   111097        && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
   111098       ){
   111099         switch( pExpr->eType ){
   111100           case FTSQUERY_NEAR: {
   111101             Fts3Expr *pLeft;
   111102             Fts3Expr *pRight;
   111103             int mergetype = MERGE_NEAR;
   111104             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
   111105               mergetype = MERGE_POS_NEAR;
   111106             }
   111107             pLeft = pExpr->pLeft;
   111108             while( pLeft->eType==FTSQUERY_NEAR ){
   111109               pLeft=pLeft->pRight;
   111110             }
   111111             pRight = pExpr->pRight;
   111112             assert( pRight->eType==FTSQUERY_PHRASE );
   111113             assert( pLeft->eType==FTSQUERY_PHRASE );
   111114 
   111115             rc = fts3NearMerge(mergetype, pExpr->nNear,
   111116                 pLeft->pPhrase->nToken, aLeft, nLeft,
   111117                 pRight->pPhrase->nToken, aRight, nRight,
   111118                 paOut, pnOut
   111119             );
   111120             sqlite3_free(aLeft);
   111121             break;
   111122           }
   111123 
   111124           case FTSQUERY_OR: {
   111125             /* Allocate a buffer for the output. The maximum size is the
   111126             ** sum of the sizes of the two input buffers. The +1 term is
   111127             ** so that a buffer of zero bytes is never allocated - this can
   111128             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
   111129             */
   111130             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
   111131             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
   111132                 aLeft, nLeft, aRight, nRight, 0
   111133             );
   111134             *paOut = aBuffer;
   111135             sqlite3_free(aLeft);
   111136             break;
   111137           }
   111138 
   111139           default: {
   111140             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
   111141             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
   111142                 aLeft, nLeft, aRight, nRight, 0
   111143             );
   111144             *paOut = aLeft;
   111145             break;
   111146           }
   111147         }
   111148       }
   111149       sqlite3_free(aRight);
   111150     }
   111151   }
   111152 
   111153   assert( rc==SQLITE_OK || *paOut==0 );
   111154   return rc;
   111155 }
   111156 
   111157 /*
   111158 ** This function is called from within xNext() for each row visited by
   111159 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
   111160 ** was able to determine the exact set of matching rows, this function sets
   111161 ** *pbRes to true and returns SQLITE_IO immediately.
   111162 **
   111163 ** Otherwise, if evaluating the query expression within xFilter() returned a
   111164 ** superset of the matching documents instead of an exact set (this happens
   111165 ** when the query includes very common tokens and it is deemed too expensive to
   111166 ** load their doclists from disk), this function tests if the current row
   111167 ** really does match the FTS3 query.
   111168 **
   111169 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
   111170 ** is returned and *pbRes is set to true if the current row matches the
   111171 ** FTS3 query (and should be included in the results returned to SQLite), or
   111172 ** false otherwise.
   111173 */
   111174 static int fts3EvalDeferred(
   111175   Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
   111176   int *pbRes                      /* OUT: Set to true if row is a match */
   111177 ){
   111178   int rc = SQLITE_OK;
   111179   if( pCsr->pDeferred==0 ){
   111180     *pbRes = 1;
   111181   }else{
   111182     rc = fts3CursorSeek(0, pCsr);
   111183     if( rc==SQLITE_OK ){
   111184       sqlite3Fts3FreeDeferredDoclists(pCsr);
   111185       rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
   111186     }
   111187     if( rc==SQLITE_OK ){
   111188       char *a = 0;
   111189       int n = 0;
   111190       rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
   111191       assert( n>=0 );
   111192       *pbRes = (n>0);
   111193       sqlite3_free(a);
   111194     }
   111195   }
   111196   return rc;
   111197 }
   111198 
   111199 /*
   111200 ** Advance the cursor to the next row in the %_content table that
   111201 ** matches the search criteria.  For a MATCH search, this will be
   111202 ** the next row that matches. For a full-table scan, this will be
   111203 ** simply the next row in the %_content table.  For a docid lookup,
   111204 ** this routine simply sets the EOF flag.
   111205 **
   111206 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
   111207 ** even if we reach end-of-file.  The fts3EofMethod() will be called
   111208 ** subsequently to determine whether or not an EOF was hit.
   111209 */
   111210 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   111211   int res;
   111212   int rc = SQLITE_OK;             /* Return code */
   111213   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   111214 
   111215   pCsr->eEvalmode = FTS3_EVAL_NEXT;
   111216   do {
   111217     if( pCsr->aDoclist==0 ){
   111218       if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
   111219         pCsr->isEof = 1;
   111220         rc = sqlite3_reset(pCsr->pStmt);
   111221         break;
   111222       }
   111223       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
   111224     }else{
   111225       if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
   111226         pCsr->isEof = 1;
   111227         break;
   111228       }
   111229       sqlite3_reset(pCsr->pStmt);
   111230       fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
   111231       pCsr->isRequireSeek = 1;
   111232       pCsr->isMatchinfoNeeded = 1;
   111233     }
   111234   }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
   111235 
   111236   return rc;
   111237 }
   111238 
   111239 /*
   111240 ** This is the xFilter interface for the virtual table.  See
   111241 ** the virtual table xFilter method documentation for additional
   111242 ** information.
   111243 **
   111244 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
   111245 ** the %_content table.
   111246 **
   111247 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
   111248 ** in the %_content table.
   111249 **
   111250 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
   111251 ** column on the left-hand side of the MATCH operator is column
   111252 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
   111253 ** side of the MATCH operator.
   111254 */
   111255 static int fts3FilterMethod(
   111256   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
   111257   int idxNum,                     /* Strategy index */
   111258   const char *idxStr,             /* Unused */
   111259   int nVal,                       /* Number of elements in apVal */
   111260   sqlite3_value **apVal           /* Arguments for the indexing scheme */
   111261 ){
   111262   const char *azSql[] = {
   111263     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
   111264     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
   111265   };
   111266   int rc;                         /* Return code */
   111267   char *zSql;                     /* SQL statement used to access %_content */
   111268   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   111269   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   111270 
   111271   UNUSED_PARAMETER(idxStr);
   111272   UNUSED_PARAMETER(nVal);
   111273 
   111274   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   111275   assert( nVal==0 || nVal==1 );
   111276   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
   111277   assert( p->pSegments==0 );
   111278 
   111279   /* In case the cursor has been used before, clear it now. */
   111280   sqlite3_finalize(pCsr->pStmt);
   111281   sqlite3_free(pCsr->aDoclist);
   111282   sqlite3Fts3ExprFree(pCsr->pExpr);
   111283   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
   111284 
   111285   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
   111286     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
   111287     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
   111288 
   111289     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   111290       return SQLITE_NOMEM;
   111291     }
   111292 
   111293     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
   111294         iCol, zQuery, -1, &pCsr->pExpr
   111295     );
   111296     if( rc!=SQLITE_OK ){
   111297       if( rc==SQLITE_ERROR ){
   111298         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
   111299                                           zQuery);
   111300       }
   111301       return rc;
   111302     }
   111303 
   111304     rc = sqlite3Fts3ReadLock(p);
   111305     if( rc!=SQLITE_OK ) return rc;
   111306 
   111307     rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
   111308     sqlite3Fts3SegmentsClose(p);
   111309     if( rc!=SQLITE_OK ) return rc;
   111310     pCsr->pNextId = pCsr->aDoclist;
   111311     pCsr->iPrevId = 0;
   111312   }
   111313 
   111314   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
   111315   ** statement loops through all rows of the %_content table. For a
   111316   ** full-text query or docid lookup, the statement retrieves a single
   111317   ** row by docid.
   111318   */
   111319   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
   111320   if( !zSql ){
   111321     rc = SQLITE_NOMEM;
   111322   }else{
   111323     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
   111324     sqlite3_free(zSql);
   111325   }
   111326   if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
   111327     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
   111328   }
   111329   pCsr->eSearch = (i16)idxNum;
   111330 
   111331   if( rc!=SQLITE_OK ) return rc;
   111332   return fts3NextMethod(pCursor);
   111333 }
   111334 
   111335 /*
   111336 ** This is the xEof method of the virtual table. SQLite calls this
   111337 ** routine to find out if it has reached the end of a result set.
   111338 */
   111339 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   111340   return ((Fts3Cursor *)pCursor)->isEof;
   111341 }
   111342 
   111343 /*
   111344 ** This is the xRowid method. The SQLite core calls this routine to
   111345 ** retrieve the rowid for the current row of the result set. fts3
   111346 ** exposes %_content.docid as the rowid for the virtual table. The
   111347 ** rowid should be written to *pRowid.
   111348 */
   111349 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   111350   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   111351   if( pCsr->aDoclist ){
   111352     *pRowid = pCsr->iPrevId;
   111353   }else{
   111354     /* This branch runs if the query is implemented using a full-table scan
   111355     ** (not using the full-text index). In this case grab the rowid from the
   111356     ** SELECT statement.
   111357     */
   111358     assert( pCsr->isRequireSeek==0 );
   111359     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
   111360   }
   111361   return SQLITE_OK;
   111362 }
   111363 
   111364 /*
   111365 ** This is the xColumn method, called by SQLite to request a value from
   111366 ** the row that the supplied cursor currently points to.
   111367 */
   111368 static int fts3ColumnMethod(
   111369   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
   111370   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
   111371   int iCol                        /* Index of column to read value from */
   111372 ){
   111373   int rc;                         /* Return Code */
   111374   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
   111375   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
   111376 
   111377   /* The column value supplied by SQLite must be in range. */
   111378   assert( iCol>=0 && iCol<=p->nColumn+1 );
   111379 
   111380   if( iCol==p->nColumn+1 ){
   111381     /* This call is a request for the "docid" column. Since "docid" is an
   111382     ** alias for "rowid", use the xRowid() method to obtain the value.
   111383     */
   111384     sqlite3_int64 iRowid;
   111385     rc = fts3RowidMethod(pCursor, &iRowid);
   111386     sqlite3_result_int64(pContext, iRowid);
   111387   }else if( iCol==p->nColumn ){
   111388     /* The extra column whose name is the same as the table.
   111389     ** Return a blob which is a pointer to the cursor.
   111390     */
   111391     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
   111392     rc = SQLITE_OK;
   111393   }else{
   111394     rc = fts3CursorSeek(0, pCsr);
   111395     if( rc==SQLITE_OK ){
   111396       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
   111397     }
   111398   }
   111399   return rc;
   111400 }
   111401 
   111402 /*
   111403 ** This function is the implementation of the xUpdate callback used by
   111404 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
   111405 ** inserted, updated or deleted.
   111406 */
   111407 static int fts3UpdateMethod(
   111408   sqlite3_vtab *pVtab,            /* Virtual table handle */
   111409   int nArg,                       /* Size of argument array */
   111410   sqlite3_value **apVal,          /* Array of arguments */
   111411   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   111412 ){
   111413   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
   111414 }
   111415 
   111416 /*
   111417 ** Implementation of xSync() method. Flush the contents of the pending-terms
   111418 ** hash-table to the database.
   111419 */
   111420 static int fts3SyncMethod(sqlite3_vtab *pVtab){
   111421   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
   111422   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
   111423   return rc;
   111424 }
   111425 
   111426 /*
   111427 ** Implementation of xBegin() method. This is a no-op.
   111428 */
   111429 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   111430   UNUSED_PARAMETER(pVtab);
   111431   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
   111432   return SQLITE_OK;
   111433 }
   111434 
   111435 /*
   111436 ** Implementation of xCommit() method. This is a no-op. The contents of
   111437 ** the pending-terms hash-table have already been flushed into the database
   111438 ** by fts3SyncMethod().
   111439 */
   111440 static int fts3CommitMethod(sqlite3_vtab *pVtab){
   111441   UNUSED_PARAMETER(pVtab);
   111442   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
   111443   return SQLITE_OK;
   111444 }
   111445 
   111446 /*
   111447 ** Implementation of xRollback(). Discard the contents of the pending-terms
   111448 ** hash-table. Any changes made to the database are reverted by SQLite.
   111449 */
   111450 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
   111451   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
   111452   return SQLITE_OK;
   111453 }
   111454 
   111455 /*
   111456 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
   111457 ** The loaded doclist contains positions as well as the document ids.
   111458 ** This is used by the matchinfo(), snippet() and offsets() auxillary
   111459 ** functions.
   111460 */
   111461 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
   111462   int rc;
   111463   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
   111464   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
   111465   rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
   111466   return rc;
   111467 }
   111468 
   111469 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
   111470   Fts3Cursor *pCsr,
   111471   Fts3Expr *pExpr,
   111472   char **paDoclist,
   111473   int *pnDoclist
   111474 ){
   111475   int rc;
   111476   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
   111477   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
   111478   pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
   111479   rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
   111480   pCsr->eEvalmode = FTS3_EVAL_NEXT;
   111481   return rc;
   111482 }
   111483 
   111484 /*
   111485 ** After ExprLoadDoclist() (see above) has been called, this function is
   111486 ** used to iterate/search through the position lists that make up the doclist
   111487 ** stored in pExpr->aDoclist.
   111488 */
   111489 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
   111490   Fts3Expr *pExpr,                /* Access this expressions doclist */
   111491   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
   111492   int iCol                        /* Column of requested pos-list */
   111493 ){
   111494   assert( pExpr->isLoaded );
   111495   if( pExpr->aDoclist ){
   111496     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
   111497     char *pCsr = pExpr->pCurrent;
   111498 
   111499     assert( pCsr );
   111500     while( pCsr<pEnd ){
   111501       if( pExpr->iCurrent<iDocid ){
   111502         fts3PoslistCopy(0, &pCsr);
   111503         if( pCsr<pEnd ){
   111504           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
   111505         }
   111506         pExpr->pCurrent = pCsr;
   111507       }else{
   111508         if( pExpr->iCurrent==iDocid ){
   111509           int iThis = 0;
   111510           if( iCol<0 ){
   111511             /* If iCol is negative, return a pointer to the start of the
   111512             ** position-list (instead of a pointer to the start of a list
   111513             ** of offsets associated with a specific column).
   111514             */
   111515             return pCsr;
   111516           }
   111517           while( iThis<iCol ){
   111518             fts3ColumnlistCopy(0, &pCsr);
   111519             if( *pCsr==0x00 ) return 0;
   111520             pCsr++;
   111521             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
   111522           }
   111523           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
   111524         }
   111525         return 0;
   111526       }
   111527     }
   111528   }
   111529 
   111530   return 0;
   111531 }
   111532 
   111533 /*
   111534 ** Helper function used by the implementation of the overloaded snippet(),
   111535 ** offsets() and optimize() SQL functions.
   111536 **
   111537 ** If the value passed as the third argument is a blob of size
   111538 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
   111539 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
   111540 ** message is written to context pContext and SQLITE_ERROR returned. The
   111541 ** string passed via zFunc is used as part of the error message.
   111542 */
   111543 static int fts3FunctionArg(
   111544   sqlite3_context *pContext,      /* SQL function call context */
   111545   const char *zFunc,              /* Function name */
   111546   sqlite3_value *pVal,            /* argv[0] passed to function */
   111547   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
   111548 ){
   111549   Fts3Cursor *pRet;
   111550   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
   111551    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
   111552   ){
   111553     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
   111554     sqlite3_result_error(pContext, zErr, -1);
   111555     sqlite3_free(zErr);
   111556     return SQLITE_ERROR;
   111557   }
   111558   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
   111559   *ppCsr = pRet;
   111560   return SQLITE_OK;
   111561 }
   111562 
   111563 /*
   111564 ** Implementation of the snippet() function for FTS3
   111565 */
   111566 static void fts3SnippetFunc(
   111567   sqlite3_context *pContext,      /* SQLite function call context */
   111568   int nVal,                       /* Size of apVal[] array */
   111569   sqlite3_value **apVal           /* Array of arguments */
   111570 ){
   111571   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   111572   const char *zStart = "<b>";
   111573   const char *zEnd = "</b>";
   111574   const char *zEllipsis = "<b>...</b>";
   111575   int iCol = -1;
   111576   int nToken = 15;                /* Default number of tokens in snippet */
   111577 
   111578   /* There must be at least one argument passed to this function (otherwise
   111579   ** the non-overloaded version would have been called instead of this one).
   111580   */
   111581   assert( nVal>=1 );
   111582 
   111583   if( nVal>6 ){
   111584     sqlite3_result_error(pContext,
   111585         "wrong number of arguments to function snippet()", -1);
   111586     return;
   111587   }
   111588   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
   111589 
   111590   switch( nVal ){
   111591     case 6: nToken = sqlite3_value_int(apVal[5]);
   111592     case 5: iCol = sqlite3_value_int(apVal[4]);
   111593     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
   111594     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
   111595     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   111596   }
   111597   if( !zEllipsis || !zEnd || !zStart ){
   111598     sqlite3_result_error_nomem(pContext);
   111599   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   111600     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
   111601   }
   111602 }
   111603 
   111604 /*
   111605 ** Implementation of the offsets() function for FTS3
   111606 */
   111607 static void fts3OffsetsFunc(
   111608   sqlite3_context *pContext,      /* SQLite function call context */
   111609   int nVal,                       /* Size of argument array */
   111610   sqlite3_value **apVal           /* Array of arguments */
   111611 ){
   111612   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   111613 
   111614   UNUSED_PARAMETER(nVal);
   111615 
   111616   assert( nVal==1 );
   111617   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
   111618   assert( pCsr );
   111619   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
   111620     sqlite3Fts3Offsets(pContext, pCsr);
   111621   }
   111622 }
   111623 
   111624 /*
   111625 ** Implementation of the special optimize() function for FTS3. This
   111626 ** function merges all segments in the database to a single segment.
   111627 ** Example usage is:
   111628 **
   111629 **   SELECT optimize(t) FROM t LIMIT 1;
   111630 **
   111631 ** where 't' is the name of an FTS3 table.
   111632 */
   111633 static void fts3OptimizeFunc(
   111634   sqlite3_context *pContext,      /* SQLite function call context */
   111635   int nVal,                       /* Size of argument array */
   111636   sqlite3_value **apVal           /* Array of arguments */
   111637 ){
   111638   int rc;                         /* Return code */
   111639   Fts3Table *p;                   /* Virtual table handle */
   111640   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
   111641 
   111642   UNUSED_PARAMETER(nVal);
   111643 
   111644   assert( nVal==1 );
   111645   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
   111646   p = (Fts3Table *)pCursor->base.pVtab;
   111647   assert( p );
   111648 
   111649   rc = sqlite3Fts3Optimize(p);
   111650 
   111651   switch( rc ){
   111652     case SQLITE_OK:
   111653       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
   111654       break;
   111655     case SQLITE_DONE:
   111656       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
   111657       break;
   111658     default:
   111659       sqlite3_result_error_code(pContext, rc);
   111660       break;
   111661   }
   111662 }
   111663 
   111664 /*
   111665 ** Implementation of the matchinfo() function for FTS3
   111666 */
   111667 static void fts3MatchinfoFunc(
   111668   sqlite3_context *pContext,      /* SQLite function call context */
   111669   int nVal,                       /* Size of argument array */
   111670   sqlite3_value **apVal           /* Array of arguments */
   111671 ){
   111672   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
   111673   assert( nVal==1 || nVal==2 );
   111674   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
   111675     const char *zArg = 0;
   111676     if( nVal>1 ){
   111677       zArg = (const char *)sqlite3_value_text(apVal[1]);
   111678     }
   111679     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
   111680   }
   111681 }
   111682 
   111683 /*
   111684 ** This routine implements the xFindFunction method for the FTS3
   111685 ** virtual table.
   111686 */
   111687 static int fts3FindFunctionMethod(
   111688   sqlite3_vtab *pVtab,            /* Virtual table handle */
   111689   int nArg,                       /* Number of SQL function arguments */
   111690   const char *zName,              /* Name of SQL function */
   111691   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
   111692   void **ppArg                    /* Unused */
   111693 ){
   111694   struct Overloaded {
   111695     const char *zName;
   111696     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   111697   } aOverload[] = {
   111698     { "snippet", fts3SnippetFunc },
   111699     { "offsets", fts3OffsetsFunc },
   111700     { "optimize", fts3OptimizeFunc },
   111701     { "matchinfo", fts3MatchinfoFunc },
   111702   };
   111703   int i;                          /* Iterator variable */
   111704 
   111705   UNUSED_PARAMETER(pVtab);
   111706   UNUSED_PARAMETER(nArg);
   111707   UNUSED_PARAMETER(ppArg);
   111708 
   111709   for(i=0; i<SizeofArray(aOverload); i++){
   111710     if( strcmp(zName, aOverload[i].zName)==0 ){
   111711       *pxFunc = aOverload[i].xFunc;
   111712       return 1;
   111713     }
   111714   }
   111715 
   111716   /* No function of the specified name was found. Return 0. */
   111717   return 0;
   111718 }
   111719 
   111720 /*
   111721 ** Implementation of FTS3 xRename method. Rename an fts3 table.
   111722 */
   111723 static int fts3RenameMethod(
   111724   sqlite3_vtab *pVtab,            /* Virtual table handle */
   111725   const char *zName               /* New name of table */
   111726 ){
   111727   Fts3Table *p = (Fts3Table *)pVtab;
   111728   sqlite3 *db = p->db;            /* Database connection */
   111729   int rc;                         /* Return Code */
   111730 
   111731   rc = sqlite3Fts3PendingTermsFlush(p);
   111732   if( rc!=SQLITE_OK ){
   111733     return rc;
   111734   }
   111735 
   111736   fts3DbExec(&rc, db,
   111737     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
   111738     p->zDb, p->zName, zName
   111739   );
   111740   if( p->bHasDocsize ){
   111741     fts3DbExec(&rc, db,
   111742       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
   111743       p->zDb, p->zName, zName
   111744     );
   111745   }
   111746   if( p->bHasStat ){
   111747     fts3DbExec(&rc, db,
   111748       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
   111749       p->zDb, p->zName, zName
   111750     );
   111751   }
   111752   fts3DbExec(&rc, db,
   111753     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
   111754     p->zDb, p->zName, zName
   111755   );
   111756   fts3DbExec(&rc, db,
   111757     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
   111758     p->zDb, p->zName, zName
   111759   );
   111760   return rc;
   111761 }
   111762 
   111763 static const sqlite3_module fts3Module = {
   111764   /* iVersion      */ 0,
   111765   /* xCreate       */ fts3CreateMethod,
   111766   /* xConnect      */ fts3ConnectMethod,
   111767   /* xBestIndex    */ fts3BestIndexMethod,
   111768   /* xDisconnect   */ fts3DisconnectMethod,
   111769   /* xDestroy      */ fts3DestroyMethod,
   111770   /* xOpen         */ fts3OpenMethod,
   111771   /* xClose        */ fts3CloseMethod,
   111772   /* xFilter       */ fts3FilterMethod,
   111773   /* xNext         */ fts3NextMethod,
   111774   /* xEof          */ fts3EofMethod,
   111775   /* xColumn       */ fts3ColumnMethod,
   111776   /* xRowid        */ fts3RowidMethod,
   111777   /* xUpdate       */ fts3UpdateMethod,
   111778   /* xBegin        */ fts3BeginMethod,
   111779   /* xSync         */ fts3SyncMethod,
   111780   /* xCommit       */ fts3CommitMethod,
   111781   /* xRollback     */ fts3RollbackMethod,
   111782   /* xFindFunction */ fts3FindFunctionMethod,
   111783   /* xRename */       fts3RenameMethod,
   111784 };
   111785 
   111786 /*
   111787 ** This function is registered as the module destructor (called when an
   111788 ** FTS3 enabled database connection is closed). It frees the memory
   111789 ** allocated for the tokenizer hash table.
   111790 */
   111791 static void hashDestroy(void *p){
   111792   Fts3Hash *pHash = (Fts3Hash *)p;
   111793   sqlite3Fts3HashClear(pHash);
   111794   sqlite3_free(pHash);
   111795 }
   111796 
   111797 /*
   111798 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
   111799 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
   111800 ** respectively. The following three forward declarations are for functions
   111801 ** declared in these files used to retrieve the respective implementations.
   111802 **
   111803 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
   111804 ** to by the argument to point to the "simple" tokenizer implementation.
   111805 ** And so on.
   111806 */
   111807 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   111808 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   111809 #ifdef SQLITE_ENABLE_ICU
   111810 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   111811 #endif
   111812 
   111813 /*
   111814 ** Initialise the fts3 extension. If this extension is built as part
   111815 ** of the sqlite library, then this function is called directly by
   111816 ** SQLite. If fts3 is built as a dynamically loadable extension, this
   111817 ** function is called by the sqlite3_extension_init() entry point.
   111818 */
   111819 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db, const char* registerAs){ // Android Change
   111820   int rc = SQLITE_OK;
   111821   Fts3Hash *pHash = 0;
   111822   const sqlite3_tokenizer_module *pSimple = 0;
   111823   const sqlite3_tokenizer_module *pPorter = 0;
   111824 
   111825 #ifdef SQLITE_ENABLE_ICU
   111826   const sqlite3_tokenizer_module *pIcu = 0;
   111827   sqlite3Fts3IcuTokenizerModule(&pIcu);
   111828 #endif
   111829 
   111830   sqlite3Fts3SimpleTokenizerModule(&pSimple);
   111831   sqlite3Fts3PorterTokenizerModule(&pPorter);
   111832 
   111833   /* Allocate and initialise the hash-table used to store tokenizers. */
   111834   pHash = sqlite3_malloc(sizeof(Fts3Hash));
   111835   if( !pHash ){
   111836     rc = SQLITE_NOMEM;
   111837   }else{
   111838     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   111839   }
   111840 
   111841   /* Load the built-in tokenizers into the hash table */
   111842   if( rc==SQLITE_OK ){
   111843     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
   111844      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
   111845 #ifdef SQLITE_ENABLE_ICU
   111846      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
   111847 #endif
   111848     ){
   111849       rc = SQLITE_NOMEM;
   111850     }
   111851   }
   111852 
   111853 #ifdef SQLITE_TEST
   111854   if( rc==SQLITE_OK ){
   111855     rc = sqlite3Fts3ExprInitTestInterface(db);
   111856   }
   111857 #endif
   111858 
   111859   /* Create the virtual table wrapper around the hash-table and overload
   111860   ** the two scalar functions. If this is successful, register the
   111861   ** module with sqlite.
   111862   */
   111863   if( SQLITE_OK==rc
   111864    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
   111865    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   111866    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
   111867    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
   111868    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
   111869    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
   111870   ){
   111871     rc = sqlite3_create_module_v2(
   111872         // Begin Android change
   111873         // Also register as fts1 and fts2
   111874         db, registerAs, &fts3Module, (void *)pHash, hashDestroy
   111875         // End Android change
   111876     );
   111877     if( rc==SQLITE_OK ){
   111878       rc = sqlite3_create_module_v2(
   111879           db, "fts4", &fts3Module, (void *)pHash, 0
   111880       );
   111881     }
   111882     return rc;
   111883   }
   111884 
   111885   /* An error has occurred. Delete the hash table and return the error code. */
   111886   assert( rc!=SQLITE_OK );
   111887   if( pHash ){
   111888     sqlite3Fts3HashClear(pHash);
   111889     sqlite3_free(pHash);
   111890   }
   111891   return rc;
   111892 }
   111893 
   111894 #if !SQLITE_CORE
   111895 SQLITE_API int sqlite3_extension_init(
   111896   sqlite3 *db,
   111897   char **pzErrMsg,
   111898   const sqlite3_api_routines *pApi
   111899 ){
   111900   SQLITE_EXTENSION_INIT2(pApi)
   111901   return sqlite3Fts3Init(db);
   111902 }
   111903 #endif
   111904 
   111905 #endif
   111906 
   111907 /************** End of fts3.c ************************************************/
   111908 /************** Begin file fts3_expr.c ***************************************/
   111909 /*
   111910 ** 2008 Nov 28
   111911 **
   111912 ** The author disclaims copyright to this source code.  In place of
   111913 ** a legal notice, here is a blessing:
   111914 **
   111915 **    May you do good and not evil.
   111916 **    May you find forgiveness for yourself and forgive others.
   111917 **    May you share freely, never taking more than you give.
   111918 **
   111919 ******************************************************************************
   111920 **
   111921 ** This module contains code that implements a parser for fts3 query strings
   111922 ** (the right-hand argument to the MATCH operator). Because the supported
   111923 ** syntax is relatively simple, the whole tokenizer/parser system is
   111924 ** hand-coded.
   111925 */
   111926 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   111927 
   111928 /*
   111929 ** By default, this module parses the legacy syntax that has been
   111930 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
   111931 ** is defined, then it uses the new syntax. The differences between
   111932 ** the new and the old syntaxes are:
   111933 **
   111934 **  a) The new syntax supports parenthesis. The old does not.
   111935 **
   111936 **  b) The new syntax supports the AND and NOT operators. The old does not.
   111937 **
   111938 **  c) The old syntax supports the "-" token qualifier. This is not
   111939 **     supported by the new syntax (it is replaced by the NOT operator).
   111940 **
   111941 **  d) When using the old syntax, the OR operator has a greater precedence
   111942 **     than an implicit AND. When using the new, both implicity and explicit
   111943 **     AND operators have a higher precedence than OR.
   111944 **
   111945 ** If compiled with SQLITE_TEST defined, then this module exports the
   111946 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
   111947 ** to zero causes the module to use the old syntax. If it is set to
   111948 ** non-zero the new syntax is activated. This is so both syntaxes can
   111949 ** be tested using a single build of testfixture.
   111950 **
   111951 ** The following describes the syntax supported by the fts3 MATCH
   111952 ** operator in a similar format to that used by the lemon parser
   111953 ** generator. This module does not use actually lemon, it uses a
   111954 ** custom parser.
   111955 **
   111956 **   query ::= andexpr (OR andexpr)*.
   111957 **
   111958 **   andexpr ::= notexpr (AND? notexpr)*.
   111959 **
   111960 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
   111961 **   notexpr ::= LP query RP.
   111962 **
   111963 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
   111964 **
   111965 **   distance_opt ::= .
   111966 **   distance_opt ::= / INTEGER.
   111967 **
   111968 **   phrase ::= TOKEN.
   111969 **   phrase ::= COLUMN:TOKEN.
   111970 **   phrase ::= "TOKEN TOKEN TOKEN...".
   111971 */
   111972 
   111973 #ifdef SQLITE_TEST
   111974 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
   111975 #else
   111976 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
   111977 #  define sqlite3_fts3_enable_parentheses 1
   111978 # else
   111979 #  define sqlite3_fts3_enable_parentheses 0
   111980 # endif
   111981 #endif
   111982 
   111983 /*
   111984 ** Default span for NEAR operators.
   111985 */
   111986 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
   111987 
   111988 
   111989 typedef struct ParseContext ParseContext;
   111990 struct ParseContext {
   111991   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
   111992   const char **azCol;                 /* Array of column names for fts3 table */
   111993   int nCol;                           /* Number of entries in azCol[] */
   111994   int iDefaultCol;                    /* Default column to query */
   111995   sqlite3_context *pCtx;              /* Write error message here */
   111996   int nNest;                          /* Number of nested brackets */
   111997 };
   111998 
   111999 /*
   112000 ** This function is equivalent to the standard isspace() function.
   112001 **
   112002 ** The standard isspace() can be awkward to use safely, because although it
   112003 ** is defined to accept an argument of type int, its behaviour when passed
   112004 ** an integer that falls outside of the range of the unsigned char type
   112005 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
   112006 ** is defined to accept an argument of type char, and always returns 0 for
   112007 ** any values that fall outside of the range of the unsigned char type (i.e.
   112008 ** negative values).
   112009 */
   112010 static int fts3isspace(char c){
   112011   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
   112012 }
   112013 
   112014 /*
   112015 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
   112016 ** zero the memory before returning a pointer to it. If unsuccessful,
   112017 ** return NULL.
   112018 */
   112019 static void *fts3MallocZero(int nByte){
   112020   void *pRet = sqlite3_malloc(nByte);
   112021   if( pRet ) memset(pRet, 0, nByte);
   112022   return pRet;
   112023 }
   112024 
   112025 
   112026 /*
   112027 ** Extract the next token from buffer z (length n) using the tokenizer
   112028 ** and other information (column names etc.) in pParse. Create an Fts3Expr
   112029 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
   112030 ** single token and set *ppExpr to point to it. If the end of the buffer is
   112031 ** reached before a token is found, set *ppExpr to zero. It is the
   112032 ** responsibility of the caller to eventually deallocate the allocated
   112033 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
   112034 **
   112035 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
   112036 ** fails.
   112037 */
   112038 static int getNextToken(
   112039   ParseContext *pParse,                   /* fts3 query parse context */
   112040   int iCol,                               /* Value for Fts3Phrase.iColumn */
   112041   const char *z, int n,                   /* Input string */
   112042   Fts3Expr **ppExpr,                      /* OUT: expression */
   112043   int *pnConsumed                         /* OUT: Number of bytes consumed */
   112044 ){
   112045   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   112046   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   112047   int rc;
   112048   sqlite3_tokenizer_cursor *pCursor;
   112049   Fts3Expr *pRet = 0;
   112050   int nConsumed = 0;
   112051 
   112052   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
   112053   if( rc==SQLITE_OK ){
   112054     const char *zToken;
   112055     int nToken, iStart, iEnd, iPosition;
   112056     int nByte;                               /* total space to allocate */
   112057 
   112058     pCursor->pTokenizer = pTokenizer;
   112059     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
   112060 
   112061     if( rc==SQLITE_OK ){
   112062       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
   112063       pRet = (Fts3Expr *)fts3MallocZero(nByte);
   112064       if( !pRet ){
   112065         rc = SQLITE_NOMEM;
   112066       }else{
   112067         pRet->eType = FTSQUERY_PHRASE;
   112068         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
   112069         pRet->pPhrase->nToken = 1;
   112070         pRet->pPhrase->iColumn = iCol;
   112071         pRet->pPhrase->aToken[0].n = nToken;
   112072         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
   112073         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
   112074 
   112075         if( iEnd<n && z[iEnd]=='*' ){
   112076           pRet->pPhrase->aToken[0].isPrefix = 1;
   112077           iEnd++;
   112078         }
   112079         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
   112080           pRet->pPhrase->isNot = 1;
   112081         }
   112082       }
   112083       nConsumed = iEnd;
   112084     }
   112085 
   112086     pModule->xClose(pCursor);
   112087   }
   112088 
   112089   *pnConsumed = nConsumed;
   112090   *ppExpr = pRet;
   112091   return rc;
   112092 }
   112093 
   112094 
   112095 /*
   112096 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
   112097 ** then free the old allocation.
   112098 */
   112099 static void *fts3ReallocOrFree(void *pOrig, int nNew){
   112100   void *pRet = sqlite3_realloc(pOrig, nNew);
   112101   if( !pRet ){
   112102     sqlite3_free(pOrig);
   112103   }
   112104   return pRet;
   112105 }
   112106 
   112107 /*
   112108 ** Buffer zInput, length nInput, contains the contents of a quoted string
   112109 ** that appeared as part of an fts3 query expression. Neither quote character
   112110 ** is included in the buffer. This function attempts to tokenize the entire
   112111 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
   112112 ** containing the results.
   112113 **
   112114 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
   112115 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
   112116 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
   112117 ** to 0.
   112118 */
   112119 static int getNextString(
   112120   ParseContext *pParse,                   /* fts3 query parse context */
   112121   const char *zInput, int nInput,         /* Input string */
   112122   Fts3Expr **ppExpr                       /* OUT: expression */
   112123 ){
   112124   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
   112125   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   112126   int rc;
   112127   Fts3Expr *p = 0;
   112128   sqlite3_tokenizer_cursor *pCursor = 0;
   112129   char *zTemp = 0;
   112130   int nTemp = 0;
   112131 
   112132   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
   112133   if( rc==SQLITE_OK ){
   112134     int ii;
   112135     pCursor->pTokenizer = pTokenizer;
   112136     for(ii=0; rc==SQLITE_OK; ii++){
   112137       const char *zToken;
   112138       int nToken, iBegin, iEnd, iPos;
   112139       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
   112140       if( rc==SQLITE_OK ){
   112141         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   112142         p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
   112143         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
   112144         if( !p || !zTemp ){
   112145           goto no_mem;
   112146         }
   112147         if( ii==0 ){
   112148           memset(p, 0, nByte);
   112149           p->pPhrase = (Fts3Phrase *)&p[1];
   112150         }
   112151         p->pPhrase = (Fts3Phrase *)&p[1];
   112152         memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
   112153         p->pPhrase->nToken = ii+1;
   112154         p->pPhrase->aToken[ii].n = nToken;
   112155         memcpy(&zTemp[nTemp], zToken, nToken);
   112156         nTemp += nToken;
   112157         if( iEnd<nInput && zInput[iEnd]=='*' ){
   112158           p->pPhrase->aToken[ii].isPrefix = 1;
   112159         }else{
   112160           p->pPhrase->aToken[ii].isPrefix = 0;
   112161         }
   112162       }
   112163     }
   112164 
   112165     pModule->xClose(pCursor);
   112166     pCursor = 0;
   112167   }
   112168 
   112169   if( rc==SQLITE_DONE ){
   112170     int jj;
   112171     char *zNew = NULL;
   112172     int nNew = 0;
   112173     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
   112174     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
   112175     p = fts3ReallocOrFree(p, nByte + nTemp);
   112176     if( !p ){
   112177       goto no_mem;
   112178     }
   112179     if( zTemp ){
   112180       zNew = &(((char *)p)[nByte]);
   112181       memcpy(zNew, zTemp, nTemp);
   112182     }else{
   112183       memset(p, 0, nByte+nTemp);
   112184     }
   112185     p->pPhrase = (Fts3Phrase *)&p[1];
   112186     for(jj=0; jj<p->pPhrase->nToken; jj++){
   112187       p->pPhrase->aToken[jj].z = &zNew[nNew];
   112188       nNew += p->pPhrase->aToken[jj].n;
   112189     }
   112190     sqlite3_free(zTemp);
   112191     p->eType = FTSQUERY_PHRASE;
   112192     p->pPhrase->iColumn = pParse->iDefaultCol;
   112193     rc = SQLITE_OK;
   112194   }
   112195 
   112196   *ppExpr = p;
   112197   return rc;
   112198 no_mem:
   112199 
   112200   if( pCursor ){
   112201     pModule->xClose(pCursor);
   112202   }
   112203   sqlite3_free(zTemp);
   112204   sqlite3_free(p);
   112205   *ppExpr = 0;
   112206   return SQLITE_NOMEM;
   112207 }
   112208 
   112209 /*
   112210 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
   112211 ** call fts3ExprParse(). So this forward declaration is required.
   112212 */
   112213 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
   112214 
   112215 /*
   112216 ** The output variable *ppExpr is populated with an allocated Fts3Expr
   112217 ** structure, or set to 0 if the end of the input buffer is reached.
   112218 **
   112219 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
   112220 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
   112221 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
   112222 */
   112223 static int getNextNode(
   112224   ParseContext *pParse,                   /* fts3 query parse context */
   112225   const char *z, int n,                   /* Input string */
   112226   Fts3Expr **ppExpr,                      /* OUT: expression */
   112227   int *pnConsumed                         /* OUT: Number of bytes consumed */
   112228 ){
   112229   static const struct Fts3Keyword {
   112230     char *z;                              /* Keyword text */
   112231     unsigned char n;                      /* Length of the keyword */
   112232     unsigned char parenOnly;              /* Only valid in paren mode */
   112233     unsigned char eType;                  /* Keyword code */
   112234   } aKeyword[] = {
   112235     { "OR" ,  2, 0, FTSQUERY_OR   },
   112236     { "AND",  3, 1, FTSQUERY_AND  },
   112237     { "NOT",  3, 1, FTSQUERY_NOT  },
   112238     { "NEAR", 4, 0, FTSQUERY_NEAR }
   112239   };
   112240   int ii;
   112241   int iCol;
   112242   int iColLen;
   112243   int rc;
   112244   Fts3Expr *pRet = 0;
   112245 
   112246   const char *zInput = z;
   112247   int nInput = n;
   112248 
   112249   /* Skip over any whitespace before checking for a keyword, an open or
   112250   ** close bracket, or a quoted string.
   112251   */
   112252   while( nInput>0 && fts3isspace(*zInput) ){
   112253     nInput--;
   112254     zInput++;
   112255   }
   112256   if( nInput==0 ){
   112257     return SQLITE_DONE;
   112258   }
   112259 
   112260   /* See if we are dealing with a keyword. */
   112261   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
   112262     const struct Fts3Keyword *pKey = &aKeyword[ii];
   112263 
   112264     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
   112265       continue;
   112266     }
   112267 
   112268     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
   112269       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
   112270       int nKey = pKey->n;
   112271       char cNext;
   112272 
   112273       /* If this is a "NEAR" keyword, check for an explicit nearness. */
   112274       if( pKey->eType==FTSQUERY_NEAR ){
   112275         assert( nKey==4 );
   112276         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
   112277           nNear = 0;
   112278           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
   112279             nNear = nNear * 10 + (zInput[nKey] - '0');
   112280           }
   112281         }
   112282       }
   112283 
   112284       /* At this point this is probably a keyword. But for that to be true,
   112285       ** the next byte must contain either whitespace, an open or close
   112286       ** parenthesis, a quote character, or EOF.
   112287       */
   112288       cNext = zInput[nKey];
   112289       if( fts3isspace(cNext)
   112290        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
   112291       ){
   112292         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
   112293         if( !pRet ){
   112294           return SQLITE_NOMEM;
   112295         }
   112296         pRet->eType = pKey->eType;
   112297         pRet->nNear = nNear;
   112298         *ppExpr = pRet;
   112299         *pnConsumed = (int)((zInput - z) + nKey);
   112300         return SQLITE_OK;
   112301       }
   112302 
   112303       /* Turns out that wasn't a keyword after all. This happens if the
   112304       ** user has supplied a token such as "ORacle". Continue.
   112305       */
   112306     }
   112307   }
   112308 
   112309   /* Check for an open bracket. */
   112310   if( sqlite3_fts3_enable_parentheses ){
   112311     if( *zInput=='(' ){
   112312       int nConsumed;
   112313       pParse->nNest++;
   112314       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
   112315       if( rc==SQLITE_OK && !*ppExpr ){
   112316         rc = SQLITE_DONE;
   112317       }
   112318       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
   112319       return rc;
   112320     }
   112321 
   112322     /* Check for a close bracket. */
   112323     if( *zInput==')' ){
   112324       pParse->nNest--;
   112325       *pnConsumed = (int)((zInput - z) + 1);
   112326       return SQLITE_DONE;
   112327     }
   112328   }
   112329 
   112330   /* See if we are dealing with a quoted phrase. If this is the case, then
   112331   ** search for the closing quote and pass the whole string to getNextString()
   112332   ** for processing. This is easy to do, as fts3 has no syntax for escaping
   112333   ** a quote character embedded in a string.
   112334   */
   112335   if( *zInput=='"' ){
   112336     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
   112337     *pnConsumed = (int)((zInput - z) + ii + 1);
   112338     if( ii==nInput ){
   112339       return SQLITE_ERROR;
   112340     }
   112341     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
   112342   }
   112343 
   112344 
   112345   /* If control flows to this point, this must be a regular token, or
   112346   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   112347   ** interface. Before doing so, figure out if there is an explicit
   112348   ** column specifier for the token.
   112349   **
   112350   ** TODO: Strangely, it is not possible to associate a column specifier
   112351   ** with a quoted phrase, only with a single token. Not sure if this was
   112352   ** an implementation artifact or an intentional decision when fts3 was
   112353   ** first implemented. Whichever it was, this module duplicates the
   112354   ** limitation.
   112355   */
   112356   iCol = pParse->iDefaultCol;
   112357   iColLen = 0;
   112358   for(ii=0; ii<pParse->nCol; ii++){
   112359     const char *zStr = pParse->azCol[ii];
   112360     int nStr = (int)strlen(zStr);
   112361     if( nInput>nStr && zInput[nStr]==':'
   112362      && sqlite3_strnicmp(zStr, zInput, nStr)==0
   112363     ){
   112364       iCol = ii;
   112365       iColLen = (int)((zInput - z) + nStr + 1);
   112366       break;
   112367     }
   112368   }
   112369   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
   112370   *pnConsumed += iColLen;
   112371   return rc;
   112372 }
   112373 
   112374 /*
   112375 ** The argument is an Fts3Expr structure for a binary operator (any type
   112376 ** except an FTSQUERY_PHRASE). Return an integer value representing the
   112377 ** precedence of the operator. Lower values have a higher precedence (i.e.
   112378 ** group more tightly). For example, in the C language, the == operator
   112379 ** groups more tightly than ||, and would therefore have a higher precedence.
   112380 **
   112381 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
   112382 ** is defined), the order of the operators in precedence from highest to
   112383 ** lowest is:
   112384 **
   112385 **   NEAR
   112386 **   NOT
   112387 **   AND (including implicit ANDs)
   112388 **   OR
   112389 **
   112390 ** Note that when using the old query syntax, the OR operator has a higher
   112391 ** precedence than the AND operator.
   112392 */
   112393 static int opPrecedence(Fts3Expr *p){
   112394   assert( p->eType!=FTSQUERY_PHRASE );
   112395   if( sqlite3_fts3_enable_parentheses ){
   112396     return p->eType;
   112397   }else if( p->eType==FTSQUERY_NEAR ){
   112398     return 1;
   112399   }else if( p->eType==FTSQUERY_OR ){
   112400     return 2;
   112401   }
   112402   assert( p->eType==FTSQUERY_AND );
   112403   return 3;
   112404 }
   112405 
   112406 /*
   112407 ** Argument ppHead contains a pointer to the current head of a query
   112408 ** expression tree being parsed. pPrev is the expression node most recently
   112409 ** inserted into the tree. This function adds pNew, which is always a binary
   112410 ** operator node, into the expression tree based on the relative precedence
   112411 ** of pNew and the existing nodes of the tree. This may result in the head
   112412 ** of the tree changing, in which case *ppHead is set to the new root node.
   112413 */
   112414 static void insertBinaryOperator(
   112415   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
   112416   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
   112417   Fts3Expr *pNew           /* New binary node to insert into expression tree */
   112418 ){
   112419   Fts3Expr *pSplit = pPrev;
   112420   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
   112421     pSplit = pSplit->pParent;
   112422   }
   112423 
   112424   if( pSplit->pParent ){
   112425     assert( pSplit->pParent->pRight==pSplit );
   112426     pSplit->pParent->pRight = pNew;
   112427     pNew->pParent = pSplit->pParent;
   112428   }else{
   112429     *ppHead = pNew;
   112430   }
   112431   pNew->pLeft = pSplit;
   112432   pSplit->pParent = pNew;
   112433 }
   112434 
   112435 /*
   112436 ** Parse the fts3 query expression found in buffer z, length n. This function
   112437 ** returns either when the end of the buffer is reached or an unmatched
   112438 ** closing bracket - ')' - is encountered.
   112439 **
   112440 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
   112441 ** parsed form of the expression and *pnConsumed is set to the number of
   112442 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
   112443 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
   112444 */
   112445 static int fts3ExprParse(
   112446   ParseContext *pParse,                   /* fts3 query parse context */
   112447   const char *z, int n,                   /* Text of MATCH query */
   112448   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
   112449   int *pnConsumed                         /* OUT: Number of bytes consumed */
   112450 ){
   112451   Fts3Expr *pRet = 0;
   112452   Fts3Expr *pPrev = 0;
   112453   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
   112454   int nIn = n;
   112455   const char *zIn = z;
   112456   int rc = SQLITE_OK;
   112457   int isRequirePhrase = 1;
   112458 
   112459   while( rc==SQLITE_OK ){
   112460     Fts3Expr *p = 0;
   112461     int nByte = 0;
   112462     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
   112463     if( rc==SQLITE_OK ){
   112464       int isPhrase;
   112465 
   112466       if( !sqlite3_fts3_enable_parentheses
   112467        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
   112468       ){
   112469         /* Create an implicit NOT operator. */
   112470         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
   112471         if( !pNot ){
   112472           sqlite3Fts3ExprFree(p);
   112473           rc = SQLITE_NOMEM;
   112474           goto exprparse_out;
   112475         }
   112476         pNot->eType = FTSQUERY_NOT;
   112477         pNot->pRight = p;
   112478         if( pNotBranch ){
   112479           pNot->pLeft = pNotBranch;
   112480         }
   112481         pNotBranch = pNot;
   112482         p = pPrev;
   112483       }else{
   112484         int eType = p->eType;
   112485         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
   112486         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
   112487 
   112488         /* The isRequirePhrase variable is set to true if a phrase or
   112489         ** an expression contained in parenthesis is required. If a
   112490         ** binary operator (AND, OR, NOT or NEAR) is encounted when
   112491         ** isRequirePhrase is set, this is a syntax error.
   112492         */
   112493         if( !isPhrase && isRequirePhrase ){
   112494           sqlite3Fts3ExprFree(p);
   112495           rc = SQLITE_ERROR;
   112496           goto exprparse_out;
   112497         }
   112498 
   112499         if( isPhrase && !isRequirePhrase ){
   112500           /* Insert an implicit AND operator. */
   112501           Fts3Expr *pAnd;
   112502           assert( pRet && pPrev );
   112503           pAnd = fts3MallocZero(sizeof(Fts3Expr));
   112504           if( !pAnd ){
   112505             sqlite3Fts3ExprFree(p);
   112506             rc = SQLITE_NOMEM;
   112507             goto exprparse_out;
   112508           }
   112509           pAnd->eType = FTSQUERY_AND;
   112510           insertBinaryOperator(&pRet, pPrev, pAnd);
   112511           pPrev = pAnd;
   112512         }
   112513 
   112514         /* This test catches attempts to make either operand of a NEAR
   112515         ** operator something other than a phrase. For example, either of
   112516         ** the following:
   112517         **
   112518         **    (bracketed expression) NEAR phrase
   112519         **    phrase NEAR (bracketed expression)
   112520         **
   112521         ** Return an error in either case.
   112522         */
   112523         if( pPrev && (
   112524             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
   112525          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
   112526         )){
   112527           sqlite3Fts3ExprFree(p);
   112528           rc = SQLITE_ERROR;
   112529           goto exprparse_out;
   112530         }
   112531 
   112532         if( isPhrase ){
   112533           if( pRet ){
   112534             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
   112535             pPrev->pRight = p;
   112536             p->pParent = pPrev;
   112537           }else{
   112538             pRet = p;
   112539           }
   112540         }else{
   112541           insertBinaryOperator(&pRet, pPrev, p);
   112542         }
   112543         isRequirePhrase = !isPhrase;
   112544       }
   112545       assert( nByte>0 );
   112546     }
   112547     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
   112548     nIn -= nByte;
   112549     zIn += nByte;
   112550     pPrev = p;
   112551   }
   112552 
   112553   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
   112554     rc = SQLITE_ERROR;
   112555   }
   112556 
   112557   if( rc==SQLITE_DONE ){
   112558     rc = SQLITE_OK;
   112559     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
   112560       if( !pRet ){
   112561         rc = SQLITE_ERROR;
   112562       }else{
   112563         Fts3Expr *pIter = pNotBranch;
   112564         while( pIter->pLeft ){
   112565           pIter = pIter->pLeft;
   112566         }
   112567         pIter->pLeft = pRet;
   112568         pRet = pNotBranch;
   112569       }
   112570     }
   112571   }
   112572   *pnConsumed = n - nIn;
   112573 
   112574 exprparse_out:
   112575   if( rc!=SQLITE_OK ){
   112576     sqlite3Fts3ExprFree(pRet);
   112577     sqlite3Fts3ExprFree(pNotBranch);
   112578     pRet = 0;
   112579   }
   112580   *ppExpr = pRet;
   112581   return rc;
   112582 }
   112583 
   112584 /*
   112585 ** Parameters z and n contain a pointer to and length of a buffer containing
   112586 ** an fts3 query expression, respectively. This function attempts to parse the
   112587 ** query expression and create a tree of Fts3Expr structures representing the
   112588 ** parsed expression. If successful, *ppExpr is set to point to the head
   112589 ** of the parsed expression tree and SQLITE_OK is returned. If an error
   112590 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
   112591 ** error) is returned and *ppExpr is set to 0.
   112592 **
   112593 ** If parameter n is a negative number, then z is assumed to point to a
   112594 ** nul-terminated string and the length is determined using strlen().
   112595 **
   112596 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
   112597 ** use to normalize query tokens while parsing the expression. The azCol[]
   112598 ** array, which is assumed to contain nCol entries, should contain the names
   112599 ** of each column in the target fts3 table, in order from left to right.
   112600 ** Column names must be nul-terminated strings.
   112601 **
   112602 ** The iDefaultCol parameter should be passed the index of the table column
   112603 ** that appears on the left-hand-side of the MATCH operator (the default
   112604 ** column to match against for tokens for which a column name is not explicitly
   112605 ** specified as part of the query string), or -1 if tokens may by default
   112606 ** match any table column.
   112607 */
   112608 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   112609   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
   112610   char **azCol,                       /* Array of column names for fts3 table */
   112611   int nCol,                           /* Number of entries in azCol[] */
   112612   int iDefaultCol,                    /* Default column to query */
   112613   const char *z, int n,               /* Text of MATCH query */
   112614   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
   112615 ){
   112616   int nParsed;
   112617   int rc;
   112618   ParseContext sParse;
   112619   sParse.pTokenizer = pTokenizer;
   112620   sParse.azCol = (const char **)azCol;
   112621   sParse.nCol = nCol;
   112622   sParse.iDefaultCol = iDefaultCol;
   112623   sParse.nNest = 0;
   112624   if( z==0 ){
   112625     *ppExpr = 0;
   112626     return SQLITE_OK;
   112627   }
   112628   if( n<0 ){
   112629     n = (int)strlen(z);
   112630   }
   112631   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
   112632 
   112633   /* Check for mismatched parenthesis */
   112634   if( rc==SQLITE_OK && sParse.nNest ){
   112635     rc = SQLITE_ERROR;
   112636     sqlite3Fts3ExprFree(*ppExpr);
   112637     *ppExpr = 0;
   112638   }
   112639 
   112640   return rc;
   112641 }
   112642 
   112643 /*
   112644 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
   112645 */
   112646 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
   112647   if( p ){
   112648     sqlite3Fts3ExprFree(p->pLeft);
   112649     sqlite3Fts3ExprFree(p->pRight);
   112650     sqlite3_free(p->aDoclist);
   112651     sqlite3_free(p);
   112652   }
   112653 }
   112654 
   112655 /****************************************************************************
   112656 *****************************************************************************
   112657 ** Everything after this point is just test code.
   112658 */
   112659 
   112660 #ifdef SQLITE_TEST
   112661 
   112662 
   112663 /*
   112664 ** Function to query the hash-table of tokenizers (see README.tokenizers).
   112665 */
   112666 static int queryTestTokenizer(
   112667   sqlite3 *db,
   112668   const char *zName,
   112669   const sqlite3_tokenizer_module **pp
   112670 ){
   112671   int rc;
   112672   sqlite3_stmt *pStmt;
   112673   const char zSql[] = "SELECT fts3_tokenizer(?)";
   112674 
   112675   *pp = 0;
   112676   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   112677   if( rc!=SQLITE_OK ){
   112678     return rc;
   112679   }
   112680 
   112681   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   112682   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   112683     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   112684       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   112685     }
   112686   }
   112687 
   112688   return sqlite3_finalize(pStmt);
   112689 }
   112690 
   112691 /*
   112692 ** Return a pointer to a buffer containing a text representation of the
   112693 ** expression passed as the first argument. The buffer is obtained from
   112694 ** sqlite3_malloc(). It is the responsibility of the caller to use
   112695 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
   112696 ** NULL is returned.
   112697 **
   112698 ** If the second argument is not NULL, then its contents are prepended to
   112699 ** the returned expression text and then freed using sqlite3_free().
   112700 */
   112701 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
   112702   switch( pExpr->eType ){
   112703     case FTSQUERY_PHRASE: {
   112704       Fts3Phrase *pPhrase = pExpr->pPhrase;
   112705       int i;
   112706       zBuf = sqlite3_mprintf(
   112707           "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
   112708       for(i=0; zBuf && i<pPhrase->nToken; i++){
   112709         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
   112710             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
   112711             (pPhrase->aToken[i].isPrefix?"+":"")
   112712         );
   112713       }
   112714       return zBuf;
   112715     }
   112716 
   112717     case FTSQUERY_NEAR:
   112718       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
   112719       break;
   112720     case FTSQUERY_NOT:
   112721       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
   112722       break;
   112723     case FTSQUERY_AND:
   112724       zBuf = sqlite3_mprintf("%zAND ", zBuf);
   112725       break;
   112726     case FTSQUERY_OR:
   112727       zBuf = sqlite3_mprintf("%zOR ", zBuf);
   112728       break;
   112729   }
   112730 
   112731   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
   112732   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
   112733   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
   112734 
   112735   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
   112736   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
   112737 
   112738   return zBuf;
   112739 }
   112740 
   112741 /*
   112742 ** This is the implementation of a scalar SQL function used to test the
   112743 ** expression parser. It should be called as follows:
   112744 **
   112745 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
   112746 **
   112747 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
   112748 ** to parse the query expression (see README.tokenizers). The second argument
   112749 ** is the query expression to parse. Each subsequent argument is the name
   112750 ** of a column of the fts3 table that the query expression may refer to.
   112751 ** For example:
   112752 **
   112753 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
   112754 */
   112755 static void fts3ExprTest(
   112756   sqlite3_context *context,
   112757   int argc,
   112758   sqlite3_value **argv
   112759 ){
   112760   sqlite3_tokenizer_module const *pModule = 0;
   112761   sqlite3_tokenizer *pTokenizer = 0;
   112762   int rc;
   112763   char **azCol = 0;
   112764   const char *zExpr;
   112765   int nExpr;
   112766   int nCol;
   112767   int ii;
   112768   Fts3Expr *pExpr;
   112769   char *zBuf = 0;
   112770   sqlite3 *db = sqlite3_context_db_handle(context);
   112771 
   112772   if( argc<3 ){
   112773     sqlite3_result_error(context,
   112774         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
   112775     );
   112776     return;
   112777   }
   112778 
   112779   rc = queryTestTokenizer(db,
   112780                           (const char *)sqlite3_value_text(argv[0]), &pModule);
   112781   if( rc==SQLITE_NOMEM ){
   112782     sqlite3_result_error_nomem(context);
   112783     goto exprtest_out;
   112784   }else if( !pModule ){
   112785     sqlite3_result_error(context, "No such tokenizer module", -1);
   112786     goto exprtest_out;
   112787   }
   112788 
   112789   rc = pModule->xCreate(0, 0, &pTokenizer);
   112790   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
   112791   if( rc==SQLITE_NOMEM ){
   112792     sqlite3_result_error_nomem(context);
   112793     goto exprtest_out;
   112794   }
   112795   pTokenizer->pModule = pModule;
   112796 
   112797   zExpr = (const char *)sqlite3_value_text(argv[1]);
   112798   nExpr = sqlite3_value_bytes(argv[1]);
   112799   nCol = argc-2;
   112800   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
   112801   if( !azCol ){
   112802     sqlite3_result_error_nomem(context);
   112803     goto exprtest_out;
   112804   }
   112805   for(ii=0; ii<nCol; ii++){
   112806     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
   112807   }
   112808 
   112809   rc = sqlite3Fts3ExprParse(
   112810       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
   112811   );
   112812   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
   112813     sqlite3_result_error(context, "Error parsing expression", -1);
   112814   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
   112815     sqlite3_result_error_nomem(context);
   112816   }else{
   112817     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   112818     sqlite3_free(zBuf);
   112819   }
   112820 
   112821   sqlite3Fts3ExprFree(pExpr);
   112822 
   112823 exprtest_out:
   112824   if( pModule && pTokenizer ){
   112825     rc = pModule->xDestroy(pTokenizer);
   112826   }
   112827   sqlite3_free(azCol);
   112828 }
   112829 
   112830 /*
   112831 ** Register the query expression parser test function fts3_exprtest()
   112832 ** with database connection db.
   112833 */
   112834 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
   112835   return sqlite3_create_function(
   112836       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
   112837   );
   112838 }
   112839 
   112840 #endif
   112841 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   112842 
   112843 /************** End of fts3_expr.c *******************************************/
   112844 /************** Begin file fts3_hash.c ***************************************/
   112845 /*
   112846 ** 2001 September 22
   112847 **
   112848 ** The author disclaims copyright to this source code.  In place of
   112849 ** a legal notice, here is a blessing:
   112850 **
   112851 **    May you do good and not evil.
   112852 **    May you find forgiveness for yourself and forgive others.
   112853 **    May you share freely, never taking more than you give.
   112854 **
   112855 *************************************************************************
   112856 ** This is the implementation of generic hash-tables used in SQLite.
   112857 ** We've modified it slightly to serve as a standalone hash table
   112858 ** implementation for the full-text indexing module.
   112859 */
   112860 
   112861 /*
   112862 ** The code in this file is only compiled if:
   112863 **
   112864 **     * The FTS3 module is being built as an extension
   112865 **       (in which case SQLITE_CORE is not defined), or
   112866 **
   112867 **     * The FTS3 module is being built into the core of
   112868 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   112869 */
   112870 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   112871 
   112872 
   112873 
   112874 /*
   112875 ** Malloc and Free functions
   112876 */
   112877 static void *fts3HashMalloc(int n){
   112878   void *p = sqlite3_malloc(n);
   112879   if( p ){
   112880     memset(p, 0, n);
   112881   }
   112882   return p;
   112883 }
   112884 static void fts3HashFree(void *p){
   112885   sqlite3_free(p);
   112886 }
   112887 
   112888 /* Turn bulk memory into a hash table object by initializing the
   112889 ** fields of the Hash structure.
   112890 **
   112891 ** "pNew" is a pointer to the hash table that is to be initialized.
   112892 ** keyClass is one of the constants
   112893 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
   112894 ** determines what kind of key the hash table will use.  "copyKey" is
   112895 ** true if the hash table should make its own private copy of keys and
   112896 ** false if it should just use the supplied pointer.
   112897 */
   112898 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
   112899   assert( pNew!=0 );
   112900   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
   112901   pNew->keyClass = keyClass;
   112902   pNew->copyKey = copyKey;
   112903   pNew->first = 0;
   112904   pNew->count = 0;
   112905   pNew->htsize = 0;
   112906   pNew->ht = 0;
   112907 }
   112908 
   112909 /* Remove all entries from a hash table.  Reclaim all memory.
   112910 ** Call this routine to delete a hash table or to reset a hash table
   112911 ** to the empty state.
   112912 */
   112913 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
   112914   Fts3HashElem *elem;         /* For looping over all elements of the table */
   112915 
   112916   assert( pH!=0 );
   112917   elem = pH->first;
   112918   pH->first = 0;
   112919   fts3HashFree(pH->ht);
   112920   pH->ht = 0;
   112921   pH->htsize = 0;
   112922   while( elem ){
   112923     Fts3HashElem *next_elem = elem->next;
   112924     if( pH->copyKey && elem->pKey ){
   112925       fts3HashFree(elem->pKey);
   112926     }
   112927     fts3HashFree(elem);
   112928     elem = next_elem;
   112929   }
   112930   pH->count = 0;
   112931 }
   112932 
   112933 /*
   112934 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
   112935 */
   112936 static int fts3StrHash(const void *pKey, int nKey){
   112937   const char *z = (const char *)pKey;
   112938   int h = 0;
   112939   if( nKey<=0 ) nKey = (int) strlen(z);
   112940   while( nKey > 0  ){
   112941     h = (h<<3) ^ h ^ *z++;
   112942     nKey--;
   112943   }
   112944   return h & 0x7fffffff;
   112945 }
   112946 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   112947   if( n1!=n2 ) return 1;
   112948   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
   112949 }
   112950 
   112951 /*
   112952 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
   112953 */
   112954 static int fts3BinHash(const void *pKey, int nKey){
   112955   int h = 0;
   112956   const char *z = (const char *)pKey;
   112957   while( nKey-- > 0 ){
   112958     h = (h<<3) ^ h ^ *(z++);
   112959   }
   112960   return h & 0x7fffffff;
   112961 }
   112962 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
   112963   if( n1!=n2 ) return 1;
   112964   return memcmp(pKey1,pKey2,n1);
   112965 }
   112966 
   112967 /*
   112968 ** Return a pointer to the appropriate hash function given the key class.
   112969 **
   112970 ** The C syntax in this function definition may be unfamilar to some
   112971 ** programmers, so we provide the following additional explanation:
   112972 **
   112973 ** The name of the function is "ftsHashFunction".  The function takes a
   112974 ** single parameter "keyClass".  The return value of ftsHashFunction()
   112975 ** is a pointer to another function.  Specifically, the return value
   112976 ** of ftsHashFunction() is a pointer to a function that takes two parameters
   112977 ** with types "const void*" and "int" and returns an "int".
   112978 */
   112979 static int (*ftsHashFunction(int keyClass))(const void*,int){
   112980   if( keyClass==FTS3_HASH_STRING ){
   112981     return &fts3StrHash;
   112982   }else{
   112983     assert( keyClass==FTS3_HASH_BINARY );
   112984     return &fts3BinHash;
   112985   }
   112986 }
   112987 
   112988 /*
   112989 ** Return a pointer to the appropriate hash function given the key class.
   112990 **
   112991 ** For help in interpreted the obscure C code in the function definition,
   112992 ** see the header comment on the previous function.
   112993 */
   112994 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
   112995   if( keyClass==FTS3_HASH_STRING ){
   112996     return &fts3StrCompare;
   112997   }else{
   112998     assert( keyClass==FTS3_HASH_BINARY );
   112999     return &fts3BinCompare;
   113000   }
   113001 }
   113002 
   113003 /* Link an element into the hash table
   113004 */
   113005 static void fts3HashInsertElement(
   113006   Fts3Hash *pH,            /* The complete hash table */
   113007   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
   113008   Fts3HashElem *pNew       /* The element to be inserted */
   113009 ){
   113010   Fts3HashElem *pHead;     /* First element already in pEntry */
   113011   pHead = pEntry->chain;
   113012   if( pHead ){
   113013     pNew->next = pHead;
   113014     pNew->prev = pHead->prev;
   113015     if( pHead->prev ){ pHead->prev->next = pNew; }
   113016     else             { pH->first = pNew; }
   113017     pHead->prev = pNew;
   113018   }else{
   113019     pNew->next = pH->first;
   113020     if( pH->first ){ pH->first->prev = pNew; }
   113021     pNew->prev = 0;
   113022     pH->first = pNew;
   113023   }
   113024   pEntry->count++;
   113025   pEntry->chain = pNew;
   113026 }
   113027 
   113028 
   113029 /* Resize the hash table so that it cantains "new_size" buckets.
   113030 ** "new_size" must be a power of 2.  The hash table might fail
   113031 ** to resize if sqliteMalloc() fails.
   113032 **
   113033 ** Return non-zero if a memory allocation error occurs.
   113034 */
   113035 static int fts3Rehash(Fts3Hash *pH, int new_size){
   113036   struct _fts3ht *new_ht;          /* The new hash table */
   113037   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
   113038   int (*xHash)(const void*,int);   /* The hash function */
   113039 
   113040   assert( (new_size & (new_size-1))==0 );
   113041   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
   113042   if( new_ht==0 ) return 1;
   113043   fts3HashFree(pH->ht);
   113044   pH->ht = new_ht;
   113045   pH->htsize = new_size;
   113046   xHash = ftsHashFunction(pH->keyClass);
   113047   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
   113048     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
   113049     next_elem = elem->next;
   113050     fts3HashInsertElement(pH, &new_ht[h], elem);
   113051   }
   113052   return 0;
   113053 }
   113054 
   113055 /* This function (for internal use only) locates an element in an
   113056 ** hash table that matches the given key.  The hash for this key has
   113057 ** already been computed and is passed as the 4th parameter.
   113058 */
   113059 static Fts3HashElem *fts3FindElementByHash(
   113060   const Fts3Hash *pH, /* The pH to be searched */
   113061   const void *pKey,   /* The key we are searching for */
   113062   int nKey,
   113063   int h               /* The hash for this key. */
   113064 ){
   113065   Fts3HashElem *elem;            /* Used to loop thru the element list */
   113066   int count;                     /* Number of elements left to test */
   113067   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
   113068 
   113069   if( pH->ht ){
   113070     struct _fts3ht *pEntry = &pH->ht[h];
   113071     elem = pEntry->chain;
   113072     count = pEntry->count;
   113073     xCompare = ftsCompareFunction(pH->keyClass);
   113074     while( count-- && elem ){
   113075       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
   113076         return elem;
   113077       }
   113078       elem = elem->next;
   113079     }
   113080   }
   113081   return 0;
   113082 }
   113083 
   113084 /* Remove a single entry from the hash table given a pointer to that
   113085 ** element and a hash on the element's key.
   113086 */
   113087 static void fts3RemoveElementByHash(
   113088   Fts3Hash *pH,         /* The pH containing "elem" */
   113089   Fts3HashElem* elem,   /* The element to be removed from the pH */
   113090   int h                 /* Hash value for the element */
   113091 ){
   113092   struct _fts3ht *pEntry;
   113093   if( elem->prev ){
   113094     elem->prev->next = elem->next;
   113095   }else{
   113096     pH->first = elem->next;
   113097   }
   113098   if( elem->next ){
   113099     elem->next->prev = elem->prev;
   113100   }
   113101   pEntry = &pH->ht[h];
   113102   if( pEntry->chain==elem ){
   113103     pEntry->chain = elem->next;
   113104   }
   113105   pEntry->count--;
   113106   if( pEntry->count<=0 ){
   113107     pEntry->chain = 0;
   113108   }
   113109   if( pH->copyKey && elem->pKey ){
   113110     fts3HashFree(elem->pKey);
   113111   }
   113112   fts3HashFree( elem );
   113113   pH->count--;
   113114   if( pH->count<=0 ){
   113115     assert( pH->first==0 );
   113116     assert( pH->count==0 );
   113117     fts3HashClear(pH);
   113118   }
   113119 }
   113120 
   113121 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   113122   const Fts3Hash *pH,
   113123   const void *pKey,
   113124   int nKey
   113125 ){
   113126   int h;                          /* A hash on key */
   113127   int (*xHash)(const void*,int);  /* The hash function */
   113128 
   113129   if( pH==0 || pH->ht==0 ) return 0;
   113130   xHash = ftsHashFunction(pH->keyClass);
   113131   assert( xHash!=0 );
   113132   h = (*xHash)(pKey,nKey);
   113133   assert( (pH->htsize & (pH->htsize-1))==0 );
   113134   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
   113135 }
   113136 
   113137 /*
   113138 ** Attempt to locate an element of the hash table pH with a key
   113139 ** that matches pKey,nKey.  Return the data for this element if it is
   113140 ** found, or NULL if there is no match.
   113141 */
   113142 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
   113143   Fts3HashElem *pElem;            /* The element that matches key (if any) */
   113144 
   113145   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
   113146   return pElem ? pElem->data : 0;
   113147 }
   113148 
   113149 /* Insert an element into the hash table pH.  The key is pKey,nKey
   113150 ** and the data is "data".
   113151 **
   113152 ** If no element exists with a matching key, then a new
   113153 ** element is created.  A copy of the key is made if the copyKey
   113154 ** flag is set.  NULL is returned.
   113155 **
   113156 ** If another element already exists with the same key, then the
   113157 ** new data replaces the old data and the old data is returned.
   113158 ** The key is not copied in this instance.  If a malloc fails, then
   113159 ** the new data is returned and the hash table is unchanged.
   113160 **
   113161 ** If the "data" parameter to this function is NULL, then the
   113162 ** element corresponding to "key" is removed from the hash table.
   113163 */
   113164 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
   113165   Fts3Hash *pH,        /* The hash table to insert into */
   113166   const void *pKey,    /* The key */
   113167   int nKey,            /* Number of bytes in the key */
   113168   void *data           /* The data */
   113169 ){
   113170   int hraw;                 /* Raw hash value of the key */
   113171   int h;                    /* the hash of the key modulo hash table size */
   113172   Fts3HashElem *elem;       /* Used to loop thru the element list */
   113173   Fts3HashElem *new_elem;   /* New element added to the pH */
   113174   int (*xHash)(const void*,int);  /* The hash function */
   113175 
   113176   assert( pH!=0 );
   113177   xHash = ftsHashFunction(pH->keyClass);
   113178   assert( xHash!=0 );
   113179   hraw = (*xHash)(pKey, nKey);
   113180   assert( (pH->htsize & (pH->htsize-1))==0 );
   113181   h = hraw & (pH->htsize-1);
   113182   elem = fts3FindElementByHash(pH,pKey,nKey,h);
   113183   if( elem ){
   113184     void *old_data = elem->data;
   113185     if( data==0 ){
   113186       fts3RemoveElementByHash(pH,elem,h);
   113187     }else{
   113188       elem->data = data;
   113189     }
   113190     return old_data;
   113191   }
   113192   if( data==0 ) return 0;
   113193   if( (pH->htsize==0 && fts3Rehash(pH,8))
   113194    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
   113195   ){
   113196     pH->count = 0;
   113197     return data;
   113198   }
   113199   assert( pH->htsize>0 );
   113200   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
   113201   if( new_elem==0 ) return data;
   113202   if( pH->copyKey && pKey!=0 ){
   113203     new_elem->pKey = fts3HashMalloc( nKey );
   113204     if( new_elem->pKey==0 ){
   113205       fts3HashFree(new_elem);
   113206       return data;
   113207     }
   113208     memcpy((void*)new_elem->pKey, pKey, nKey);
   113209   }else{
   113210     new_elem->pKey = (void*)pKey;
   113211   }
   113212   new_elem->nKey = nKey;
   113213   pH->count++;
   113214   assert( pH->htsize>0 );
   113215   assert( (pH->htsize & (pH->htsize-1))==0 );
   113216   h = hraw & (pH->htsize-1);
   113217   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
   113218   new_elem->data = data;
   113219   return 0;
   113220 }
   113221 
   113222 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   113223 
   113224 /************** End of fts3_hash.c *******************************************/
   113225 /************** Begin file fts3_porter.c *************************************/
   113226 /*
   113227 ** 2006 September 30
   113228 **
   113229 ** The author disclaims copyright to this source code.  In place of
   113230 ** a legal notice, here is a blessing:
   113231 **
   113232 **    May you do good and not evil.
   113233 **    May you find forgiveness for yourself and forgive others.
   113234 **    May you share freely, never taking more than you give.
   113235 **
   113236 *************************************************************************
   113237 ** Implementation of the full-text-search tokenizer that implements
   113238 ** a Porter stemmer.
   113239 */
   113240 
   113241 /*
   113242 ** The code in this file is only compiled if:
   113243 **
   113244 **     * The FTS3 module is being built as an extension
   113245 **       (in which case SQLITE_CORE is not defined), or
   113246 **
   113247 **     * The FTS3 module is being built into the core of
   113248 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   113249 */
   113250 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   113251 
   113252 
   113253 
   113254 
   113255 /*
   113256 ** Class derived from sqlite3_tokenizer
   113257 */
   113258 typedef struct porter_tokenizer {
   113259   sqlite3_tokenizer base;      /* Base class */
   113260 } porter_tokenizer;
   113261 
   113262 /*
   113263 ** Class derived from sqlit3_tokenizer_cursor
   113264 */
   113265 typedef struct porter_tokenizer_cursor {
   113266   sqlite3_tokenizer_cursor base;
   113267   const char *zInput;          /* input we are tokenizing */
   113268   int nInput;                  /* size of the input */
   113269   int iOffset;                 /* current position in zInput */
   113270   int iToken;                  /* index of next token to be returned */
   113271   char *zToken;                /* storage for current token */
   113272   int nAllocated;              /* space allocated to zToken buffer */
   113273 } porter_tokenizer_cursor;
   113274 
   113275 
   113276 /*
   113277 ** Create a new tokenizer instance.
   113278 */
   113279 static int porterCreate(
   113280   int argc, const char * const *argv,
   113281   sqlite3_tokenizer **ppTokenizer
   113282 ){
   113283   porter_tokenizer *t;
   113284 
   113285   UNUSED_PARAMETER(argc);
   113286   UNUSED_PARAMETER(argv);
   113287 
   113288   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
   113289   if( t==NULL ) return SQLITE_NOMEM;
   113290   memset(t, 0, sizeof(*t));
   113291   *ppTokenizer = &t->base;
   113292   return SQLITE_OK;
   113293 }
   113294 
   113295 /*
   113296 ** Destroy a tokenizer
   113297 */
   113298 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
   113299   sqlite3_free(pTokenizer);
   113300   return SQLITE_OK;
   113301 }
   113302 
   113303 /*
   113304 ** Prepare to begin tokenizing a particular string.  The input
   113305 ** string to be tokenized is zInput[0..nInput-1].  A cursor
   113306 ** used to incrementally tokenize this string is returned in
   113307 ** *ppCursor.
   113308 */
   113309 static int porterOpen(
   113310   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   113311   const char *zInput, int nInput,        /* String to be tokenized */
   113312   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   113313 ){
   113314   porter_tokenizer_cursor *c;
   113315 
   113316   UNUSED_PARAMETER(pTokenizer);
   113317 
   113318   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   113319   if( c==NULL ) return SQLITE_NOMEM;
   113320 
   113321   c->zInput = zInput;
   113322   if( zInput==0 ){
   113323     c->nInput = 0;
   113324   }else if( nInput<0 ){
   113325     c->nInput = (int)strlen(zInput);
   113326   }else{
   113327     c->nInput = nInput;
   113328   }
   113329   c->iOffset = 0;                 /* start tokenizing at the beginning */
   113330   c->iToken = 0;
   113331   c->zToken = NULL;               /* no space allocated, yet. */
   113332   c->nAllocated = 0;
   113333 
   113334   *ppCursor = &c->base;
   113335   return SQLITE_OK;
   113336 }
   113337 
   113338 /*
   113339 ** Close a tokenization cursor previously opened by a call to
   113340 ** porterOpen() above.
   113341 */
   113342 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
   113343   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   113344   sqlite3_free(c->zToken);
   113345   sqlite3_free(c);
   113346   return SQLITE_OK;
   113347 }
   113348 /*
   113349 ** Vowel or consonant
   113350 */
   113351 static const char cType[] = {
   113352    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
   113353    1, 1, 1, 2, 1
   113354 };
   113355 
   113356 /*
   113357 ** isConsonant() and isVowel() determine if their first character in
   113358 ** the string they point to is a consonant or a vowel, according
   113359 ** to Porter ruls.
   113360 **
   113361 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
   113362 ** 'Y' is a consonant unless it follows another consonant,
   113363 ** in which case it is a vowel.
   113364 **
   113365 ** In these routine, the letters are in reverse order.  So the 'y' rule
   113366 ** is that 'y' is a consonant unless it is followed by another
   113367 ** consonent.
   113368 */
   113369 static int isVowel(const char*);
   113370 static int isConsonant(const char *z){
   113371   int j;
   113372   char x = *z;
   113373   if( x==0 ) return 0;
   113374   assert( x>='a' && x<='z' );
   113375   j = cType[x-'a'];
   113376   if( j<2 ) return j;
   113377   return z[1]==0 || isVowel(z + 1);
   113378 }
   113379 static int isVowel(const char *z){
   113380   int j;
   113381   char x = *z;
   113382   if( x==0 ) return 0;
   113383   assert( x>='a' && x<='z' );
   113384   j = cType[x-'a'];
   113385   if( j<2 ) return 1-j;
   113386   return isConsonant(z + 1);
   113387 }
   113388 
   113389 /*
   113390 ** Let any sequence of one or more vowels be represented by V and let
   113391 ** C be sequence of one or more consonants.  Then every word can be
   113392 ** represented as:
   113393 **
   113394 **           [C] (VC){m} [V]
   113395 **
   113396 ** In prose:  A word is an optional consonant followed by zero or
   113397 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
   113398 ** number of vowel consonant pairs.  This routine computes the value
   113399 ** of m for the first i bytes of a word.
   113400 **
   113401 ** Return true if the m-value for z is 1 or more.  In other words,
   113402 ** return true if z contains at least one vowel that is followed
   113403 ** by a consonant.
   113404 **
   113405 ** In this routine z[] is in reverse order.  So we are really looking
   113406 ** for an instance of of a consonant followed by a vowel.
   113407 */
   113408 static int m_gt_0(const char *z){
   113409   while( isVowel(z) ){ z++; }
   113410   if( *z==0 ) return 0;
   113411   while( isConsonant(z) ){ z++; }
   113412   return *z!=0;
   113413 }
   113414 
   113415 /* Like mgt0 above except we are looking for a value of m which is
   113416 ** exactly 1
   113417 */
   113418 static int m_eq_1(const char *z){
   113419   while( isVowel(z) ){ z++; }
   113420   if( *z==0 ) return 0;
   113421   while( isConsonant(z) ){ z++; }
   113422   if( *z==0 ) return 0;
   113423   while( isVowel(z) ){ z++; }
   113424   if( *z==0 ) return 1;
   113425   while( isConsonant(z) ){ z++; }
   113426   return *z==0;
   113427 }
   113428 
   113429 /* Like mgt0 above except we are looking for a value of m>1 instead
   113430 ** or m>0
   113431 */
   113432 static int m_gt_1(const char *z){
   113433   while( isVowel(z) ){ z++; }
   113434   if( *z==0 ) return 0;
   113435   while( isConsonant(z) ){ z++; }
   113436   if( *z==0 ) return 0;
   113437   while( isVowel(z) ){ z++; }
   113438   if( *z==0 ) return 0;
   113439   while( isConsonant(z) ){ z++; }
   113440   return *z!=0;
   113441 }
   113442 
   113443 /*
   113444 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
   113445 */
   113446 static int hasVowel(const char *z){
   113447   while( isConsonant(z) ){ z++; }
   113448   return *z!=0;
   113449 }
   113450 
   113451 /*
   113452 ** Return TRUE if the word ends in a double consonant.
   113453 **
   113454 ** The text is reversed here. So we are really looking at
   113455 ** the first two characters of z[].
   113456 */
   113457 static int doubleConsonant(const char *z){
   113458   return isConsonant(z) && z[0]==z[1];
   113459 }
   113460 
   113461 /*
   113462 ** Return TRUE if the word ends with three letters which
   113463 ** are consonant-vowel-consonent and where the final consonant
   113464 ** is not 'w', 'x', or 'y'.
   113465 **
   113466 ** The word is reversed here.  So we are really checking the
   113467 ** first three letters and the first one cannot be in [wxy].
   113468 */
   113469 static int star_oh(const char *z){
   113470   return
   113471     isConsonant(z) &&
   113472     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
   113473     isVowel(z+1) &&
   113474     isConsonant(z+2);
   113475 }
   113476 
   113477 /*
   113478 ** If the word ends with zFrom and xCond() is true for the stem
   113479 ** of the word that preceeds the zFrom ending, then change the
   113480 ** ending to zTo.
   113481 **
   113482 ** The input word *pz and zFrom are both in reverse order.  zTo
   113483 ** is in normal order.
   113484 **
   113485 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
   113486 ** match.  Not that TRUE is returned even if xCond() fails and
   113487 ** no substitution occurs.
   113488 */
   113489 static int stem(
   113490   char **pz,             /* The word being stemmed (Reversed) */
   113491   const char *zFrom,     /* If the ending matches this... (Reversed) */
   113492   const char *zTo,       /* ... change the ending to this (not reversed) */
   113493   int (*xCond)(const char*)   /* Condition that must be true */
   113494 ){
   113495   char *z = *pz;
   113496   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
   113497   if( *zFrom!=0 ) return 0;
   113498   if( xCond && !xCond(z) ) return 1;
   113499   while( *zTo ){
   113500     *(--z) = *(zTo++);
   113501   }
   113502   *pz = z;
   113503   return 1;
   113504 }
   113505 
   113506 /*
   113507 ** This is the fallback stemmer used when the porter stemmer is
   113508 ** inappropriate.  The input word is copied into the output with
   113509 ** US-ASCII case folding.  If the input word is too long (more
   113510 ** than 20 bytes if it contains no digits or more than 6 bytes if
   113511 ** it contains digits) then word is truncated to 20 or 6 bytes
   113512 ** by taking 10 or 3 bytes from the beginning and end.
   113513 */
   113514 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   113515   int i, mx, j;
   113516   int hasDigit = 0;
   113517   for(i=0; i<nIn; i++){
   113518     char c = zIn[i];
   113519     if( c>='A' && c<='Z' ){
   113520       zOut[i] = c - 'A' + 'a';
   113521     }else{
   113522       if( c>='0' && c<='9' ) hasDigit = 1;
   113523       zOut[i] = c;
   113524     }
   113525   }
   113526   mx = hasDigit ? 3 : 10;
   113527   if( nIn>mx*2 ){
   113528     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
   113529       zOut[j] = zOut[i];
   113530     }
   113531     i = j;
   113532   }
   113533   zOut[i] = 0;
   113534   *pnOut = i;
   113535 }
   113536 
   113537 
   113538 /*
   113539 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
   113540 ** zOut is at least big enough to hold nIn bytes.  Write the actual
   113541 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
   113542 **
   113543 ** Any upper-case characters in the US-ASCII character set ([A-Z])
   113544 ** are converted to lower case.  Upper-case UTF characters are
   113545 ** unchanged.
   113546 **
   113547 ** Words that are longer than about 20 bytes are stemmed by retaining
   113548 ** a few bytes from the beginning and the end of the word.  If the
   113549 ** word contains digits, 3 bytes are taken from the beginning and
   113550 ** 3 bytes from the end.  For long words without digits, 10 bytes
   113551 ** are taken from each end.  US-ASCII case folding still applies.
   113552 **
   113553 ** If the input word contains not digits but does characters not
   113554 ** in [a-zA-Z] then no stemming is attempted and this routine just
   113555 ** copies the input into the input into the output with US-ASCII
   113556 ** case folding.
   113557 **
   113558 ** Stemming never increases the length of the word.  So there is
   113559 ** no chance of overflowing the zOut buffer.
   113560 */
   113561 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
   113562   int i, j;
   113563   char zReverse[28];
   113564   char *z, *z2;
   113565   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
   113566     /* The word is too big or too small for the porter stemmer.
   113567     ** Fallback to the copy stemmer */
   113568     copy_stemmer(zIn, nIn, zOut, pnOut);
   113569     return;
   113570   }
   113571   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
   113572     char c = zIn[i];
   113573     if( c>='A' && c<='Z' ){
   113574       zReverse[j] = c + 'a' - 'A';
   113575     }else if( c>='a' && c<='z' ){
   113576       zReverse[j] = c;
   113577     }else{
   113578       /* The use of a character not in [a-zA-Z] means that we fallback
   113579       ** to the copy stemmer */
   113580       copy_stemmer(zIn, nIn, zOut, pnOut);
   113581       return;
   113582     }
   113583   }
   113584   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
   113585   z = &zReverse[j+1];
   113586 
   113587 
   113588   /* Step 1a */
   113589   if( z[0]=='s' ){
   113590     if(
   113591      !stem(&z, "sess", "ss", 0) &&
   113592      !stem(&z, "sei", "i", 0)  &&
   113593      !stem(&z, "ss", "ss", 0)
   113594     ){
   113595       z++;
   113596     }
   113597   }
   113598 
   113599   /* Step 1b */
   113600   z2 = z;
   113601   if( stem(&z, "dee", "ee", m_gt_0) ){
   113602     /* Do nothing.  The work was all in the test */
   113603   }else if(
   113604      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
   113605       && z!=z2
   113606   ){
   113607      if( stem(&z, "ta", "ate", 0) ||
   113608          stem(&z, "lb", "ble", 0) ||
   113609          stem(&z, "zi", "ize", 0) ){
   113610        /* Do nothing.  The work was all in the test */
   113611      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
   113612        z++;
   113613      }else if( m_eq_1(z) && star_oh(z) ){
   113614        *(--z) = 'e';
   113615      }
   113616   }
   113617 
   113618   /* Step 1c */
   113619   if( z[0]=='y' && hasVowel(z+1) ){
   113620     z[0] = 'i';
   113621   }
   113622 
   113623   /* Step 2 */
   113624   switch( z[1] ){
   113625    case 'a':
   113626      stem(&z, "lanoita", "ate", m_gt_0) ||
   113627      stem(&z, "lanoit", "tion", m_gt_0);
   113628      break;
   113629    case 'c':
   113630      stem(&z, "icne", "ence", m_gt_0) ||
   113631      stem(&z, "icna", "ance", m_gt_0);
   113632      break;
   113633    case 'e':
   113634      stem(&z, "rezi", "ize", m_gt_0);
   113635      break;
   113636    case 'g':
   113637      stem(&z, "igol", "log", m_gt_0);
   113638      break;
   113639    case 'l':
   113640      stem(&z, "ilb", "ble", m_gt_0) ||
   113641      stem(&z, "illa", "al", m_gt_0) ||
   113642      stem(&z, "iltne", "ent", m_gt_0) ||
   113643      stem(&z, "ile", "e", m_gt_0) ||
   113644      stem(&z, "ilsuo", "ous", m_gt_0);
   113645      break;
   113646    case 'o':
   113647      stem(&z, "noitazi", "ize", m_gt_0) ||
   113648      stem(&z, "noita", "ate", m_gt_0) ||
   113649      stem(&z, "rota", "ate", m_gt_0);
   113650      break;
   113651    case 's':
   113652      stem(&z, "msila", "al", m_gt_0) ||
   113653      stem(&z, "ssenevi", "ive", m_gt_0) ||
   113654      stem(&z, "ssenluf", "ful", m_gt_0) ||
   113655      stem(&z, "ssensuo", "ous", m_gt_0);
   113656      break;
   113657    case 't':
   113658      stem(&z, "itila", "al", m_gt_0) ||
   113659      stem(&z, "itivi", "ive", m_gt_0) ||
   113660      stem(&z, "itilib", "ble", m_gt_0);
   113661      break;
   113662   }
   113663 
   113664   /* Step 3 */
   113665   switch( z[0] ){
   113666    case 'e':
   113667      stem(&z, "etaci", "ic", m_gt_0) ||
   113668      stem(&z, "evita", "", m_gt_0)   ||
   113669      stem(&z, "ezila", "al", m_gt_0);
   113670      break;
   113671    case 'i':
   113672      stem(&z, "itici", "ic", m_gt_0);
   113673      break;
   113674    case 'l':
   113675      stem(&z, "laci", "ic", m_gt_0) ||
   113676      stem(&z, "luf", "", m_gt_0);
   113677      break;
   113678    case 's':
   113679      stem(&z, "ssen", "", m_gt_0);
   113680      break;
   113681   }
   113682 
   113683   /* Step 4 */
   113684   switch( z[1] ){
   113685    case 'a':
   113686      if( z[0]=='l' && m_gt_1(z+2) ){
   113687        z += 2;
   113688      }
   113689      break;
   113690    case 'c':
   113691      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
   113692        z += 4;
   113693      }
   113694      break;
   113695    case 'e':
   113696      if( z[0]=='r' && m_gt_1(z+2) ){
   113697        z += 2;
   113698      }
   113699      break;
   113700    case 'i':
   113701      if( z[0]=='c' && m_gt_1(z+2) ){
   113702        z += 2;
   113703      }
   113704      break;
   113705    case 'l':
   113706      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
   113707        z += 4;
   113708      }
   113709      break;
   113710    case 'n':
   113711      if( z[0]=='t' ){
   113712        if( z[2]=='a' ){
   113713          if( m_gt_1(z+3) ){
   113714            z += 3;
   113715          }
   113716        }else if( z[2]=='e' ){
   113717          stem(&z, "tneme", "", m_gt_1) ||
   113718          stem(&z, "tnem", "", m_gt_1) ||
   113719          stem(&z, "tne", "", m_gt_1);
   113720        }
   113721      }
   113722      break;
   113723    case 'o':
   113724      if( z[0]=='u' ){
   113725        if( m_gt_1(z+2) ){
   113726          z += 2;
   113727        }
   113728      }else if( z[3]=='s' || z[3]=='t' ){
   113729        stem(&z, "noi", "", m_gt_1);
   113730      }
   113731      break;
   113732    case 's':
   113733      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
   113734        z += 3;
   113735      }
   113736      break;
   113737    case 't':
   113738      stem(&z, "eta", "", m_gt_1) ||
   113739      stem(&z, "iti", "", m_gt_1);
   113740      break;
   113741    case 'u':
   113742      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
   113743        z += 3;
   113744      }
   113745      break;
   113746    case 'v':
   113747    case 'z':
   113748      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
   113749        z += 3;
   113750      }
   113751      break;
   113752   }
   113753 
   113754   /* Step 5a */
   113755   if( z[0]=='e' ){
   113756     if( m_gt_1(z+1) ){
   113757       z++;
   113758     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
   113759       z++;
   113760     }
   113761   }
   113762 
   113763   /* Step 5b */
   113764   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
   113765     z++;
   113766   }
   113767 
   113768   /* z[] is now the stemmed word in reverse order.  Flip it back
   113769   ** around into forward order and return.
   113770   */
   113771   *pnOut = i = (int)strlen(z);
   113772   zOut[i] = 0;
   113773   while( *z ){
   113774     zOut[--i] = *(z++);
   113775   }
   113776 }
   113777 
   113778 /*
   113779 ** Characters that can be part of a token.  We assume any character
   113780 ** whose value is greater than 0x80 (any UTF character) can be
   113781 ** part of a token.  In other words, delimiters all must have
   113782 ** values of 0x7f or lower.
   113783 */
   113784 static const char porterIdChar[] = {
   113785 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
   113786     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   113787     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   113788     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   113789     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   113790     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   113791 };
   113792 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
   113793 
   113794 /*
   113795 ** Extract the next token from a tokenization cursor.  The cursor must
   113796 ** have been opened by a prior call to porterOpen().
   113797 */
   113798 static int porterNext(
   113799   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
   113800   const char **pzToken,               /* OUT: *pzToken is the token text */
   113801   int *pnBytes,                       /* OUT: Number of bytes in token */
   113802   int *piStartOffset,                 /* OUT: Starting offset of token */
   113803   int *piEndOffset,                   /* OUT: Ending offset of token */
   113804   int *piPosition                     /* OUT: Position integer of token */
   113805 ){
   113806   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
   113807   const char *z = c->zInput;
   113808 
   113809   while( c->iOffset<c->nInput ){
   113810     int iStartOffset, ch;
   113811 
   113812     /* Scan past delimiter characters */
   113813     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
   113814       c->iOffset++;
   113815     }
   113816 
   113817     /* Count non-delimiter characters. */
   113818     iStartOffset = c->iOffset;
   113819     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
   113820       c->iOffset++;
   113821     }
   113822 
   113823     if( c->iOffset>iStartOffset ){
   113824       int n = c->iOffset-iStartOffset;
   113825       if( n>c->nAllocated ){
   113826         char *pNew;
   113827         c->nAllocated = n+20;
   113828         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
   113829         if( !pNew ) return SQLITE_NOMEM;
   113830         c->zToken = pNew;
   113831       }
   113832       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
   113833       *pzToken = c->zToken;
   113834       *piStartOffset = iStartOffset;
   113835       *piEndOffset = c->iOffset;
   113836       *piPosition = c->iToken++;
   113837       return SQLITE_OK;
   113838     }
   113839   }
   113840   return SQLITE_DONE;
   113841 }
   113842 
   113843 /*
   113844 ** The set of routines that implement the porter-stemmer tokenizer
   113845 */
   113846 static const sqlite3_tokenizer_module porterTokenizerModule = {
   113847   0,
   113848   porterCreate,
   113849   porterDestroy,
   113850   porterOpen,
   113851   porterClose,
   113852   porterNext,
   113853 };
   113854 
   113855 /*
   113856 ** Allocate a new porter tokenizer.  Return a pointer to the new
   113857 ** tokenizer in *ppModule
   113858 */
   113859 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
   113860   sqlite3_tokenizer_module const**ppModule
   113861 ){
   113862   *ppModule = &porterTokenizerModule;
   113863 }
   113864 
   113865 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   113866 
   113867 /************** End of fts3_porter.c *****************************************/
   113868 /************** Begin file fts3_tokenizer.c **********************************/
   113869 /*
   113870 ** 2007 June 22
   113871 **
   113872 ** The author disclaims copyright to this source code.  In place of
   113873 ** a legal notice, here is a blessing:
   113874 **
   113875 **    May you do good and not evil.
   113876 **    May you find forgiveness for yourself and forgive others.
   113877 **    May you share freely, never taking more than you give.
   113878 **
   113879 ******************************************************************************
   113880 **
   113881 ** This is part of an SQLite module implementing full-text search.
   113882 ** This particular file implements the generic tokenizer interface.
   113883 */
   113884 
   113885 /*
   113886 ** The code in this file is only compiled if:
   113887 **
   113888 **     * The FTS3 module is being built as an extension
   113889 **       (in which case SQLITE_CORE is not defined), or
   113890 **
   113891 **     * The FTS3 module is being built into the core of
   113892 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   113893 */
   113894 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   113895 
   113896 #ifndef SQLITE_CORE
   113897   SQLITE_EXTENSION_INIT1
   113898 #endif
   113899 
   113900 
   113901 /*
   113902 ** Implementation of the SQL scalar function for accessing the underlying
   113903 ** hash table. This function may be called as follows:
   113904 **
   113905 **   SELECT <function-name>(<key-name>);
   113906 **   SELECT <function-name>(<key-name>, <pointer>);
   113907 **
   113908 ** where <function-name> is the name passed as the second argument
   113909 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
   113910 **
   113911 ** If the <pointer> argument is specified, it must be a blob value
   113912 ** containing a pointer to be stored as the hash data corresponding
   113913 ** to the string <key-name>. If <pointer> is not specified, then
   113914 ** the string <key-name> must already exist in the has table. Otherwise,
   113915 ** an error is returned.
   113916 **
   113917 ** Whether or not the <pointer> argument is specified, the value returned
   113918 ** is a blob containing the pointer stored as the hash data corresponding
   113919 ** to string <key-name> (after the hash-table is updated, if applicable).
   113920 */
   113921 static void scalarFunc(
   113922   sqlite3_context *context,
   113923   int argc,
   113924   sqlite3_value **argv
   113925 ){
   113926   Fts3Hash *pHash;
   113927   void *pPtr = 0;
   113928   const unsigned char *zName;
   113929   int nName;
   113930 
   113931   assert( argc==1 || argc==2 );
   113932 
   113933   pHash = (Fts3Hash *)sqlite3_user_data(context);
   113934 
   113935   zName = sqlite3_value_text(argv[0]);
   113936   nName = sqlite3_value_bytes(argv[0])+1;
   113937 
   113938   if( argc==2 ){
   113939     void *pOld;
   113940     int n = sqlite3_value_bytes(argv[1]);
   113941     if( n!=sizeof(pPtr) ){
   113942       sqlite3_result_error(context, "argument type mismatch", -1);
   113943       return;
   113944     }
   113945     pPtr = *(void **)sqlite3_value_blob(argv[1]);
   113946     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
   113947     if( pOld==pPtr ){
   113948       sqlite3_result_error(context, "out of memory", -1);
   113949       return;
   113950     }
   113951   }else{
   113952     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
   113953     if( !pPtr ){
   113954       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   113955       sqlite3_result_error(context, zErr, -1);
   113956       sqlite3_free(zErr);
   113957       return;
   113958     }
   113959   }
   113960 
   113961   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
   113962 }
   113963 
   113964 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
   113965   static const char isFtsIdChar[] = {
   113966       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
   113967       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
   113968       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
   113969       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
   113970       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
   113971       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
   113972       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
   113973       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
   113974   };
   113975   return (c&0x80 || isFtsIdChar[(int)(c)]);
   113976 }
   113977 
   113978 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
   113979   const char *z1;
   113980   const char *z2 = 0;
   113981 
   113982   /* Find the start of the next token. */
   113983   z1 = zStr;
   113984   while( z2==0 ){
   113985     char c = *z1;
   113986     switch( c ){
   113987       case '\0': return 0;        /* No more tokens here */
   113988       case '\'':
   113989       case '"':
   113990       case '`': {
   113991         z2 = z1;
   113992         while( *++z2 && (*z2!=c || *++z2==c) );
   113993         break;
   113994       }
   113995       case '[':
   113996         z2 = &z1[1];
   113997         while( *z2 && z2[0]!=']' ) z2++;
   113998         if( *z2 ) z2++;
   113999         break;
   114000 
   114001       default:
   114002         if( sqlite3Fts3IsIdChar(*z1) ){
   114003           z2 = &z1[1];
   114004           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
   114005         }else{
   114006           z1++;
   114007         }
   114008     }
   114009   }
   114010 
   114011   *pn = (int)(z2-z1);
   114012   return z1;
   114013 }
   114014 
   114015 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
   114016   Fts3Hash *pHash,                /* Tokenizer hash table */
   114017   const char *zArg,               /* Tokenizer name */
   114018   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
   114019   char **pzErr                    /* OUT: Set to malloced error message */
   114020 ){
   114021   int rc;
   114022   char *z = (char *)zArg;
   114023   int n;
   114024   char *zCopy;
   114025   char *zEnd;                     /* Pointer to nul-term of zCopy */
   114026   sqlite3_tokenizer_module *m;
   114027 
   114028   zCopy = sqlite3_mprintf("%s", zArg);
   114029   if( !zCopy ) return SQLITE_NOMEM;
   114030   zEnd = &zCopy[strlen(zCopy)];
   114031 
   114032   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
   114033   z[n] = '\0';
   114034   sqlite3Fts3Dequote(z);
   114035 
   114036   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
   114037   if( !m ){
   114038     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
   114039     rc = SQLITE_ERROR;
   114040   }else{
   114041     char const **aArg = 0;
   114042     int iArg = 0;
   114043     z = &z[n+1];
   114044     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
   114045       int nNew = sizeof(char *)*(iArg+1);
   114046       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
   114047       if( !aNew ){
   114048         sqlite3_free(zCopy);
   114049         sqlite3_free((void *)aArg);
   114050         return SQLITE_NOMEM;
   114051       }
   114052       aArg = aNew;
   114053       aArg[iArg++] = z;
   114054       z[n] = '\0';
   114055       sqlite3Fts3Dequote(z);
   114056       z = &z[n+1];
   114057     }
   114058     rc = m->xCreate(iArg, aArg, ppTok);
   114059     assert( rc!=SQLITE_OK || *ppTok );
   114060     if( rc!=SQLITE_OK ){
   114061       *pzErr = sqlite3_mprintf("unknown tokenizer");
   114062     }else{
   114063       (*ppTok)->pModule = m;
   114064     }
   114065     sqlite3_free((void *)aArg);
   114066   }
   114067 
   114068   sqlite3_free(zCopy);
   114069   return rc;
   114070 }
   114071 
   114072 
   114073 #ifdef SQLITE_TEST
   114074 
   114075 
   114076 /*
   114077 ** Implementation of a special SQL scalar function for testing tokenizers
   114078 ** designed to be used in concert with the Tcl testing framework. This
   114079 ** function must be called with two arguments:
   114080 **
   114081 **   SELECT <function-name>(<key-name>, <input-string>);
   114082 **   SELECT <function-name>(<key-name>, <pointer>);
   114083 **
   114084 ** where <function-name> is the name passed as the second argument
   114085 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
   114086 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
   114087 **
   114088 ** The return value is a string that may be interpreted as a Tcl
   114089 ** list. For each token in the <input-string>, three elements are
   114090 ** added to the returned list. The first is the token position, the
   114091 ** second is the token text (folded, stemmed, etc.) and the third is the
   114092 ** substring of <input-string> associated with the token. For example,
   114093 ** using the built-in "simple" tokenizer:
   114094 **
   114095 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
   114096 **
   114097 ** will return the string:
   114098 **
   114099 **   "{0 i I 1 dont don't 2 see see 3 how how}"
   114100 **
   114101 */
   114102 static void testFunc(
   114103   sqlite3_context *context,
   114104   int argc,
   114105   sqlite3_value **argv
   114106 ){
   114107   Fts3Hash *pHash;
   114108   sqlite3_tokenizer_module *p;
   114109   sqlite3_tokenizer *pTokenizer = 0;
   114110   sqlite3_tokenizer_cursor *pCsr = 0;
   114111 
   114112   const char *zErr = 0;
   114113 
   114114   const char *zName;
   114115   int nName;
   114116   const char *zInput;
   114117   int nInput;
   114118 
   114119   const char *zArg = 0;
   114120 
   114121   const char *zToken;
   114122   int nToken;
   114123   int iStart;
   114124   int iEnd;
   114125   int iPos;
   114126 
   114127   Tcl_Obj *pRet;
   114128 
   114129   assert( argc==2 || argc==3 );
   114130 
   114131   nName = sqlite3_value_bytes(argv[0]);
   114132   zName = (const char *)sqlite3_value_text(argv[0]);
   114133   nInput = sqlite3_value_bytes(argv[argc-1]);
   114134   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
   114135 
   114136   if( argc==3 ){
   114137     zArg = (const char *)sqlite3_value_text(argv[1]);
   114138   }
   114139 
   114140   pHash = (Fts3Hash *)sqlite3_user_data(context);
   114141   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
   114142 
   114143   if( !p ){
   114144     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
   114145     sqlite3_result_error(context, zErr, -1);
   114146     sqlite3_free(zErr);
   114147     return;
   114148   }
   114149 
   114150   pRet = Tcl_NewObj();
   114151   Tcl_IncrRefCount(pRet);
   114152 
   114153   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
   114154     zErr = "error in xCreate()";
   114155     goto finish;
   114156   }
   114157   pTokenizer->pModule = p;
   114158   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
   114159     zErr = "error in xOpen()";
   114160     goto finish;
   114161   }
   114162   pCsr->pTokenizer = pTokenizer;
   114163 
   114164   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
   114165     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
   114166     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   114167     zToken = &zInput[iStart];
   114168     nToken = iEnd-iStart;
   114169     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
   114170   }
   114171 
   114172   if( SQLITE_OK!=p->xClose(pCsr) ){
   114173     zErr = "error in xClose()";
   114174     goto finish;
   114175   }
   114176   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
   114177     zErr = "error in xDestroy()";
   114178     goto finish;
   114179   }
   114180 
   114181 finish:
   114182   if( zErr ){
   114183     sqlite3_result_error(context, zErr, -1);
   114184   }else{
   114185     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
   114186   }
   114187   Tcl_DecrRefCount(pRet);
   114188 }
   114189 
   114190 static
   114191 int registerTokenizer(
   114192   sqlite3 *db,
   114193   char *zName,
   114194   const sqlite3_tokenizer_module *p
   114195 ){
   114196   int rc;
   114197   sqlite3_stmt *pStmt;
   114198   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
   114199 
   114200   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   114201   if( rc!=SQLITE_OK ){
   114202     return rc;
   114203   }
   114204 
   114205   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   114206   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
   114207   sqlite3_step(pStmt);
   114208 
   114209   return sqlite3_finalize(pStmt);
   114210 }
   114211 
   114212 static
   114213 int queryTokenizer(
   114214   sqlite3 *db,
   114215   char *zName,
   114216   const sqlite3_tokenizer_module **pp
   114217 ){
   114218   int rc;
   114219   sqlite3_stmt *pStmt;
   114220   const char zSql[] = "SELECT fts3_tokenizer(?)";
   114221 
   114222   *pp = 0;
   114223   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   114224   if( rc!=SQLITE_OK ){
   114225     return rc;
   114226   }
   114227 
   114228   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   114229   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   114230     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
   114231       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
   114232     }
   114233   }
   114234 
   114235   return sqlite3_finalize(pStmt);
   114236 }
   114237 
   114238 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
   114239 
   114240 /*
   114241 ** Implementation of the scalar function fts3_tokenizer_internal_test().
   114242 ** This function is used for testing only, it is not included in the
   114243 ** build unless SQLITE_TEST is defined.
   114244 **
   114245 ** The purpose of this is to test that the fts3_tokenizer() function
   114246 ** can be used as designed by the C-code in the queryTokenizer and
   114247 ** registerTokenizer() functions above. These two functions are repeated
   114248 ** in the README.tokenizer file as an example, so it is important to
   114249 ** test them.
   114250 **
   114251 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
   114252 ** function with no arguments. An assert() will fail if a problem is
   114253 ** detected. i.e.:
   114254 **
   114255 **     SELECT fts3_tokenizer_internal_test();
   114256 **
   114257 */
   114258 static void intTestFunc(
   114259   sqlite3_context *context,
   114260   int argc,
   114261   sqlite3_value **argv
   114262 ){
   114263   int rc;
   114264   const sqlite3_tokenizer_module *p1;
   114265   const sqlite3_tokenizer_module *p2;
   114266   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
   114267 
   114268   UNUSED_PARAMETER(argc);
   114269   UNUSED_PARAMETER(argv);
   114270 
   114271   /* Test the query function */
   114272   sqlite3Fts3SimpleTokenizerModule(&p1);
   114273   rc = queryTokenizer(db, "simple", &p2);
   114274   assert( rc==SQLITE_OK );
   114275   assert( p1==p2 );
   114276   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   114277   assert( rc==SQLITE_ERROR );
   114278   assert( p2==0 );
   114279   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
   114280 
   114281   /* Test the storage function */
   114282   rc = registerTokenizer(db, "nosuchtokenizer", p1);
   114283   assert( rc==SQLITE_OK );
   114284   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
   114285   assert( rc==SQLITE_OK );
   114286   assert( p2==p1 );
   114287 
   114288   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
   114289 }
   114290 
   114291 #endif
   114292 
   114293 /*
   114294 ** Set up SQL objects in database db used to access the contents of
   114295 ** the hash table pointed to by argument pHash. The hash table must
   114296 ** been initialised to use string keys, and to take a private copy
   114297 ** of the key when a value is inserted. i.e. by a call similar to:
   114298 **
   114299 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
   114300 **
   114301 ** This function adds a scalar function (see header comment above
   114302 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
   114303 ** defined at compilation time, a temporary virtual table (see header
   114304 ** comment above struct HashTableVtab) to the database schema. Both
   114305 ** provide read/write access to the contents of *pHash.
   114306 **
   114307 ** The third argument to this function, zName, is used as the name
   114308 ** of both the scalar and, if created, the virtual table.
   114309 */
   114310 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
   114311   sqlite3 *db,
   114312   Fts3Hash *pHash,
   114313   const char *zName
   114314 ){
   114315   int rc = SQLITE_OK;
   114316   void *p = (void *)pHash;
   114317   const int any = SQLITE_ANY;
   114318 
   114319 #ifdef SQLITE_TEST
   114320   char *zTest = 0;
   114321   char *zTest2 = 0;
   114322   void *pdb = (void *)db;
   114323   zTest = sqlite3_mprintf("%s_test", zName);
   114324   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
   114325   if( !zTest || !zTest2 ){
   114326     rc = SQLITE_NOMEM;
   114327   }
   114328 #endif
   114329 
   114330   if( SQLITE_OK==rc ){
   114331     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
   114332   }
   114333   if( SQLITE_OK==rc ){
   114334     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
   114335   }
   114336 #ifdef SQLITE_TEST
   114337   if( SQLITE_OK==rc ){
   114338     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
   114339   }
   114340   if( SQLITE_OK==rc ){
   114341     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
   114342   }
   114343   if( SQLITE_OK==rc ){
   114344     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
   114345   }
   114346 #endif
   114347 
   114348 #ifdef SQLITE_TEST
   114349   sqlite3_free(zTest);
   114350   sqlite3_free(zTest2);
   114351 #endif
   114352 
   114353   return rc;
   114354 }
   114355 
   114356 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   114357 
   114358 /************** End of fts3_tokenizer.c **************************************/
   114359 /************** Begin file fts3_tokenizer1.c *********************************/
   114360 /*
   114361 ** 2006 Oct 10
   114362 **
   114363 ** The author disclaims copyright to this source code.  In place of
   114364 ** a legal notice, here is a blessing:
   114365 **
   114366 **    May you do good and not evil.
   114367 **    May you find forgiveness for yourself and forgive others.
   114368 **    May you share freely, never taking more than you give.
   114369 **
   114370 ******************************************************************************
   114371 **
   114372 ** Implementation of the "simple" full-text-search tokenizer.
   114373 */
   114374 
   114375 /*
   114376 ** The code in this file is only compiled if:
   114377 **
   114378 **     * The FTS3 module is being built as an extension
   114379 **       (in which case SQLITE_CORE is not defined), or
   114380 **
   114381 **     * The FTS3 module is being built into the core of
   114382 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
   114383 */
   114384 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   114385 
   114386 
   114387 
   114388 
   114389 typedef struct simple_tokenizer {
   114390   sqlite3_tokenizer base;
   114391   char delim[128];             /* flag ASCII delimiters */
   114392 } simple_tokenizer;
   114393 
   114394 typedef struct simple_tokenizer_cursor {
   114395   sqlite3_tokenizer_cursor base;
   114396   const char *pInput;          /* input we are tokenizing */
   114397   int nBytes;                  /* size of the input */
   114398   int iOffset;                 /* current position in pInput */
   114399   int iToken;                  /* index of next token to be returned */
   114400   char *pToken;                /* storage for current token */
   114401   int nTokenAllocated;         /* space allocated to zToken buffer */
   114402 } simple_tokenizer_cursor;
   114403 
   114404 
   114405 static int simpleDelim(simple_tokenizer *t, unsigned char c){
   114406   return c<0x80 && t->delim[c];
   114407 }
   114408 static int fts3_isalnum(int x){
   114409   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
   114410 }
   114411 
   114412 /*
   114413 ** Create a new tokenizer instance.
   114414 */
   114415 static int simpleCreate(
   114416   int argc, const char * const *argv,
   114417   sqlite3_tokenizer **ppTokenizer
   114418 ){
   114419   simple_tokenizer *t;
   114420 
   114421   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
   114422   if( t==NULL ) return SQLITE_NOMEM;
   114423   memset(t, 0, sizeof(*t));
   114424 
   114425   /* TODO(shess) Delimiters need to remain the same from run to run,
   114426   ** else we need to reindex.  One solution would be a meta-table to
   114427   ** track such information in the database, then we'd only want this
   114428   ** information on the initial create.
   114429   */
   114430   if( argc>1 ){
   114431     int i, n = (int)strlen(argv[1]);
   114432     for(i=0; i<n; i++){
   114433       unsigned char ch = argv[1][i];
   114434       /* We explicitly don't support UTF-8 delimiters for now. */
   114435       if( ch>=0x80 ){
   114436         sqlite3_free(t);
   114437         return SQLITE_ERROR;
   114438       }
   114439       t->delim[ch] = 1;
   114440     }
   114441   } else {
   114442     /* Mark non-alphanumeric ASCII characters as delimiters */
   114443     int i;
   114444     for(i=1; i<0x80; i++){
   114445       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
   114446     }
   114447   }
   114448 
   114449   *ppTokenizer = &t->base;
   114450   return SQLITE_OK;
   114451 }
   114452 
   114453 /*
   114454 ** Destroy a tokenizer
   114455 */
   114456 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
   114457   sqlite3_free(pTokenizer);
   114458   return SQLITE_OK;
   114459 }
   114460 
   114461 /*
   114462 ** Prepare to begin tokenizing a particular string.  The input
   114463 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   114464 ** used to incrementally tokenize this string is returned in
   114465 ** *ppCursor.
   114466 */
   114467 static int simpleOpen(
   114468   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   114469   const char *pInput, int nBytes,        /* String to be tokenized */
   114470   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   114471 ){
   114472   simple_tokenizer_cursor *c;
   114473 
   114474   UNUSED_PARAMETER(pTokenizer);
   114475 
   114476   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
   114477   if( c==NULL ) return SQLITE_NOMEM;
   114478 
   114479   c->pInput = pInput;
   114480   if( pInput==0 ){
   114481     c->nBytes = 0;
   114482   }else if( nBytes<0 ){
   114483     c->nBytes = (int)strlen(pInput);
   114484   }else{
   114485     c->nBytes = nBytes;
   114486   }
   114487   c->iOffset = 0;                 /* start tokenizing at the beginning */
   114488   c->iToken = 0;
   114489   c->pToken = NULL;               /* no space allocated, yet. */
   114490   c->nTokenAllocated = 0;
   114491 
   114492   *ppCursor = &c->base;
   114493   return SQLITE_OK;
   114494 }
   114495 
   114496 /*
   114497 ** Close a tokenization cursor previously opened by a call to
   114498 ** simpleOpen() above.
   114499 */
   114500 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
   114501   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   114502   sqlite3_free(c->pToken);
   114503   sqlite3_free(c);
   114504   return SQLITE_OK;
   114505 }
   114506 
   114507 /*
   114508 ** Extract the next token from a tokenization cursor.  The cursor must
   114509 ** have been opened by a prior call to simpleOpen().
   114510 */
   114511 static int simpleNext(
   114512   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   114513   const char **ppToken,               /* OUT: *ppToken is the token text */
   114514   int *pnBytes,                       /* OUT: Number of bytes in token */
   114515   int *piStartOffset,                 /* OUT: Starting offset of token */
   114516   int *piEndOffset,                   /* OUT: Ending offset of token */
   114517   int *piPosition                     /* OUT: Position integer of token */
   114518 ){
   114519   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
   114520   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
   114521   unsigned char *p = (unsigned char *)c->pInput;
   114522 
   114523   while( c->iOffset<c->nBytes ){
   114524     int iStartOffset;
   114525 
   114526     /* Scan past delimiter characters */
   114527     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
   114528       c->iOffset++;
   114529     }
   114530 
   114531     /* Count non-delimiter characters. */
   114532     iStartOffset = c->iOffset;
   114533     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
   114534       c->iOffset++;
   114535     }
   114536 
   114537     if( c->iOffset>iStartOffset ){
   114538       int i, n = c->iOffset-iStartOffset;
   114539       if( n>c->nTokenAllocated ){
   114540         char *pNew;
   114541         c->nTokenAllocated = n+20;
   114542         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
   114543         if( !pNew ) return SQLITE_NOMEM;
   114544         c->pToken = pNew;
   114545       }
   114546       for(i=0; i<n; i++){
   114547         /* TODO(shess) This needs expansion to handle UTF-8
   114548         ** case-insensitivity.
   114549         */
   114550         unsigned char ch = p[iStartOffset+i];
   114551         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
   114552       }
   114553       *ppToken = c->pToken;
   114554       *pnBytes = n;
   114555       *piStartOffset = iStartOffset;
   114556       *piEndOffset = c->iOffset;
   114557       *piPosition = c->iToken++;
   114558 
   114559       return SQLITE_OK;
   114560     }
   114561   }
   114562   return SQLITE_DONE;
   114563 }
   114564 
   114565 /*
   114566 ** The set of routines that implement the simple tokenizer
   114567 */
   114568 static const sqlite3_tokenizer_module simpleTokenizerModule = {
   114569   0,
   114570   simpleCreate,
   114571   simpleDestroy,
   114572   simpleOpen,
   114573   simpleClose,
   114574   simpleNext,
   114575 };
   114576 
   114577 /*
   114578 ** Allocate a new simple tokenizer.  Return a pointer to the new
   114579 ** tokenizer in *ppModule
   114580 */
   114581 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
   114582   sqlite3_tokenizer_module const**ppModule
   114583 ){
   114584   *ppModule = &simpleTokenizerModule;
   114585 }
   114586 
   114587 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   114588 
   114589 /************** End of fts3_tokenizer1.c *************************************/
   114590 /************** Begin file fts3_write.c **************************************/
   114591 /*
   114592 ** 2009 Oct 23
   114593 **
   114594 ** The author disclaims copyright to this source code.  In place of
   114595 ** a legal notice, here is a blessing:
   114596 **
   114597 **    May you do good and not evil.
   114598 **    May you find forgiveness for yourself and forgive others.
   114599 **    May you share freely, never taking more than you give.
   114600 **
   114601 ******************************************************************************
   114602 **
   114603 ** This file is part of the SQLite FTS3 extension module. Specifically,
   114604 ** this file contains code to insert, update and delete rows from FTS3
   114605 ** tables. It also contains code to merge FTS3 b-tree segments. Some
   114606 ** of the sub-routines used to merge segments are also used by the query
   114607 ** code in fts3.c.
   114608 */
   114609 
   114610 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   114611 
   114612 
   114613 /*
   114614 ** When full-text index nodes are loaded from disk, the buffer that they
   114615 ** are loaded into has the following number of bytes of padding at the end
   114616 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
   114617 ** of 920 bytes is allocated for it.
   114618 **
   114619 ** This means that if we have a pointer into a buffer containing node data,
   114620 ** it is always safe to read up to two varints from it without risking an
   114621 ** overread, even if the node data is corrupted.
   114622 */
   114623 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
   114624 
   114625 typedef struct PendingList PendingList;
   114626 typedef struct SegmentNode SegmentNode;
   114627 typedef struct SegmentWriter SegmentWriter;
   114628 
   114629 /*
   114630 ** Data structure used while accumulating terms in the pending-terms hash
   114631 ** table. The hash table entry maps from term (a string) to a malloc'd
   114632 ** instance of this structure.
   114633 */
   114634 struct PendingList {
   114635   int nData;
   114636   char *aData;
   114637   int nSpace;
   114638   sqlite3_int64 iLastDocid;
   114639   sqlite3_int64 iLastCol;
   114640   sqlite3_int64 iLastPos;
   114641 };
   114642 
   114643 
   114644 /*
   114645 ** Each cursor has a (possibly empty) linked list of the following objects.
   114646 */
   114647 struct Fts3DeferredToken {
   114648   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
   114649   int iCol;                       /* Column token must occur in */
   114650   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
   114651   PendingList *pList;             /* Doclist is assembled here */
   114652 };
   114653 
   114654 /*
   114655 ** An instance of this structure is used to iterate through the terms on
   114656 ** a contiguous set of segment b-tree leaf nodes. Although the details of
   114657 ** this structure are only manipulated by code in this file, opaque handles
   114658 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
   114659 ** terms when querying the full-text index. See functions:
   114660 **
   114661 **   sqlite3Fts3SegReaderNew()
   114662 **   sqlite3Fts3SegReaderFree()
   114663 **   sqlite3Fts3SegReaderCost()
   114664 **   sqlite3Fts3SegReaderIterate()
   114665 **
   114666 ** Methods used to manipulate Fts3SegReader structures:
   114667 **
   114668 **   fts3SegReaderNext()
   114669 **   fts3SegReaderFirstDocid()
   114670 **   fts3SegReaderNextDocid()
   114671 */
   114672 struct Fts3SegReader {
   114673   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
   114674 
   114675   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
   114676   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
   114677   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
   114678   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
   114679 
   114680   char *aNode;                    /* Pointer to node data (or NULL) */
   114681   int nNode;                      /* Size of buffer at aNode (or 0) */
   114682   Fts3HashElem **ppNextElem;
   114683 
   114684   /* Variables set by fts3SegReaderNext(). These may be read directly
   114685   ** by the caller. They are valid from the time SegmentReaderNew() returns
   114686   ** until SegmentReaderNext() returns something other than SQLITE_OK
   114687   ** (i.e. SQLITE_DONE).
   114688   */
   114689   int nTerm;                      /* Number of bytes in current term */
   114690   char *zTerm;                    /* Pointer to current term */
   114691   int nTermAlloc;                 /* Allocated size of zTerm buffer */
   114692   char *aDoclist;                 /* Pointer to doclist of current entry */
   114693   int nDoclist;                   /* Size of doclist in current entry */
   114694 
   114695   /* The following variables are used to iterate through the current doclist */
   114696   char *pOffsetList;
   114697   sqlite3_int64 iDocid;
   114698 };
   114699 
   114700 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
   114701 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
   114702 
   114703 /*
   114704 ** An instance of this structure is used to create a segment b-tree in the
   114705 ** database. The internal details of this type are only accessed by the
   114706 ** following functions:
   114707 **
   114708 **   fts3SegWriterAdd()
   114709 **   fts3SegWriterFlush()
   114710 **   fts3SegWriterFree()
   114711 */
   114712 struct SegmentWriter {
   114713   SegmentNode *pTree;             /* Pointer to interior tree structure */
   114714   sqlite3_int64 iFirst;           /* First slot in %_segments written */
   114715   sqlite3_int64 iFree;            /* Next free slot in %_segments */
   114716   char *zTerm;                    /* Pointer to previous term buffer */
   114717   int nTerm;                      /* Number of bytes in zTerm */
   114718   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   114719   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   114720   int nSize;                      /* Size of allocation at aData */
   114721   int nData;                      /* Bytes of data in aData */
   114722   char *aData;                    /* Pointer to block from malloc() */
   114723 };
   114724 
   114725 /*
   114726 ** Type SegmentNode is used by the following three functions to create
   114727 ** the interior part of the segment b+-tree structures (everything except
   114728 ** the leaf nodes). These functions and type are only ever used by code
   114729 ** within the fts3SegWriterXXX() family of functions described above.
   114730 **
   114731 **   fts3NodeAddTerm()
   114732 **   fts3NodeWrite()
   114733 **   fts3NodeFree()
   114734 */
   114735 struct SegmentNode {
   114736   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
   114737   SegmentNode *pRight;            /* Pointer to right-sibling */
   114738   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
   114739   int nEntry;                     /* Number of terms written to node so far */
   114740   char *zTerm;                    /* Pointer to previous term buffer */
   114741   int nTerm;                      /* Number of bytes in zTerm */
   114742   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
   114743   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
   114744   int nData;                      /* Bytes of valid data so far */
   114745   char *aData;                    /* Node data */
   114746 };
   114747 
   114748 /*
   114749 ** Valid values for the second argument to fts3SqlStmt().
   114750 */
   114751 #define SQL_DELETE_CONTENT             0
   114752 #define SQL_IS_EMPTY                   1
   114753 #define SQL_DELETE_ALL_CONTENT         2
   114754 #define SQL_DELETE_ALL_SEGMENTS        3
   114755 #define SQL_DELETE_ALL_SEGDIR          4
   114756 #define SQL_DELETE_ALL_DOCSIZE         5
   114757 #define SQL_DELETE_ALL_STAT            6
   114758 #define SQL_SELECT_CONTENT_BY_ROWID    7
   114759 #define SQL_NEXT_SEGMENT_INDEX         8
   114760 #define SQL_INSERT_SEGMENTS            9
   114761 #define SQL_NEXT_SEGMENTS_ID          10
   114762 #define SQL_INSERT_SEGDIR             11
   114763 #define SQL_SELECT_LEVEL              12
   114764 #define SQL_SELECT_ALL_LEVEL          13
   114765 #define SQL_SELECT_LEVEL_COUNT        14
   114766 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
   114767 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
   114768 #define SQL_DELETE_SEGMENTS_RANGE     17
   114769 #define SQL_CONTENT_INSERT            18
   114770 #define SQL_DELETE_DOCSIZE            19
   114771 #define SQL_REPLACE_DOCSIZE           20
   114772 #define SQL_SELECT_DOCSIZE            21
   114773 #define SQL_SELECT_DOCTOTAL           22
   114774 #define SQL_REPLACE_DOCTOTAL          23
   114775 
   114776 /*
   114777 ** This function is used to obtain an SQLite prepared statement handle
   114778 ** for the statement identified by the second argument. If successful,
   114779 ** *pp is set to the requested statement handle and SQLITE_OK returned.
   114780 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
   114781 **
   114782 ** If argument apVal is not NULL, then it must point to an array with
   114783 ** at least as many entries as the requested statement has bound
   114784 ** parameters. The values are bound to the statements parameters before
   114785 ** returning.
   114786 */
   114787 static int fts3SqlStmt(
   114788   Fts3Table *p,                   /* Virtual table handle */
   114789   int eStmt,                      /* One of the SQL_XXX constants above */
   114790   sqlite3_stmt **pp,              /* OUT: Statement handle */
   114791   sqlite3_value **apVal           /* Values to bind to statement */
   114792 ){
   114793   const char *azSql[] = {
   114794 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
   114795 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
   114796 /* 2  */  "DELETE FROM %Q.'%q_content'",
   114797 /* 3  */  "DELETE FROM %Q.'%q_segments'",
   114798 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
   114799 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
   114800 /* 6  */  "DELETE FROM %Q.'%q_stat'",
   114801 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
   114802 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
   114803 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
   114804 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
   114805 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
   114806 
   114807           /* Return segments in order from oldest to newest.*/
   114808 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   114809             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
   114810 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
   114811             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
   114812 
   114813 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
   114814 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
   114815 
   114816 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
   114817 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
   114818 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
   114819 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
   114820 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
   114821 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
   114822 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
   114823 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
   114824   };
   114825   int rc = SQLITE_OK;
   114826   sqlite3_stmt *pStmt;
   114827 
   114828   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   114829   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
   114830 
   114831   pStmt = p->aStmt[eStmt];
   114832   if( !pStmt ){
   114833     char *zSql;
   114834     if( eStmt==SQL_CONTENT_INSERT ){
   114835       int i;                      /* Iterator variable */
   114836       char *zVarlist;             /* The "?, ?, ..." string */
   114837       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
   114838       if( !zVarlist ){
   114839         *pp = 0;
   114840         return SQLITE_NOMEM;
   114841       }
   114842       zVarlist[0] = '?';
   114843       zVarlist[p->nColumn*2+1] = '\0';
   114844       for(i=1; i<=p->nColumn; i++){
   114845         zVarlist[i*2-1] = ',';
   114846         zVarlist[i*2] = '?';
   114847       }
   114848       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
   114849     }else{
   114850       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
   114851     }
   114852     if( !zSql ){
   114853       rc = SQLITE_NOMEM;
   114854     }else{
   114855       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
   114856       sqlite3_free(zSql);
   114857       assert( rc==SQLITE_OK || pStmt==0 );
   114858       p->aStmt[eStmt] = pStmt;
   114859     }
   114860   }
   114861   if( apVal ){
   114862     int i;
   114863     int nParam = sqlite3_bind_parameter_count(pStmt);
   114864     for(i=0; rc==SQLITE_OK && i<nParam; i++){
   114865       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
   114866     }
   114867   }
   114868   *pp = pStmt;
   114869   return rc;
   114870 }
   114871 
   114872 static int fts3SelectDocsize(
   114873   Fts3Table *pTab,                /* FTS3 table handle */
   114874   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
   114875   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
   114876   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   114877 ){
   114878   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
   114879   int rc;                         /* Return code */
   114880 
   114881   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
   114882 
   114883   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
   114884   if( rc==SQLITE_OK ){
   114885     if( eStmt==SQL_SELECT_DOCSIZE ){
   114886       sqlite3_bind_int64(pStmt, 1, iDocid);
   114887     }
   114888     rc = sqlite3_step(pStmt);
   114889     if( rc!=SQLITE_ROW ){
   114890       rc = sqlite3_reset(pStmt);
   114891       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
   114892       pStmt = 0;
   114893     }else{
   114894       rc = SQLITE_OK;
   114895     }
   114896   }
   114897 
   114898   *ppStmt = pStmt;
   114899   return rc;
   114900 }
   114901 
   114902 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
   114903   Fts3Table *pTab,                /* Fts3 table handle */
   114904   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   114905 ){
   114906   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
   114907 }
   114908 
   114909 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
   114910   Fts3Table *pTab,                /* Fts3 table handle */
   114911   sqlite3_int64 iDocid,           /* Docid to read size data for */
   114912   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
   114913 ){
   114914   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
   114915 }
   114916 
   114917 /*
   114918 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
   114919 ** array apVal[] to the SQL statement identified by eStmt, the statement
   114920 ** is executed.
   114921 **
   114922 ** Returns SQLITE_OK if the statement is successfully executed, or an
   114923 ** SQLite error code otherwise.
   114924 */
   114925 static void fts3SqlExec(
   114926   int *pRC,                /* Result code */
   114927   Fts3Table *p,            /* The FTS3 table */
   114928   int eStmt,               /* Index of statement to evaluate */
   114929   sqlite3_value **apVal    /* Parameters to bind */
   114930 ){
   114931   sqlite3_stmt *pStmt;
   114932   int rc;
   114933   if( *pRC ) return;
   114934   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   114935   if( rc==SQLITE_OK ){
   114936     sqlite3_step(pStmt);
   114937     rc = sqlite3_reset(pStmt);
   114938   }
   114939   *pRC = rc;
   114940 }
   114941 
   114942 
   114943 /*
   114944 ** This function ensures that the caller has obtained a shared-cache
   114945 ** table-lock on the %_content table. This is required before reading
   114946 ** data from the fts3 table. If this lock is not acquired first, then
   114947 ** the caller may end up holding read-locks on the %_segments and %_segdir
   114948 ** tables, but no read-lock on the %_content table. If this happens
   114949 ** a second connection will be able to write to the fts3 table, but
   114950 ** attempting to commit those writes might return SQLITE_LOCKED or
   114951 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
   114952 ** write-locks on the %_segments and %_segdir ** tables).
   114953 **
   114954 ** We try to avoid this because if FTS3 returns any error when committing
   114955 ** a transaction, the whole transaction will be rolled back. And this is
   114956 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
   114957 ** still happen if the user reads data directly from the %_segments or
   114958 ** %_segdir tables instead of going through FTS3 though.
   114959 */
   114960 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
   114961   int rc;                         /* Return code */
   114962   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
   114963 
   114964   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
   114965   if( rc==SQLITE_OK ){
   114966     sqlite3_bind_null(pStmt, 1);
   114967     sqlite3_step(pStmt);
   114968     rc = sqlite3_reset(pStmt);
   114969   }
   114970   return rc;
   114971 }
   114972 
   114973 /*
   114974 ** Set *ppStmt to a statement handle that may be used to iterate through
   114975 ** all rows in the %_segdir table, from oldest to newest. If successful,
   114976 ** return SQLITE_OK. If an error occurs while preparing the statement,
   114977 ** return an SQLite error code.
   114978 **
   114979 ** There is only ever one instance of this SQL statement compiled for
   114980 ** each FTS3 table.
   114981 **
   114982 ** The statement returns the following columns from the %_segdir table:
   114983 **
   114984 **   0: idx
   114985 **   1: start_block
   114986 **   2: leaves_end_block
   114987 **   3: end_block
   114988 **   4: root
   114989 */
   114990 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
   114991   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
   114992 }
   114993 
   114994 
   114995 /*
   114996 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
   114997 ** if successful, or an SQLite error code otherwise.
   114998 **
   114999 ** This function also serves to allocate the PendingList structure itself.
   115000 ** For example, to create a new PendingList structure containing two
   115001 ** varints:
   115002 **
   115003 **   PendingList *p = 0;
   115004 **   fts3PendingListAppendVarint(&p, 1);
   115005 **   fts3PendingListAppendVarint(&p, 2);
   115006 */
   115007 static int fts3PendingListAppendVarint(
   115008   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
   115009   sqlite3_int64 i                 /* Value to append to data */
   115010 ){
   115011   PendingList *p = *pp;
   115012 
   115013   /* Allocate or grow the PendingList as required. */
   115014   if( !p ){
   115015     p = sqlite3_malloc(sizeof(*p) + 100);
   115016     if( !p ){
   115017       return SQLITE_NOMEM;
   115018     }
   115019     p->nSpace = 100;
   115020     p->aData = (char *)&p[1];
   115021     p->nData = 0;
   115022   }
   115023   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
   115024     int nNew = p->nSpace * 2;
   115025     p = sqlite3_realloc(p, sizeof(*p) + nNew);
   115026     if( !p ){
   115027       sqlite3_free(*pp);
   115028       *pp = 0;
   115029       return SQLITE_NOMEM;
   115030     }
   115031     p->nSpace = nNew;
   115032     p->aData = (char *)&p[1];
   115033   }
   115034 
   115035   /* Append the new serialized varint to the end of the list. */
   115036   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
   115037   p->aData[p->nData] = '\0';
   115038   *pp = p;
   115039   return SQLITE_OK;
   115040 }
   115041 
   115042 /*
   115043 ** Add a docid/column/position entry to a PendingList structure. Non-zero
   115044 ** is returned if the structure is sqlite3_realloced as part of adding
   115045 ** the entry. Otherwise, zero.
   115046 **
   115047 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
   115048 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
   115049 ** it is set to SQLITE_OK.
   115050 */
   115051 static int fts3PendingListAppend(
   115052   PendingList **pp,               /* IN/OUT: PendingList structure */
   115053   sqlite3_int64 iDocid,           /* Docid for entry to add */
   115054   sqlite3_int64 iCol,             /* Column for entry to add */
   115055   sqlite3_int64 iPos,             /* Position of term for entry to add */
   115056   int *pRc                        /* OUT: Return code */
   115057 ){
   115058   PendingList *p = *pp;
   115059   int rc = SQLITE_OK;
   115060 
   115061   assert( !p || p->iLastDocid<=iDocid );
   115062 
   115063   if( !p || p->iLastDocid!=iDocid ){
   115064     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
   115065     if( p ){
   115066       assert( p->nData<p->nSpace );
   115067       assert( p->aData[p->nData]==0 );
   115068       p->nData++;
   115069     }
   115070     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
   115071       goto pendinglistappend_out;
   115072     }
   115073     p->iLastCol = -1;
   115074     p->iLastPos = 0;
   115075     p->iLastDocid = iDocid;
   115076   }
   115077   if( iCol>0 && p->iLastCol!=iCol ){
   115078     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
   115079      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
   115080     ){
   115081       goto pendinglistappend_out;
   115082     }
   115083     p->iLastCol = iCol;
   115084     p->iLastPos = 0;
   115085   }
   115086   if( iCol>=0 ){
   115087     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
   115088     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
   115089     if( rc==SQLITE_OK ){
   115090       p->iLastPos = iPos;
   115091     }
   115092   }
   115093 
   115094  pendinglistappend_out:
   115095   *pRc = rc;
   115096   if( p!=*pp ){
   115097     *pp = p;
   115098     return 1;
   115099   }
   115100   return 0;
   115101 }
   115102 
   115103 /*
   115104 ** Tokenize the nul-terminated string zText and add all tokens to the
   115105 ** pending-terms hash-table. The docid used is that currently stored in
   115106 ** p->iPrevDocid, and the column is specified by argument iCol.
   115107 **
   115108 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   115109 */
   115110 static int fts3PendingTermsAdd(
   115111   Fts3Table *p,                   /* Table into which text will be inserted */
   115112   const char *zText,              /* Text of document to be inserted */
   115113   int iCol,                       /* Column into which text is being inserted */
   115114   u32 *pnWord                     /* OUT: Number of tokens inserted */
   115115 ){
   115116   int rc;
   115117   int iStart;
   115118   int iEnd;
   115119   int iPos;
   115120   int nWord = 0;
   115121 
   115122   char const *zToken;
   115123   int nToken;
   115124 
   115125   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
   115126   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
   115127   sqlite3_tokenizer_cursor *pCsr;
   115128   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
   115129       const char**,int*,int*,int*,int*);
   115130 
   115131   assert( pTokenizer && pModule );
   115132 
   115133   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
   115134   if( rc!=SQLITE_OK ){
   115135     return rc;
   115136   }
   115137   pCsr->pTokenizer = pTokenizer;
   115138 
   115139   xNext = pModule->xNext;
   115140   while( SQLITE_OK==rc
   115141       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
   115142   ){
   115143     PendingList *pList;
   115144 
   115145     if( iPos>=nWord ) nWord = iPos+1;
   115146 
   115147     /* Positions cannot be negative; we use -1 as a terminator internally.
   115148     ** Tokens must have a non-zero length.
   115149     */
   115150     if( iPos<0 || !zToken || nToken<=0 ){
   115151       rc = SQLITE_ERROR;
   115152       break;
   115153     }
   115154 
   115155     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
   115156     if( pList ){
   115157       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
   115158     }
   115159     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
   115160       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
   115161         /* Malloc failed while inserting the new entry. This can only
   115162         ** happen if there was no previous entry for this token.
   115163         */
   115164         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
   115165         sqlite3_free(pList);
   115166         rc = SQLITE_NOMEM;
   115167       }
   115168     }
   115169     if( rc==SQLITE_OK ){
   115170       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
   115171     }
   115172   }
   115173 
   115174   pModule->xClose(pCsr);
   115175   *pnWord = nWord;
   115176   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
   115177 }
   115178 
   115179 /*
   115180 ** Calling this function indicates that subsequent calls to
   115181 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
   115182 ** contents of the document with docid iDocid.
   115183 */
   115184 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
   115185   /* TODO(shess) Explore whether partially flushing the buffer on
   115186   ** forced-flush would provide better performance.  I suspect that if
   115187   ** we ordered the doclists by size and flushed the largest until the
   115188   ** buffer was half empty, that would let the less frequent terms
   115189   ** generate longer doclists.
   115190   */
   115191   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
   115192     int rc = sqlite3Fts3PendingTermsFlush(p);
   115193     if( rc!=SQLITE_OK ) return rc;
   115194   }
   115195   p->iPrevDocid = iDocid;
   115196   return SQLITE_OK;
   115197 }
   115198 
   115199 /*
   115200 ** Discard the contents of the pending-terms hash table.
   115201 */
   115202 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   115203   Fts3HashElem *pElem;
   115204   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
   115205     sqlite3_free(fts3HashData(pElem));
   115206   }
   115207   fts3HashClear(&p->pendingTerms);
   115208   p->nPendingData = 0;
   115209 }
   115210 
   115211 /*
   115212 ** This function is called by the xUpdate() method as part of an INSERT
   115213 ** operation. It adds entries for each term in the new record to the
   115214 ** pendingTerms hash table.
   115215 **
   115216 ** Argument apVal is the same as the similarly named argument passed to
   115217 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
   115218 */
   115219 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
   115220   int i;                          /* Iterator variable */
   115221   for(i=2; i<p->nColumn+2; i++){
   115222     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
   115223     if( zText ){
   115224       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
   115225       if( rc!=SQLITE_OK ){
   115226         return rc;
   115227       }
   115228     }
   115229     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
   115230   }
   115231   return SQLITE_OK;
   115232 }
   115233 
   115234 /*
   115235 ** This function is called by the xUpdate() method for an INSERT operation.
   115236 ** The apVal parameter is passed a copy of the apVal argument passed by
   115237 ** SQLite to the xUpdate() method. i.e:
   115238 **
   115239 **   apVal[0]                Not used for INSERT.
   115240 **   apVal[1]                rowid
   115241 **   apVal[2]                Left-most user-defined column
   115242 **   ...
   115243 **   apVal[p->nColumn+1]     Right-most user-defined column
   115244 **   apVal[p->nColumn+2]     Hidden column with same name as table
   115245 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
   115246 */
   115247 static int fts3InsertData(
   115248   Fts3Table *p,                   /* Full-text table */
   115249   sqlite3_value **apVal,          /* Array of values to insert */
   115250   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
   115251 ){
   115252   int rc;                         /* Return code */
   115253   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
   115254 
   115255   /* Locate the statement handle used to insert data into the %_content
   115256   ** table. The SQL for this statement is:
   115257   **
   115258   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
   115259   **
   115260   ** The statement features N '?' variables, where N is the number of user
   115261   ** defined columns in the FTS3 table, plus one for the docid field.
   115262   */
   115263   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   115264   if( rc!=SQLITE_OK ){
   115265     return rc;
   115266   }
   115267 
   115268   /* There is a quirk here. The users INSERT statement may have specified
   115269   ** a value for the "rowid" field, for the "docid" field, or for both.
   115270   ** Which is a problem, since "rowid" and "docid" are aliases for the
   115271   ** same value. For example:
   115272   **
   115273   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
   115274   **
   115275   ** In FTS3, this is an error. It is an error to specify non-NULL values
   115276   ** for both docid and some other rowid alias.
   115277   */
   115278   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
   115279     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
   115280      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
   115281     ){
   115282       /* A rowid/docid conflict. */
   115283       return SQLITE_ERROR;
   115284     }
   115285     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
   115286     if( rc!=SQLITE_OK ) return rc;
   115287   }
   115288 
   115289   /* Execute the statement to insert the record. Set *piDocid to the
   115290   ** new docid value.
   115291   */
   115292   sqlite3_step(pContentInsert);
   115293   rc = sqlite3_reset(pContentInsert);
   115294 
   115295   *piDocid = sqlite3_last_insert_rowid(p->db);
   115296   return rc;
   115297 }
   115298 
   115299 
   115300 
   115301 /*
   115302 ** Remove all data from the FTS3 table. Clear the hash table containing
   115303 ** pending terms.
   115304 */
   115305 static int fts3DeleteAll(Fts3Table *p){
   115306   int rc = SQLITE_OK;             /* Return code */
   115307 
   115308   /* Discard the contents of the pending-terms hash table. */
   115309   sqlite3Fts3PendingTermsClear(p);
   115310 
   115311   /* Delete everything from the %_content, %_segments and %_segdir tables. */
   115312   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
   115313   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
   115314   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   115315   if( p->bHasDocsize ){
   115316     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
   115317   }
   115318   if( p->bHasStat ){
   115319     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
   115320   }
   115321   return rc;
   115322 }
   115323 
   115324 /*
   115325 ** The first element in the apVal[] array is assumed to contain the docid
   115326 ** (an integer) of a row about to be deleted. Remove all terms from the
   115327 ** full-text index.
   115328 */
   115329 static void fts3DeleteTerms(
   115330   int *pRC,               /* Result code */
   115331   Fts3Table *p,           /* The FTS table to delete from */
   115332   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
   115333   u32 *aSz                /* Sizes of deleted document written here */
   115334 ){
   115335   int rc;
   115336   sqlite3_stmt *pSelect;
   115337 
   115338   if( *pRC ) return;
   115339   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
   115340   if( rc==SQLITE_OK ){
   115341     if( SQLITE_ROW==sqlite3_step(pSelect) ){
   115342       int i;
   115343       for(i=1; i<=p->nColumn; i++){
   115344         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
   115345         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
   115346         if( rc!=SQLITE_OK ){
   115347           sqlite3_reset(pSelect);
   115348           *pRC = rc;
   115349           return;
   115350         }
   115351         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
   115352       }
   115353     }
   115354     rc = sqlite3_reset(pSelect);
   115355   }else{
   115356     sqlite3_reset(pSelect);
   115357   }
   115358   *pRC = rc;
   115359 }
   115360 
   115361 /*
   115362 ** Forward declaration to account for the circular dependency between
   115363 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
   115364 */
   115365 static int fts3SegmentMerge(Fts3Table *, int);
   115366 
   115367 /*
   115368 ** This function allocates a new level iLevel index in the segdir table.
   115369 ** Usually, indexes are allocated within a level sequentially starting
   115370 ** with 0, so the allocated index is one greater than the value returned
   115371 ** by:
   115372 **
   115373 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
   115374 **
   115375 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
   115376 ** level, they are merged into a single level (iLevel+1) segment and the
   115377 ** allocated index is 0.
   115378 **
   115379 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
   115380 ** returned. Otherwise, an SQLite error code is returned.
   115381 */
   115382 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
   115383   int rc;                         /* Return Code */
   115384   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
   115385   int iNext = 0;                  /* Result of query pNextIdx */
   115386 
   115387   /* Set variable iNext to the next available segdir index at level iLevel. */
   115388   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
   115389   if( rc==SQLITE_OK ){
   115390     sqlite3_bind_int(pNextIdx, 1, iLevel);
   115391     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
   115392       iNext = sqlite3_column_int(pNextIdx, 0);
   115393     }
   115394     rc = sqlite3_reset(pNextIdx);
   115395   }
   115396 
   115397   if( rc==SQLITE_OK ){
   115398     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
   115399     ** full, merge all segments in level iLevel into a single iLevel+1
   115400     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
   115401     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
   115402     */
   115403     if( iNext>=FTS3_MERGE_COUNT ){
   115404       rc = fts3SegmentMerge(p, iLevel);
   115405       *piIdx = 0;
   115406     }else{
   115407       *piIdx = iNext;
   115408     }
   115409   }
   115410 
   115411   return rc;
   115412 }
   115413 
   115414 /*
   115415 ** The %_segments table is declared as follows:
   115416 **
   115417 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
   115418 **
   115419 ** This function reads data from a single row of the %_segments table. The
   115420 ** specific row is identified by the iBlockid parameter. If paBlob is not
   115421 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
   115422 ** with the contents of the blob stored in the "block" column of the
   115423 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
   115424 ** to the size of the blob in bytes before returning.
   115425 **
   115426 ** If an error occurs, or the table does not contain the specified row,
   115427 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
   115428 ** paBlob is non-NULL, then it is the responsibility of the caller to
   115429 ** eventually free the returned buffer.
   115430 **
   115431 ** This function may leave an open sqlite3_blob* handle in the
   115432 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
   115433 ** to this function. The handle may be closed by calling the
   115434 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
   115435 ** performance improvement, but the blob handle should always be closed
   115436 ** before control is returned to the user (to prevent a lock being held
   115437 ** on the database file for longer than necessary). Thus, any virtual table
   115438 ** method (xFilter etc.) that may directly or indirectly call this function
   115439 ** must call sqlite3Fts3SegmentsClose() before returning.
   115440 */
   115441 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
   115442   Fts3Table *p,                   /* FTS3 table handle */
   115443   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
   115444   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
   115445   int *pnBlob                     /* OUT: Size of blob data */
   115446 ){
   115447   int rc;                         /* Return code */
   115448 
   115449   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
   115450   assert( pnBlob);
   115451 
   115452   if( p->pSegments ){
   115453     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
   115454   }else{
   115455     if( 0==p->zSegmentsTbl ){
   115456       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
   115457       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
   115458     }
   115459     rc = sqlite3_blob_open(
   115460        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
   115461     );
   115462   }
   115463 
   115464   if( rc==SQLITE_OK ){
   115465     int nByte = sqlite3_blob_bytes(p->pSegments);
   115466     if( paBlob ){
   115467       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
   115468       if( !aByte ){
   115469         rc = SQLITE_NOMEM;
   115470       }else{
   115471         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
   115472         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
   115473         if( rc!=SQLITE_OK ){
   115474           sqlite3_free(aByte);
   115475           aByte = 0;
   115476         }
   115477       }
   115478       *paBlob = aByte;
   115479     }
   115480     *pnBlob = nByte;
   115481   }
   115482 
   115483   return rc;
   115484 }
   115485 
   115486 /*
   115487 ** Close the blob handle at p->pSegments, if it is open. See comments above
   115488 ** the sqlite3Fts3ReadBlock() function for details.
   115489 */
   115490 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   115491   sqlite3_blob_close(p->pSegments);
   115492   p->pSegments = 0;
   115493 }
   115494 
   115495 /*
   115496 ** Move the iterator passed as the first argument to the next term in the
   115497 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
   115498 ** SQLITE_DONE. Otherwise, an SQLite error code.
   115499 */
   115500 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
   115501   char *pNext;                    /* Cursor variable */
   115502   int nPrefix;                    /* Number of bytes in term prefix */
   115503   int nSuffix;                    /* Number of bytes in term suffix */
   115504 
   115505   if( !pReader->aDoclist ){
   115506     pNext = pReader->aNode;
   115507   }else{
   115508     pNext = &pReader->aDoclist[pReader->nDoclist];
   115509   }
   115510 
   115511   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
   115512     int rc;                       /* Return code from Fts3ReadBlock() */
   115513 
   115514     if( fts3SegReaderIsPending(pReader) ){
   115515       Fts3HashElem *pElem = *(pReader->ppNextElem);
   115516       if( pElem==0 ){
   115517         pReader->aNode = 0;
   115518       }else{
   115519         PendingList *pList = (PendingList *)fts3HashData(pElem);
   115520         pReader->zTerm = (char *)fts3HashKey(pElem);
   115521         pReader->nTerm = fts3HashKeysize(pElem);
   115522         pReader->nNode = pReader->nDoclist = pList->nData + 1;
   115523         pReader->aNode = pReader->aDoclist = pList->aData;
   115524         pReader->ppNextElem++;
   115525         assert( pReader->aNode );
   115526       }
   115527       return SQLITE_OK;
   115528     }
   115529 
   115530     if( !fts3SegReaderIsRootOnly(pReader) ){
   115531       sqlite3_free(pReader->aNode);
   115532     }
   115533     pReader->aNode = 0;
   115534 
   115535     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
   115536     ** blocks have already been traversed.  */
   115537     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
   115538     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
   115539       return SQLITE_OK;
   115540     }
   115541 
   115542     rc = sqlite3Fts3ReadBlock(
   115543         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
   115544     );
   115545     if( rc!=SQLITE_OK ) return rc;
   115546     pNext = pReader->aNode;
   115547   }
   115548 
   115549   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   115550   ** safe (no risk of overread) even if the node data is corrupted.
   115551   */
   115552   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
   115553   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
   115554   if( nPrefix<0 || nSuffix<=0
   115555    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
   115556   ){
   115557     return SQLITE_CORRUPT;
   115558   }
   115559 
   115560   if( nPrefix+nSuffix>pReader->nTermAlloc ){
   115561     int nNew = (nPrefix+nSuffix)*2;
   115562     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
   115563     if( !zNew ){
   115564       return SQLITE_NOMEM;
   115565     }
   115566     pReader->zTerm = zNew;
   115567     pReader->nTermAlloc = nNew;
   115568   }
   115569   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
   115570   pReader->nTerm = nPrefix+nSuffix;
   115571   pNext += nSuffix;
   115572   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
   115573   pReader->aDoclist = pNext;
   115574   pReader->pOffsetList = 0;
   115575 
   115576   /* Check that the doclist does not appear to extend past the end of the
   115577   ** b-tree node. And that the final byte of the doclist is 0x00. If either
   115578   ** of these statements is untrue, then the data structure is corrupt.
   115579   */
   115580   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
   115581    || pReader->aDoclist[pReader->nDoclist-1]
   115582   ){
   115583     return SQLITE_CORRUPT;
   115584   }
   115585   return SQLITE_OK;
   115586 }
   115587 
   115588 /*
   115589 ** Set the SegReader to point to the first docid in the doclist associated
   115590 ** with the current term.
   115591 */
   115592 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
   115593   int n;
   115594   assert( pReader->aDoclist );
   115595   assert( !pReader->pOffsetList );
   115596   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
   115597   pReader->pOffsetList = &pReader->aDoclist[n];
   115598 }
   115599 
   115600 /*
   115601 ** Advance the SegReader to point to the next docid in the doclist
   115602 ** associated with the current term.
   115603 **
   115604 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
   115605 ** *ppOffsetList is set to point to the first column-offset list
   115606 ** in the doclist entry (i.e. immediately past the docid varint).
   115607 ** *pnOffsetList is set to the length of the set of column-offset
   115608 ** lists, not including the nul-terminator byte. For example:
   115609 */
   115610 static void fts3SegReaderNextDocid(
   115611   Fts3SegReader *pReader,
   115612   char **ppOffsetList,
   115613   int *pnOffsetList
   115614 ){
   115615   char *p = pReader->pOffsetList;
   115616   char c = 0;
   115617 
   115618   /* Pointer p currently points at the first byte of an offset list. The
   115619   ** following two lines advance it to point one byte past the end of
   115620   ** the same offset list.
   115621   */
   115622   while( *p | c ) c = *p++ & 0x80;
   115623   p++;
   115624 
   115625   /* If required, populate the output variables with a pointer to and the
   115626   ** size of the previous offset-list.
   115627   */
   115628   if( ppOffsetList ){
   115629     *ppOffsetList = pReader->pOffsetList;
   115630     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
   115631   }
   115632 
   115633   /* If there are no more entries in the doclist, set pOffsetList to
   115634   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
   115635   ** Fts3SegReader.pOffsetList to point to the next offset list before
   115636   ** returning.
   115637   */
   115638   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
   115639     pReader->pOffsetList = 0;
   115640   }else{
   115641     sqlite3_int64 iDelta;
   115642     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
   115643     pReader->iDocid += iDelta;
   115644   }
   115645 }
   115646 
   115647 /*
   115648 ** This function is called to estimate the amount of data that will be
   115649 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
   115650 ** in units of average document size.
   115651 **
   115652 ** This can be used as follows: If the caller has a small doclist that
   115653 ** contains references to N documents, and is considering merging it with
   115654 ** a large doclist (size X "average documents"), it may opt not to load
   115655 ** the large doclist if X>N.
   115656 */
   115657 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
   115658   Fts3Cursor *pCsr,               /* FTS3 cursor handle */
   115659   Fts3SegReader *pReader,         /* Segment-reader handle */
   115660   int *pnCost                     /* IN/OUT: Number of bytes read */
   115661 ){
   115662   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
   115663   int rc = SQLITE_OK;             /* Return code */
   115664   int nCost = 0;                  /* Cost in bytes to return */
   115665   int pgsz = p->nPgsz;            /* Database page size */
   115666 
   115667   /* If this seg-reader is reading the pending-terms table, or if all data
   115668   ** for the segment is stored on the root page of the b-tree, then the cost
   115669   ** is zero. In this case all required data is already in main memory.
   115670   */
   115671   if( p->bHasStat
   115672    && !fts3SegReaderIsPending(pReader)
   115673    && !fts3SegReaderIsRootOnly(pReader)
   115674   ){
   115675     int nBlob = 0;
   115676     sqlite3_int64 iBlock;
   115677 
   115678     if( pCsr->nRowAvg==0 ){
   115679       /* The average document size, which is required to calculate the cost
   115680       ** of each doclist, has not yet been determined. Read the required
   115681       ** data from the %_stat table to calculate it.
   115682       **
   115683       ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
   115684       ** varints, where nCol is the number of columns in the FTS3 table.
   115685       ** The first varint is the number of documents currently stored in
   115686       ** the table. The following nCol varints contain the total amount of
   115687       ** data stored in all rows of each column of the table, from left
   115688       ** to right.
   115689       */
   115690       sqlite3_stmt *pStmt;
   115691       rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
   115692       if( rc ) return rc;
   115693       if( sqlite3_step(pStmt)==SQLITE_ROW ){
   115694         sqlite3_int64 nDoc = 0;
   115695         sqlite3_int64 nByte = 0;
   115696         const char *a = sqlite3_column_blob(pStmt, 0);
   115697         if( a ){
   115698           const char *pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
   115699           a += sqlite3Fts3GetVarint(a, &nDoc);
   115700           while( a<pEnd ){
   115701             a += sqlite3Fts3GetVarint(a, &nByte);
   115702           }
   115703         }
   115704 
   115705         pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz - 1) / pgsz);
   115706       }
   115707       rc = sqlite3_reset(pStmt);
   115708       if( rc!=SQLITE_OK || pCsr->nRowAvg==0 ) return rc;
   115709     }
   115710 
   115711     /* Assume that a blob flows over onto overflow pages if it is larger
   115712     ** than (pgsz-35) bytes in size (the file-format documentation
   115713     ** confirms this).
   115714     */
   115715     for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
   115716       rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
   115717       if( rc!=SQLITE_OK ) break;
   115718       if( (nBlob+35)>pgsz ){
   115719         int nOvfl = (nBlob + 34)/pgsz;
   115720         nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
   115721       }
   115722     }
   115723   }
   115724 
   115725   *pnCost += nCost;
   115726   return rc;
   115727 }
   115728 
   115729 /*
   115730 ** Free all allocations associated with the iterator passed as the
   115731 ** second argument.
   115732 */
   115733 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
   115734   if( pReader && !fts3SegReaderIsPending(pReader) ){
   115735     sqlite3_free(pReader->zTerm);
   115736     if( !fts3SegReaderIsRootOnly(pReader) ){
   115737       sqlite3_free(pReader->aNode);
   115738     }
   115739   }
   115740   sqlite3_free(pReader);
   115741 }
   115742 
   115743 /*
   115744 ** Allocate a new SegReader object.
   115745 */
   115746 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
   115747   int iAge,                       /* Segment "age". */
   115748   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
   115749   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
   115750   sqlite3_int64 iEndBlock,        /* Final block of segment */
   115751   const char *zRoot,              /* Buffer containing root node */
   115752   int nRoot,                      /* Size of buffer containing root node */
   115753   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   115754 ){
   115755   int rc = SQLITE_OK;             /* Return code */
   115756   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
   115757   int nExtra = 0;                 /* Bytes to allocate segment root node */
   115758 
   115759   assert( iStartLeaf<=iEndLeaf );
   115760   if( iStartLeaf==0 ){
   115761     nExtra = nRoot + FTS3_NODE_PADDING;
   115762   }
   115763 
   115764   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
   115765   if( !pReader ){
   115766     return SQLITE_NOMEM;
   115767   }
   115768   memset(pReader, 0, sizeof(Fts3SegReader));
   115769   pReader->iIdx = iAge;
   115770   pReader->iStartBlock = iStartLeaf;
   115771   pReader->iLeafEndBlock = iEndLeaf;
   115772   pReader->iEndBlock = iEndBlock;
   115773 
   115774   if( nExtra ){
   115775     /* The entire segment is stored in the root node. */
   115776     pReader->aNode = (char *)&pReader[1];
   115777     pReader->nNode = nRoot;
   115778     memcpy(pReader->aNode, zRoot, nRoot);
   115779     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
   115780   }else{
   115781     pReader->iCurrentBlock = iStartLeaf-1;
   115782   }
   115783 
   115784   if( rc==SQLITE_OK ){
   115785     *ppReader = pReader;
   115786   }else{
   115787     sqlite3Fts3SegReaderFree(pReader);
   115788   }
   115789   return rc;
   115790 }
   115791 
   115792 /*
   115793 ** This is a comparison function used as a qsort() callback when sorting
   115794 ** an array of pending terms by term. This occurs as part of flushing
   115795 ** the contents of the pending-terms hash table to the database.
   115796 */
   115797 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
   115798   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
   115799   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
   115800   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
   115801   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
   115802 
   115803   int n = (n1<n2 ? n1 : n2);
   115804   int c = memcmp(z1, z2, n);
   115805   if( c==0 ){
   115806     c = n1 - n2;
   115807   }
   115808   return c;
   115809 }
   115810 
   115811 /*
   115812 ** This function is used to allocate an Fts3SegReader that iterates through
   115813 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
   115814 */
   115815 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
   115816   Fts3Table *p,                   /* Virtual table handle */
   115817   const char *zTerm,              /* Term to search for */
   115818   int nTerm,                      /* Size of buffer zTerm */
   115819   int isPrefix,                   /* True for a term-prefix query */
   115820   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
   115821 ){
   115822   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
   115823   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
   115824   int nElem = 0;                  /* Size of array at aElem */
   115825   int rc = SQLITE_OK;             /* Return Code */
   115826 
   115827   if( isPrefix ){
   115828     int nAlloc = 0;               /* Size of allocated array at aElem */
   115829     Fts3HashElem *pE = 0;         /* Iterator variable */
   115830 
   115831     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
   115832       char *zKey = (char *)fts3HashKey(pE);
   115833       int nKey = fts3HashKeysize(pE);
   115834       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
   115835         if( nElem==nAlloc ){
   115836           Fts3HashElem **aElem2;
   115837           nAlloc += 16;
   115838           aElem2 = (Fts3HashElem **)sqlite3_realloc(
   115839               aElem, nAlloc*sizeof(Fts3HashElem *)
   115840           );
   115841           if( !aElem2 ){
   115842             rc = SQLITE_NOMEM;
   115843             nElem = 0;
   115844             break;
   115845           }
   115846           aElem = aElem2;
   115847         }
   115848         aElem[nElem++] = pE;
   115849       }
   115850     }
   115851 
   115852     /* If more than one term matches the prefix, sort the Fts3HashElem
   115853     ** objects in term order using qsort(). This uses the same comparison
   115854     ** callback as is used when flushing terms to disk.
   115855     */
   115856     if( nElem>1 ){
   115857       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
   115858     }
   115859 
   115860   }else{
   115861     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
   115862     if( pE ){
   115863       aElem = &pE;
   115864       nElem = 1;
   115865     }
   115866   }
   115867 
   115868   if( nElem>0 ){
   115869     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
   115870     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
   115871     if( !pReader ){
   115872       rc = SQLITE_NOMEM;
   115873     }else{
   115874       memset(pReader, 0, nByte);
   115875       pReader->iIdx = 0x7FFFFFFF;
   115876       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
   115877       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
   115878     }
   115879   }
   115880 
   115881   if( isPrefix ){
   115882     sqlite3_free(aElem);
   115883   }
   115884   *ppReader = pReader;
   115885   return rc;
   115886 }
   115887 
   115888 
   115889 /*
   115890 ** The second argument to this function is expected to be a statement of
   115891 ** the form:
   115892 **
   115893 **   SELECT
   115894 **     idx,                  -- col 0
   115895 **     start_block,          -- col 1
   115896 **     leaves_end_block,     -- col 2
   115897 **     end_block,            -- col 3
   115898 **     root                  -- col 4
   115899 **   FROM %_segdir ...
   115900 **
   115901 ** This function allocates and initializes a Fts3SegReader structure to
   115902 ** iterate through the terms stored in the segment identified by the
   115903 ** current row that pStmt is pointing to.
   115904 **
   115905 ** If successful, the Fts3SegReader is left pointing to the first term
   115906 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
   115907 ** code is returned.
   115908 */
   115909 static int fts3SegReaderNew(
   115910   sqlite3_stmt *pStmt,            /* See above */
   115911   int iAge,                       /* Segment "age". */
   115912   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
   115913 ){
   115914   return sqlite3Fts3SegReaderNew(iAge,
   115915       sqlite3_column_int64(pStmt, 1),
   115916       sqlite3_column_int64(pStmt, 2),
   115917       sqlite3_column_int64(pStmt, 3),
   115918       sqlite3_column_blob(pStmt, 4),
   115919       sqlite3_column_bytes(pStmt, 4),
   115920       ppReader
   115921   );
   115922 }
   115923 
   115924 /*
   115925 ** Compare the entries pointed to by two Fts3SegReader structures.
   115926 ** Comparison is as follows:
   115927 **
   115928 **   1) EOF is greater than not EOF.
   115929 **
   115930 **   2) The current terms (if any) are compared using memcmp(). If one
   115931 **      term is a prefix of another, the longer term is considered the
   115932 **      larger.
   115933 **
   115934 **   3) By segment age. An older segment is considered larger.
   115935 */
   115936 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   115937   int rc;
   115938   if( pLhs->aNode && pRhs->aNode ){
   115939     int rc2 = pLhs->nTerm - pRhs->nTerm;
   115940     if( rc2<0 ){
   115941       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
   115942     }else{
   115943       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
   115944     }
   115945     if( rc==0 ){
   115946       rc = rc2;
   115947     }
   115948   }else{
   115949     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
   115950   }
   115951   if( rc==0 ){
   115952     rc = pRhs->iIdx - pLhs->iIdx;
   115953   }
   115954   assert( rc!=0 );
   115955   return rc;
   115956 }
   115957 
   115958 /*
   115959 ** A different comparison function for SegReader structures. In this
   115960 ** version, it is assumed that each SegReader points to an entry in
   115961 ** a doclist for identical terms. Comparison is made as follows:
   115962 **
   115963 **   1) EOF (end of doclist in this case) is greater than not EOF.
   115964 **
   115965 **   2) By current docid.
   115966 **
   115967 **   3) By segment age. An older segment is considered larger.
   115968 */
   115969 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
   115970   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
   115971   if( rc==0 ){
   115972     if( pLhs->iDocid==pRhs->iDocid ){
   115973       rc = pRhs->iIdx - pLhs->iIdx;
   115974     }else{
   115975       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
   115976     }
   115977   }
   115978   assert( pLhs->aNode && pRhs->aNode );
   115979   return rc;
   115980 }
   115981 
   115982 /*
   115983 ** Compare the term that the Fts3SegReader object passed as the first argument
   115984 ** points to with the term specified by arguments zTerm and nTerm.
   115985 **
   115986 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
   115987 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
   115988 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
   115989 */
   115990 static int fts3SegReaderTermCmp(
   115991   Fts3SegReader *pSeg,            /* Segment reader object */
   115992   const char *zTerm,              /* Term to compare to */
   115993   int nTerm                       /* Size of term zTerm in bytes */
   115994 ){
   115995   int res = 0;
   115996   if( pSeg->aNode ){
   115997     if( pSeg->nTerm>nTerm ){
   115998       res = memcmp(pSeg->zTerm, zTerm, nTerm);
   115999     }else{
   116000       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
   116001     }
   116002     if( res==0 ){
   116003       res = pSeg->nTerm-nTerm;
   116004     }
   116005   }
   116006   return res;
   116007 }
   116008 
   116009 /*
   116010 ** Argument apSegment is an array of nSegment elements. It is known that
   116011 ** the final (nSegment-nSuspect) members are already in sorted order
   116012 ** (according to the comparison function provided). This function shuffles
   116013 ** the array around until all entries are in sorted order.
   116014 */
   116015 static void fts3SegReaderSort(
   116016   Fts3SegReader **apSegment,                     /* Array to sort entries of */
   116017   int nSegment,                                  /* Size of apSegment array */
   116018   int nSuspect,                                  /* Unsorted entry count */
   116019   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
   116020 ){
   116021   int i;                          /* Iterator variable */
   116022 
   116023   assert( nSuspect<=nSegment );
   116024 
   116025   if( nSuspect==nSegment ) nSuspect--;
   116026   for(i=nSuspect-1; i>=0; i--){
   116027     int j;
   116028     for(j=i; j<(nSegment-1); j++){
   116029       Fts3SegReader *pTmp;
   116030       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
   116031       pTmp = apSegment[j+1];
   116032       apSegment[j+1] = apSegment[j];
   116033       apSegment[j] = pTmp;
   116034     }
   116035   }
   116036 
   116037 #ifndef NDEBUG
   116038   /* Check that the list really is sorted now. */
   116039   for(i=0; i<(nSuspect-1); i++){
   116040     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
   116041   }
   116042 #endif
   116043 }
   116044 
   116045 /*
   116046 ** Insert a record into the %_segments table.
   116047 */
   116048 static int fts3WriteSegment(
   116049   Fts3Table *p,                   /* Virtual table handle */
   116050   sqlite3_int64 iBlock,           /* Block id for new block */
   116051   char *z,                        /* Pointer to buffer containing block data */
   116052   int n                           /* Size of buffer z in bytes */
   116053 ){
   116054   sqlite3_stmt *pStmt;
   116055   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
   116056   if( rc==SQLITE_OK ){
   116057     sqlite3_bind_int64(pStmt, 1, iBlock);
   116058     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
   116059     sqlite3_step(pStmt);
   116060     rc = sqlite3_reset(pStmt);
   116061   }
   116062   return rc;
   116063 }
   116064 
   116065 /*
   116066 ** Insert a record into the %_segdir table.
   116067 */
   116068 static int fts3WriteSegdir(
   116069   Fts3Table *p,                   /* Virtual table handle */
   116070   int iLevel,                     /* Value for "level" field */
   116071   int iIdx,                       /* Value for "idx" field */
   116072   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
   116073   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
   116074   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
   116075   char *zRoot,                    /* Blob value for "root" field */
   116076   int nRoot                       /* Number of bytes in buffer zRoot */
   116077 ){
   116078   sqlite3_stmt *pStmt;
   116079   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
   116080   if( rc==SQLITE_OK ){
   116081     sqlite3_bind_int(pStmt, 1, iLevel);
   116082     sqlite3_bind_int(pStmt, 2, iIdx);
   116083     sqlite3_bind_int64(pStmt, 3, iStartBlock);
   116084     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
   116085     sqlite3_bind_int64(pStmt, 5, iEndBlock);
   116086     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
   116087     sqlite3_step(pStmt);
   116088     rc = sqlite3_reset(pStmt);
   116089   }
   116090   return rc;
   116091 }
   116092 
   116093 /*
   116094 ** Return the size of the common prefix (if any) shared by zPrev and
   116095 ** zNext, in bytes. For example,
   116096 **
   116097 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
   116098 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
   116099 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
   116100 */
   116101 static int fts3PrefixCompress(
   116102   const char *zPrev,              /* Buffer containing previous term */
   116103   int nPrev,                      /* Size of buffer zPrev in bytes */
   116104   const char *zNext,              /* Buffer containing next term */
   116105   int nNext                       /* Size of buffer zNext in bytes */
   116106 ){
   116107   int n;
   116108   UNUSED_PARAMETER(nNext);
   116109   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
   116110   return n;
   116111 }
   116112 
   116113 /*
   116114 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
   116115 ** (according to memcmp) than the previous term.
   116116 */
   116117 static int fts3NodeAddTerm(
   116118   Fts3Table *p,                   /* Virtual table handle */
   116119   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   116120   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   116121   const char *zTerm,              /* Pointer to buffer containing term */
   116122   int nTerm                       /* Size of term in bytes */
   116123 ){
   116124   SegmentNode *pTree = *ppTree;
   116125   int rc;
   116126   SegmentNode *pNew;
   116127 
   116128   /* First try to append the term to the current node. Return early if
   116129   ** this is possible.
   116130   */
   116131   if( pTree ){
   116132     int nData = pTree->nData;     /* Current size of node in bytes */
   116133     int nReq = nData;             /* Required space after adding zTerm */
   116134     int nPrefix;                  /* Number of bytes of prefix compression */
   116135     int nSuffix;                  /* Suffix length */
   116136 
   116137     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
   116138     nSuffix = nTerm-nPrefix;
   116139 
   116140     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
   116141     if( nReq<=p->nNodeSize || !pTree->zTerm ){
   116142 
   116143       if( nReq>p->nNodeSize ){
   116144         /* An unusual case: this is the first term to be added to the node
   116145         ** and the static node buffer (p->nNodeSize bytes) is not large
   116146         ** enough. Use a separately malloced buffer instead This wastes
   116147         ** p->nNodeSize bytes, but since this scenario only comes about when
   116148         ** the database contain two terms that share a prefix of almost 2KB,
   116149         ** this is not expected to be a serious problem.
   116150         */
   116151         assert( pTree->aData==(char *)&pTree[1] );
   116152         pTree->aData = (char *)sqlite3_malloc(nReq);
   116153         if( !pTree->aData ){
   116154           return SQLITE_NOMEM;
   116155         }
   116156       }
   116157 
   116158       if( pTree->zTerm ){
   116159         /* There is no prefix-length field for first term in a node */
   116160         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
   116161       }
   116162 
   116163       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
   116164       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
   116165       pTree->nData = nData + nSuffix;
   116166       pTree->nEntry++;
   116167 
   116168       if( isCopyTerm ){
   116169         if( pTree->nMalloc<nTerm ){
   116170           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
   116171           if( !zNew ){
   116172             return SQLITE_NOMEM;
   116173           }
   116174           pTree->nMalloc = nTerm*2;
   116175           pTree->zMalloc = zNew;
   116176         }
   116177         pTree->zTerm = pTree->zMalloc;
   116178         memcpy(pTree->zTerm, zTerm, nTerm);
   116179         pTree->nTerm = nTerm;
   116180       }else{
   116181         pTree->zTerm = (char *)zTerm;
   116182         pTree->nTerm = nTerm;
   116183       }
   116184       return SQLITE_OK;
   116185     }
   116186   }
   116187 
   116188   /* If control flows to here, it was not possible to append zTerm to the
   116189   ** current node. Create a new node (a right-sibling of the current node).
   116190   ** If this is the first node in the tree, the term is added to it.
   116191   **
   116192   ** Otherwise, the term is not added to the new node, it is left empty for
   116193   ** now. Instead, the term is inserted into the parent of pTree. If pTree
   116194   ** has no parent, one is created here.
   116195   */
   116196   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
   116197   if( !pNew ){
   116198     return SQLITE_NOMEM;
   116199   }
   116200   memset(pNew, 0, sizeof(SegmentNode));
   116201   pNew->nData = 1 + FTS3_VARINT_MAX;
   116202   pNew->aData = (char *)&pNew[1];
   116203 
   116204   if( pTree ){
   116205     SegmentNode *pParent = pTree->pParent;
   116206     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
   116207     if( pTree->pParent==0 ){
   116208       pTree->pParent = pParent;
   116209     }
   116210     pTree->pRight = pNew;
   116211     pNew->pLeftmost = pTree->pLeftmost;
   116212     pNew->pParent = pParent;
   116213     pNew->zMalloc = pTree->zMalloc;
   116214     pNew->nMalloc = pTree->nMalloc;
   116215     pTree->zMalloc = 0;
   116216   }else{
   116217     pNew->pLeftmost = pNew;
   116218     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   116219   }
   116220 
   116221   *ppTree = pNew;
   116222   return rc;
   116223 }
   116224 
   116225 /*
   116226 ** Helper function for fts3NodeWrite().
   116227 */
   116228 static int fts3TreeFinishNode(
   116229   SegmentNode *pTree,
   116230   int iHeight,
   116231   sqlite3_int64 iLeftChild
   116232 ){
   116233   int nStart;
   116234   assert( iHeight>=1 && iHeight<128 );
   116235   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
   116236   pTree->aData[nStart] = (char)iHeight;
   116237   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
   116238   return nStart;
   116239 }
   116240 
   116241 /*
   116242 ** Write the buffer for the segment node pTree and all of its peers to the
   116243 ** database. Then call this function recursively to write the parent of
   116244 ** pTree and its peers to the database.
   116245 **
   116246 ** Except, if pTree is a root node, do not write it to the database. Instead,
   116247 ** set output variables *paRoot and *pnRoot to contain the root node.
   116248 **
   116249 ** If successful, SQLITE_OK is returned and output variable *piLast is
   116250 ** set to the largest blockid written to the database (or zero if no
   116251 ** blocks were written to the db). Otherwise, an SQLite error code is
   116252 ** returned.
   116253 */
   116254 static int fts3NodeWrite(
   116255   Fts3Table *p,                   /* Virtual table handle */
   116256   SegmentNode *pTree,             /* SegmentNode handle */
   116257   int iHeight,                    /* Height of this node in tree */
   116258   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
   116259   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
   116260   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
   116261   char **paRoot,                  /* OUT: Data for root node */
   116262   int *pnRoot                     /* OUT: Size of root node in bytes */
   116263 ){
   116264   int rc = SQLITE_OK;
   116265 
   116266   if( !pTree->pParent ){
   116267     /* Root node of the tree. */
   116268     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
   116269     *piLast = iFree-1;
   116270     *pnRoot = pTree->nData - nStart;
   116271     *paRoot = &pTree->aData[nStart];
   116272   }else{
   116273     SegmentNode *pIter;
   116274     sqlite3_int64 iNextFree = iFree;
   116275     sqlite3_int64 iNextLeaf = iLeaf;
   116276     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
   116277       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
   116278       int nWrite = pIter->nData - nStart;
   116279 
   116280       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
   116281       iNextFree++;
   116282       iNextLeaf += (pIter->nEntry+1);
   116283     }
   116284     if( rc==SQLITE_OK ){
   116285       assert( iNextLeaf==iFree );
   116286       rc = fts3NodeWrite(
   116287           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
   116288       );
   116289     }
   116290   }
   116291 
   116292   return rc;
   116293 }
   116294 
   116295 /*
   116296 ** Free all memory allocations associated with the tree pTree.
   116297 */
   116298 static void fts3NodeFree(SegmentNode *pTree){
   116299   if( pTree ){
   116300     SegmentNode *p = pTree->pLeftmost;
   116301     fts3NodeFree(p->pParent);
   116302     while( p ){
   116303       SegmentNode *pRight = p->pRight;
   116304       if( p->aData!=(char *)&p[1] ){
   116305         sqlite3_free(p->aData);
   116306       }
   116307       assert( pRight==0 || p->zMalloc==0 );
   116308       sqlite3_free(p->zMalloc);
   116309       sqlite3_free(p);
   116310       p = pRight;
   116311     }
   116312   }
   116313 }
   116314 
   116315 /*
   116316 ** Add a term to the segment being constructed by the SegmentWriter object
   116317 ** *ppWriter. When adding the first term to a segment, *ppWriter should
   116318 ** be passed NULL. This function will allocate a new SegmentWriter object
   116319 ** and return it via the input/output variable *ppWriter in this case.
   116320 **
   116321 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
   116322 */
   116323 static int fts3SegWriterAdd(
   116324   Fts3Table *p,                   /* Virtual table handle */
   116325   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   116326   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   116327   const char *zTerm,              /* Pointer to buffer containing term */
   116328   int nTerm,                      /* Size of term in bytes */
   116329   const char *aDoclist,           /* Pointer to buffer containing doclist */
   116330   int nDoclist                    /* Size of doclist in bytes */
   116331 ){
   116332   int nPrefix;                    /* Size of term prefix in bytes */
   116333   int nSuffix;                    /* Size of term suffix in bytes */
   116334   int nReq;                       /* Number of bytes required on leaf page */
   116335   int nData;
   116336   SegmentWriter *pWriter = *ppWriter;
   116337 
   116338   if( !pWriter ){
   116339     int rc;
   116340     sqlite3_stmt *pStmt;
   116341 
   116342     /* Allocate the SegmentWriter structure */
   116343     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
   116344     if( !pWriter ) return SQLITE_NOMEM;
   116345     memset(pWriter, 0, sizeof(SegmentWriter));
   116346     *ppWriter = pWriter;
   116347 
   116348     /* Allocate a buffer in which to accumulate data */
   116349     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
   116350     if( !pWriter->aData ) return SQLITE_NOMEM;
   116351     pWriter->nSize = p->nNodeSize;
   116352 
   116353     /* Find the next free blockid in the %_segments table */
   116354     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
   116355     if( rc!=SQLITE_OK ) return rc;
   116356     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   116357       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
   116358       pWriter->iFirst = pWriter->iFree;
   116359     }
   116360     rc = sqlite3_reset(pStmt);
   116361     if( rc!=SQLITE_OK ) return rc;
   116362   }
   116363   nData = pWriter->nData;
   116364 
   116365   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   116366   nSuffix = nTerm-nPrefix;
   116367 
   116368   /* Figure out how many bytes are required by this new entry */
   116369   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
   116370     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
   116371     nSuffix +                               /* Term suffix */
   116372     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
   116373     nDoclist;                               /* Doclist data */
   116374 
   116375   if( nData>0 && nData+nReq>p->nNodeSize ){
   116376     int rc;
   116377 
   116378     /* The current leaf node is full. Write it out to the database. */
   116379     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
   116380     if( rc!=SQLITE_OK ) return rc;
   116381 
   116382     /* Add the current term to the interior node tree. The term added to
   116383     ** the interior tree must:
   116384     **
   116385     **   a) be greater than the largest term on the leaf node just written
   116386     **      to the database (still available in pWriter->zTerm), and
   116387     **
   116388     **   b) be less than or equal to the term about to be added to the new
   116389     **      leaf node (zTerm/nTerm).
   116390     **
   116391     ** In other words, it must be the prefix of zTerm 1 byte longer than
   116392     ** the common prefix (if any) of zTerm and pWriter->zTerm.
   116393     */
   116394     assert( nPrefix<nTerm );
   116395     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
   116396     if( rc!=SQLITE_OK ) return rc;
   116397 
   116398     nData = 0;
   116399     pWriter->nTerm = 0;
   116400 
   116401     nPrefix = 0;
   116402     nSuffix = nTerm;
   116403     nReq = 1 +                              /* varint containing prefix size */
   116404       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
   116405       nTerm +                               /* Term suffix */
   116406       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
   116407       nDoclist;                             /* Doclist data */
   116408   }
   116409 
   116410   /* If the buffer currently allocated is too small for this entry, realloc
   116411   ** the buffer to make it large enough.
   116412   */
   116413   if( nReq>pWriter->nSize ){
   116414     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
   116415     if( !aNew ) return SQLITE_NOMEM;
   116416     pWriter->aData = aNew;
   116417     pWriter->nSize = nReq;
   116418   }
   116419   assert( nData+nReq<=pWriter->nSize );
   116420 
   116421   /* Append the prefix-compressed term and doclist to the buffer. */
   116422   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   116423   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
   116424   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   116425   nData += nSuffix;
   116426   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
   116427   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   116428   pWriter->nData = nData + nDoclist;
   116429 
   116430   /* Save the current term so that it can be used to prefix-compress the next.
   116431   ** If the isCopyTerm parameter is true, then the buffer pointed to by
   116432   ** zTerm is transient, so take a copy of the term data. Otherwise, just
   116433   ** store a copy of the pointer.
   116434   */
   116435   if( isCopyTerm ){
   116436     if( nTerm>pWriter->nMalloc ){
   116437       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
   116438       if( !zNew ){
   116439         return SQLITE_NOMEM;
   116440       }
   116441       pWriter->nMalloc = nTerm*2;
   116442       pWriter->zMalloc = zNew;
   116443       pWriter->zTerm = zNew;
   116444     }
   116445     assert( pWriter->zTerm==pWriter->zMalloc );
   116446     memcpy(pWriter->zTerm, zTerm, nTerm);
   116447   }else{
   116448     pWriter->zTerm = (char *)zTerm;
   116449   }
   116450   pWriter->nTerm = nTerm;
   116451 
   116452   return SQLITE_OK;
   116453 }
   116454 
   116455 /*
   116456 ** Flush all data associated with the SegmentWriter object pWriter to the
   116457 ** database. This function must be called after all terms have been added
   116458 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
   116459 ** returned. Otherwise, an SQLite error code.
   116460 */
   116461 static int fts3SegWriterFlush(
   116462   Fts3Table *p,                   /* Virtual table handle */
   116463   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
   116464   int iLevel,                     /* Value for 'level' column of %_segdir */
   116465   int iIdx                        /* Value for 'idx' column of %_segdir */
   116466 ){
   116467   int rc;                         /* Return code */
   116468   if( pWriter->pTree ){
   116469     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
   116470     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
   116471     char *zRoot = NULL;           /* Pointer to buffer containing root node */
   116472     int nRoot = 0;                /* Size of buffer zRoot */
   116473 
   116474     iLastLeaf = pWriter->iFree;
   116475     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
   116476     if( rc==SQLITE_OK ){
   116477       rc = fts3NodeWrite(p, pWriter->pTree, 1,
   116478           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
   116479     }
   116480     if( rc==SQLITE_OK ){
   116481       rc = fts3WriteSegdir(
   116482           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
   116483     }
   116484   }else{
   116485     /* The entire tree fits on the root node. Write it to the segdir table. */
   116486     rc = fts3WriteSegdir(
   116487         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
   116488   }
   116489   return rc;
   116490 }
   116491 
   116492 /*
   116493 ** Release all memory held by the SegmentWriter object passed as the
   116494 ** first argument.
   116495 */
   116496 static void fts3SegWriterFree(SegmentWriter *pWriter){
   116497   if( pWriter ){
   116498     sqlite3_free(pWriter->aData);
   116499     sqlite3_free(pWriter->zMalloc);
   116500     fts3NodeFree(pWriter->pTree);
   116501     sqlite3_free(pWriter);
   116502   }
   116503 }
   116504 
   116505 /*
   116506 ** The first value in the apVal[] array is assumed to contain an integer.
   116507 ** This function tests if there exist any documents with docid values that
   116508 ** are different from that integer. i.e. if deleting the document with docid
   116509 ** apVal[0] would mean the FTS3 table were empty.
   116510 **
   116511 ** If successful, *pisEmpty is set to true if the table is empty except for
   116512 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
   116513 ** error occurs, an SQLite error code is returned.
   116514 */
   116515 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
   116516   sqlite3_stmt *pStmt;
   116517   int rc;
   116518   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
   116519   if( rc==SQLITE_OK ){
   116520     if( SQLITE_ROW==sqlite3_step(pStmt) ){
   116521       *pisEmpty = sqlite3_column_int(pStmt, 0);
   116522     }
   116523     rc = sqlite3_reset(pStmt);
   116524   }
   116525   return rc;
   116526 }
   116527 
   116528 /*
   116529 ** Set *pnSegment to the number of segments of level iLevel in the database.
   116530 **
   116531 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   116532 */
   116533 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
   116534   sqlite3_stmt *pStmt;
   116535   int rc;
   116536 
   116537   assert( iLevel>=0 );
   116538   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
   116539   if( rc!=SQLITE_OK ) return rc;
   116540   sqlite3_bind_int(pStmt, 1, iLevel);
   116541   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   116542     *pnSegment = sqlite3_column_int(pStmt, 0);
   116543   }
   116544   return sqlite3_reset(pStmt);
   116545 }
   116546 
   116547 /*
   116548 ** Set *pnSegment to the total number of segments in the database. Set
   116549 ** *pnMax to the largest segment level in the database (segment levels
   116550 ** are stored in the 'level' column of the %_segdir table).
   116551 **
   116552 ** Return SQLITE_OK if successful, or an SQLite error code if not.
   116553 */
   116554 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
   116555   sqlite3_stmt *pStmt;
   116556   int rc;
   116557 
   116558   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
   116559   if( rc!=SQLITE_OK ) return rc;
   116560   if( SQLITE_ROW==sqlite3_step(pStmt) ){
   116561     *pnSegment = sqlite3_column_int(pStmt, 0);
   116562     *pnMax = sqlite3_column_int(pStmt, 1);
   116563   }
   116564   return sqlite3_reset(pStmt);
   116565 }
   116566 
   116567 /*
   116568 ** This function is used after merging multiple segments into a single large
   116569 ** segment to delete the old, now redundant, segment b-trees. Specifically,
   116570 ** it:
   116571 **
   116572 **   1) Deletes all %_segments entries for the segments associated with
   116573 **      each of the SegReader objects in the array passed as the third
   116574 **      argument, and
   116575 **
   116576 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
   116577 **      entries regardless of level if (iLevel<0).
   116578 **
   116579 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
   116580 */
   116581 static int fts3DeleteSegdir(
   116582   Fts3Table *p,                   /* Virtual table handle */
   116583   int iLevel,                     /* Level of %_segdir entries to delete */
   116584   Fts3SegReader **apSegment,      /* Array of SegReader objects */
   116585   int nReader                     /* Size of array apSegment */
   116586 ){
   116587   int rc;                         /* Return Code */
   116588   int i;                          /* Iterator variable */
   116589   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
   116590 
   116591   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
   116592   for(i=0; rc==SQLITE_OK && i<nReader; i++){
   116593     Fts3SegReader *pSegment = apSegment[i];
   116594     if( pSegment->iStartBlock ){
   116595       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
   116596       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
   116597       sqlite3_step(pDelete);
   116598       rc = sqlite3_reset(pDelete);
   116599     }
   116600   }
   116601   if( rc!=SQLITE_OK ){
   116602     return rc;
   116603   }
   116604 
   116605   if( iLevel>=0 ){
   116606     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
   116607     if( rc==SQLITE_OK ){
   116608       sqlite3_bind_int(pDelete, 1, iLevel);
   116609       sqlite3_step(pDelete);
   116610       rc = sqlite3_reset(pDelete);
   116611     }
   116612   }else{
   116613     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
   116614   }
   116615 
   116616   return rc;
   116617 }
   116618 
   116619 /*
   116620 ** When this function is called, buffer *ppList (size *pnList bytes) contains
   116621 ** a position list that may (or may not) feature multiple columns. This
   116622 ** function adjusts the pointer *ppList and the length *pnList so that they
   116623 ** identify the subset of the position list that corresponds to column iCol.
   116624 **
   116625 ** If there are no entries in the input position list for column iCol, then
   116626 ** *pnList is set to zero before returning.
   116627 */
   116628 static void fts3ColumnFilter(
   116629   int iCol,                       /* Column to filter on */
   116630   char **ppList,                  /* IN/OUT: Pointer to position list */
   116631   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
   116632 ){
   116633   char *pList = *ppList;
   116634   int nList = *pnList;
   116635   char *pEnd = &pList[nList];
   116636   int iCurrent = 0;
   116637   char *p = pList;
   116638 
   116639   assert( iCol>=0 );
   116640   while( 1 ){
   116641     char c = 0;
   116642     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
   116643 
   116644     if( iCol==iCurrent ){
   116645       nList = (int)(p - pList);
   116646       break;
   116647     }
   116648 
   116649     nList -= (int)(p - pList);
   116650     pList = p;
   116651     if( nList==0 ){
   116652       break;
   116653     }
   116654     p = &pList[1];
   116655     p += sqlite3Fts3GetVarint32(p, &iCurrent);
   116656   }
   116657 
   116658   *ppList = pList;
   116659   *pnList = nList;
   116660 }
   116661 
   116662 /*
   116663 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple
   116664 ** segments to create a single, larger segment.
   116665 */
   116666 static int fts3MergeCallback(
   116667   Fts3Table *p,                   /* FTS3 Virtual table handle */
   116668   void *pContext,                 /* Pointer to SegmentWriter* to write with */
   116669   char *zTerm,                    /* Term to write to the db */
   116670   int nTerm,                      /* Number of bytes in zTerm */
   116671   char *aDoclist,                 /* Doclist associated with zTerm */
   116672   int nDoclist                    /* Number of bytes in doclist */
   116673 ){
   116674   SegmentWriter **ppW = (SegmentWriter **)pContext;
   116675   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
   116676 }
   116677 
   116678 /*
   116679 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
   116680 ** of the pending-terms hash table to the database.
   116681 */
   116682 static int fts3FlushCallback(
   116683   Fts3Table *p,                   /* FTS3 Virtual table handle */
   116684   void *pContext,                 /* Pointer to SegmentWriter* to write with */
   116685   char *zTerm,                    /* Term to write to the db */
   116686   int nTerm,                      /* Number of bytes in zTerm */
   116687   char *aDoclist,                 /* Doclist associated with zTerm */
   116688   int nDoclist                    /* Number of bytes in doclist */
   116689 ){
   116690   SegmentWriter **ppW = (SegmentWriter **)pContext;
   116691   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
   116692 }
   116693 
   116694 /*
   116695 ** This function is used to iterate through a contiguous set of terms
   116696 ** stored in the full-text index. It merges data contained in one or
   116697 ** more segments to support this.
   116698 **
   116699 ** The second argument is passed an array of pointers to SegReader objects
   116700 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
   116701 ** of terms selected by each SegReader. If a single term is present in
   116702 ** more than one segment, the associated doclists are merged. For each
   116703 ** term and (possibly merged) doclist in the merged range, the callback
   116704 ** function xFunc is invoked with its arguments set as follows.
   116705 **
   116706 **   arg 0: Copy of 'p' parameter passed to this function
   116707 **   arg 1: Copy of 'pContext' parameter passed to this function
   116708 **   arg 2: Pointer to buffer containing term
   116709 **   arg 3: Size of arg 2 buffer in bytes
   116710 **   arg 4: Pointer to buffer containing doclist
   116711 **   arg 5: Size of arg 2 buffer in bytes
   116712 **
   116713 ** The 4th argument to this function is a pointer to a structure of type
   116714 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
   116715 ** further restrict the range of terms that callbacks are made for and
   116716 ** modify the behaviour of this function. See comments above structure
   116717 ** definition for details.
   116718 */
   116719 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
   116720   Fts3Table *p,                   /* Virtual table handle */
   116721   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
   116722   int nSegment,                   /* Size of apSegment array */
   116723   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
   116724   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
   116725   void *pContext                  /* Callback context (2nd argument) */
   116726 ){
   116727   int i;                          /* Iterator variable */
   116728   char *aBuffer = 0;              /* Buffer to merge doclists in */
   116729   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
   116730   int rc = SQLITE_OK;             /* Return code */
   116731 
   116732   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
   116733   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
   116734   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
   116735   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
   116736 
   116737   /* If there are zero segments, this function is a no-op. This scenario
   116738   ** comes about only when reading from an empty database.
   116739   */
   116740   if( nSegment==0 ) goto finished;
   116741 
   116742   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   116743   ** for, then advance each segment iterator until it points to a term of
   116744   ** equal or greater value than the specified term. This prevents many
   116745   ** unnecessary merge/sort operations for the case where single segment
   116746   ** b-tree leaf nodes contain more than one term.
   116747   */
   116748   for(i=0; i<nSegment; i++){
   116749     int nTerm = pFilter->nTerm;
   116750     const char *zTerm = pFilter->zTerm;
   116751     Fts3SegReader *pSeg = apSegment[i];
   116752     do {
   116753       rc = fts3SegReaderNext(p, pSeg);
   116754       if( rc!=SQLITE_OK ) goto finished;
   116755     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
   116756   }
   116757 
   116758   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
   116759   while( apSegment[0]->aNode ){
   116760     int nTerm = apSegment[0]->nTerm;
   116761     char *zTerm = apSegment[0]->zTerm;
   116762     int nMerge = 1;
   116763 
   116764     /* If this is a prefix-search, and if the term that apSegment[0] points
   116765     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
   116766     ** required callbacks have been made. In this case exit early.
   116767     **
   116768     ** Similarly, if this is a search for an exact match, and the first term
   116769     ** of segment apSegment[0] is not a match, exit early.
   116770     */
   116771     if( pFilter->zTerm ){
   116772       if( nTerm<pFilter->nTerm
   116773        || (!isPrefix && nTerm>pFilter->nTerm)
   116774        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
   116775     ){
   116776         goto finished;
   116777       }
   116778     }
   116779 
   116780     while( nMerge<nSegment
   116781         && apSegment[nMerge]->aNode
   116782         && apSegment[nMerge]->nTerm==nTerm
   116783         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
   116784     ){
   116785       nMerge++;
   116786     }
   116787 
   116788     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
   116789     if( nMerge==1 && !isIgnoreEmpty ){
   116790       Fts3SegReader *p0 = apSegment[0];
   116791       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
   116792       if( rc!=SQLITE_OK ) goto finished;
   116793     }else{
   116794       int nDoclist = 0;           /* Size of doclist */
   116795       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
   116796 
   116797       /* The current term of the first nMerge entries in the array
   116798       ** of Fts3SegReader objects is the same. The doclists must be merged
   116799       ** and a single term added to the new segment.
   116800       */
   116801       for(i=0; i<nMerge; i++){
   116802         fts3SegReaderFirstDocid(apSegment[i]);
   116803       }
   116804       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
   116805       while( apSegment[0]->pOffsetList ){
   116806         int j;                    /* Number of segments that share a docid */
   116807         char *pList;
   116808         int nList;
   116809         int nByte;
   116810         sqlite3_int64 iDocid = apSegment[0]->iDocid;
   116811         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
   116812         j = 1;
   116813         while( j<nMerge
   116814             && apSegment[j]->pOffsetList
   116815             && apSegment[j]->iDocid==iDocid
   116816         ){
   116817           fts3SegReaderNextDocid(apSegment[j], 0, 0);
   116818           j++;
   116819         }
   116820 
   116821         if( isColFilter ){
   116822           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
   116823         }
   116824 
   116825         if( !isIgnoreEmpty || nList>0 ){
   116826           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
   116827           if( nDoclist+nByte>nAlloc ){
   116828             char *aNew;
   116829             nAlloc = nDoclist+nByte*2;
   116830             aNew = sqlite3_realloc(aBuffer, nAlloc);
   116831             if( !aNew ){
   116832               rc = SQLITE_NOMEM;
   116833               goto finished;
   116834             }
   116835             aBuffer = aNew;
   116836           }
   116837           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
   116838           iPrev = iDocid;
   116839           if( isRequirePos ){
   116840             memcpy(&aBuffer[nDoclist], pList, nList);
   116841             nDoclist += nList;
   116842             aBuffer[nDoclist++] = '\0';
   116843           }
   116844         }
   116845 
   116846         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
   116847       }
   116848 
   116849       if( nDoclist>0 ){
   116850         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
   116851         if( rc!=SQLITE_OK ) goto finished;
   116852       }
   116853     }
   116854 
   116855     /* If there is a term specified to filter on, and this is not a prefix
   116856     ** search, return now. The callback that corresponds to the required
   116857     ** term (if such a term exists in the index) has already been made.
   116858     */
   116859     if( pFilter->zTerm && !isPrefix ){
   116860       goto finished;
   116861     }
   116862 
   116863     for(i=0; i<nMerge; i++){
   116864       rc = fts3SegReaderNext(p, apSegment[i]);
   116865       if( rc!=SQLITE_OK ) goto finished;
   116866     }
   116867     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
   116868   }
   116869 
   116870  finished:
   116871   sqlite3_free(aBuffer);
   116872   return rc;
   116873 }
   116874 
   116875 /*
   116876 ** Merge all level iLevel segments in the database into a single
   116877 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
   116878 ** single segment with a level equal to the numerically largest level
   116879 ** currently present in the database.
   116880 **
   116881 ** If this function is called with iLevel<0, but there is only one
   116882 ** segment in the database, SQLITE_DONE is returned immediately.
   116883 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
   116884 ** an SQLite error code is returned.
   116885 */
   116886 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
   116887   int i;                          /* Iterator variable */
   116888   int rc;                         /* Return code */
   116889   int iIdx;                       /* Index of new segment */
   116890   int iNewLevel = 0;              /* Level to create new segment at */
   116891   sqlite3_stmt *pStmt = 0;
   116892   SegmentWriter *pWriter = 0;
   116893   int nSegment = 0;               /* Number of segments being merged */
   116894   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
   116895   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
   116896   Fts3SegFilter filter;           /* Segment term filter condition */
   116897 
   116898   if( iLevel<0 ){
   116899     /* This call is to merge all segments in the database to a single
   116900     ** segment. The level of the new segment is equal to the the numerically
   116901     ** greatest segment level currently present in the database. The index
   116902     ** of the new segment is always 0.
   116903     */
   116904     iIdx = 0;
   116905     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
   116906     if( rc!=SQLITE_OK ) goto finished;
   116907     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
   116908     if( rc!=SQLITE_OK ) goto finished;
   116909     nSegment += (pPending!=0);
   116910     if( nSegment<=1 ){
   116911       return SQLITE_DONE;
   116912     }
   116913   }else{
   116914     /* This call is to merge all segments at level iLevel. Find the next
   116915     ** available segment index at level iLevel+1. The call to
   116916     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
   116917     ** a single iLevel+2 segment if necessary.
   116918     */
   116919     iNewLevel = iLevel+1;
   116920     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
   116921     if( rc!=SQLITE_OK ) goto finished;
   116922     rc = fts3SegmentCount(p, iLevel, &nSegment);
   116923     if( rc!=SQLITE_OK ) goto finished;
   116924   }
   116925   assert( nSegment>0 );
   116926   assert( iNewLevel>=0 );
   116927 
   116928   /* Allocate space for an array of pointers to segment iterators. */
   116929   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
   116930   if( !apSegment ){
   116931     rc = SQLITE_NOMEM;
   116932     goto finished;
   116933   }
   116934   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
   116935 
   116936   /* Allocate a Fts3SegReader structure for each segment being merged. A
   116937   ** Fts3SegReader stores the state data required to iterate through all
   116938   ** entries on all leaves of a single segment.
   116939   */
   116940   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
   116941   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
   116942   if( rc!=SQLITE_OK ) goto finished;
   116943   sqlite3_bind_int(pStmt, 1, iLevel);
   116944   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
   116945     rc = fts3SegReaderNew(pStmt, i, &apSegment[i]);
   116946     if( rc!=SQLITE_OK ){
   116947       goto finished;
   116948     }
   116949   }
   116950   rc = sqlite3_reset(pStmt);
   116951   if( pPending ){
   116952     apSegment[i] = pPending;
   116953     pPending = 0;
   116954   }
   116955   pStmt = 0;
   116956   if( rc!=SQLITE_OK ) goto finished;
   116957 
   116958   memset(&filter, 0, sizeof(Fts3SegFilter));
   116959   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
   116960   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
   116961   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
   116962       &filter, fts3MergeCallback, (void *)&pWriter
   116963   );
   116964   if( rc!=SQLITE_OK ) goto finished;
   116965 
   116966   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
   116967   if( rc==SQLITE_OK ){
   116968     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
   116969   }
   116970 
   116971  finished:
   116972   fts3SegWriterFree(pWriter);
   116973   if( apSegment ){
   116974     for(i=0; i<nSegment; i++){
   116975       sqlite3Fts3SegReaderFree(apSegment[i]);
   116976     }
   116977     sqlite3_free(apSegment);
   116978   }
   116979   sqlite3Fts3SegReaderFree(pPending);
   116980   sqlite3_reset(pStmt);
   116981   return rc;
   116982 }
   116983 
   116984 
   116985 /*
   116986 ** Flush the contents of pendingTerms to a level 0 segment.
   116987 */
   116988 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   116989   int rc;                         /* Return Code */
   116990   int idx;                        /* Index of new segment created */
   116991   SegmentWriter *pWriter = 0;     /* Used to write the segment */
   116992   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
   116993 
   116994   /* Allocate a SegReader object to iterate through the contents of the
   116995   ** pending-terms table. If an error occurs, or if there are no terms
   116996   ** in the pending-terms table, return immediately.
   116997   */
   116998   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
   116999   if( rc!=SQLITE_OK || pReader==0 ){
   117000     return rc;
   117001   }
   117002 
   117003   /* Determine the next index at level 0. If level 0 is already full, this
   117004   ** call may merge all existing level 0 segments into a single level 1
   117005   ** segment.
   117006   */
   117007   rc = fts3AllocateSegdirIdx(p, 0, &idx);
   117008 
   117009   /* If no errors have occured, iterate through the contents of the
   117010   ** pending-terms hash table using the Fts3SegReader iterator. The callback
   117011   ** writes each term (along with its doclist) to the database via the
   117012   ** SegmentWriter handle pWriter.
   117013   */
   117014   if( rc==SQLITE_OK ){
   117015     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
   117016     Fts3SegFilter f;              /* SegReaderIterate() parameters */
   117017 
   117018     memset(&f, 0, sizeof(Fts3SegFilter));
   117019     f.flags = FTS3_SEGMENT_REQUIRE_POS;
   117020     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
   117021   }
   117022   assert( pWriter || rc!=SQLITE_OK );
   117023 
   117024   /* If no errors have occured, flush the SegmentWriter object to the
   117025   ** database. Then delete the SegmentWriter and Fts3SegReader objects
   117026   ** allocated by this function.
   117027   */
   117028   if( rc==SQLITE_OK ){
   117029     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
   117030   }
   117031   fts3SegWriterFree(pWriter);
   117032   sqlite3Fts3SegReaderFree(pReader);
   117033 
   117034   if( rc==SQLITE_OK ){
   117035     sqlite3Fts3PendingTermsClear(p);
   117036   }
   117037   return rc;
   117038 }
   117039 
   117040 /*
   117041 ** Encode N integers as varints into a blob.
   117042 */
   117043 static void fts3EncodeIntArray(
   117044   int N,             /* The number of integers to encode */
   117045   u32 *a,            /* The integer values */
   117046   char *zBuf,        /* Write the BLOB here */
   117047   int *pNBuf         /* Write number of bytes if zBuf[] used here */
   117048 ){
   117049   int i, j;
   117050   for(i=j=0; i<N; i++){
   117051     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
   117052   }
   117053   *pNBuf = j;
   117054 }
   117055 
   117056 /*
   117057 ** Decode a blob of varints into N integers
   117058 */
   117059 static void fts3DecodeIntArray(
   117060   int N,             /* The number of integers to decode */
   117061   u32 *a,            /* Write the integer values */
   117062   const char *zBuf,  /* The BLOB containing the varints */
   117063   int nBuf           /* size of the BLOB */
   117064 ){
   117065   int i, j;
   117066   UNUSED_PARAMETER(nBuf);
   117067   for(i=j=0; i<N; i++){
   117068     sqlite3_int64 x;
   117069     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
   117070     assert(j<=nBuf);
   117071     a[i] = (u32)(x & 0xffffffff);
   117072   }
   117073 }
   117074 
   117075 /*
   117076 ** Insert the sizes (in tokens) for each column of the document
   117077 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
   117078 ** a blob of varints.
   117079 */
   117080 static void fts3InsertDocsize(
   117081   int *pRC,         /* Result code */
   117082   Fts3Table *p,     /* Table into which to insert */
   117083   u32 *aSz          /* Sizes of each column */
   117084 ){
   117085   char *pBlob;             /* The BLOB encoding of the document size */
   117086   int nBlob;               /* Number of bytes in the BLOB */
   117087   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
   117088   int rc;                  /* Result code from subfunctions */
   117089 
   117090   if( *pRC ) return;
   117091   pBlob = sqlite3_malloc( 10*p->nColumn );
   117092   if( pBlob==0 ){
   117093     *pRC = SQLITE_NOMEM;
   117094     return;
   117095   }
   117096   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
   117097   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
   117098   if( rc ){
   117099     sqlite3_free(pBlob);
   117100     *pRC = rc;
   117101     return;
   117102   }
   117103   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
   117104   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
   117105   sqlite3_step(pStmt);
   117106   *pRC = sqlite3_reset(pStmt);
   117107 }
   117108 
   117109 /*
   117110 ** Record 0 of the %_stat table contains a blob consisting of N varints,
   117111 ** where N is the number of user defined columns in the fts3 table plus
   117112 ** two. If nCol is the number of user defined columns, then values of the
   117113 ** varints are set as follows:
   117114 **
   117115 **   Varint 0:       Total number of rows in the table.
   117116 **
   117117 **   Varint 1..nCol: For each column, the total number of tokens stored in
   117118 **                   the column for all rows of the table.
   117119 **
   117120 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
   117121 **                   columns of all rows of the table.
   117122 **
   117123 */
   117124 static void fts3UpdateDocTotals(
   117125   int *pRC,                       /* The result code */
   117126   Fts3Table *p,                   /* Table being updated */
   117127   u32 *aSzIns,                    /* Size increases */
   117128   u32 *aSzDel,                    /* Size decreases */
   117129   int nChng                       /* Change in the number of documents */
   117130 ){
   117131   char *pBlob;             /* Storage for BLOB written into %_stat */
   117132   int nBlob;               /* Size of BLOB written into %_stat */
   117133   u32 *a;                  /* Array of integers that becomes the BLOB */
   117134   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
   117135   int i;                   /* Loop counter */
   117136   int rc;                  /* Result code from subfunctions */
   117137 
   117138   const int nStat = p->nColumn+2;
   117139 
   117140   if( *pRC ) return;
   117141   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
   117142   if( a==0 ){
   117143     *pRC = SQLITE_NOMEM;
   117144     return;
   117145   }
   117146   pBlob = (char*)&a[nStat];
   117147   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
   117148   if( rc ){
   117149     sqlite3_free(a);
   117150     *pRC = rc;
   117151     return;
   117152   }
   117153   if( sqlite3_step(pStmt)==SQLITE_ROW ){
   117154     fts3DecodeIntArray(nStat, a,
   117155          sqlite3_column_blob(pStmt, 0),
   117156          sqlite3_column_bytes(pStmt, 0));
   117157   }else{
   117158     memset(a, 0, sizeof(u32)*(nStat) );
   117159   }
   117160   sqlite3_reset(pStmt);
   117161   if( nChng<0 && a[0]<(u32)(-nChng) ){
   117162     a[0] = 0;
   117163   }else{
   117164     a[0] += nChng;
   117165   }
   117166   for(i=0; i<p->nColumn+1; i++){
   117167     u32 x = a[i+1];
   117168     if( x+aSzIns[i] < aSzDel[i] ){
   117169       x = 0;
   117170     }else{
   117171       x = x + aSzIns[i] - aSzDel[i];
   117172     }
   117173     a[i+1] = x;
   117174   }
   117175   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
   117176   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
   117177   if( rc ){
   117178     sqlite3_free(a);
   117179     *pRC = rc;
   117180     return;
   117181   }
   117182   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
   117183   sqlite3_step(pStmt);
   117184   *pRC = sqlite3_reset(pStmt);
   117185   sqlite3_free(a);
   117186 }
   117187 
   117188 /*
   117189 ** Handle a 'special' INSERT of the form:
   117190 **
   117191 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
   117192 **
   117193 ** Argument pVal contains the result of <expr>. Currently the only
   117194 ** meaningful value to insert is the text 'optimize'.
   117195 */
   117196 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
   117197   int rc;                         /* Return Code */
   117198   const char *zVal = (const char *)sqlite3_value_text(pVal);
   117199   int nVal = sqlite3_value_bytes(pVal);
   117200 
   117201   if( !zVal ){
   117202     return SQLITE_NOMEM;
   117203   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
   117204     rc = fts3SegmentMerge(p, -1);
   117205     if( rc==SQLITE_DONE ){
   117206       rc = SQLITE_OK;
   117207     }else{
   117208       sqlite3Fts3PendingTermsClear(p);
   117209     }
   117210 #ifdef SQLITE_TEST
   117211   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
   117212     p->nNodeSize = atoi(&zVal[9]);
   117213     rc = SQLITE_OK;
   117214   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
   117215     p->nMaxPendingData = atoi(&zVal[11]);
   117216     rc = SQLITE_OK;
   117217 #endif
   117218   }else{
   117219     rc = SQLITE_ERROR;
   117220   }
   117221 
   117222   sqlite3Fts3SegmentsClose(p);
   117223   return rc;
   117224 }
   117225 
   117226 /*
   117227 ** Return the deferred doclist associated with deferred token pDeferred.
   117228 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
   117229 ** been called to allocate and populate the doclist.
   117230 */
   117231 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
   117232   if( pDeferred->pList ){
   117233     *pnByte = pDeferred->pList->nData;
   117234     return pDeferred->pList->aData;
   117235   }
   117236   *pnByte = 0;
   117237   return 0;
   117238 }
   117239 
   117240 /*
   117241 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
   117242 ** references to deferred doclists from within the tree of Fts3Expr
   117243 ** structures headed by
   117244 */
   117245 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
   117246   if( pExpr ){
   117247     fts3DeferredDoclistClear(pExpr->pLeft);
   117248     fts3DeferredDoclistClear(pExpr->pRight);
   117249     if( pExpr->isLoaded ){
   117250       sqlite3_free(pExpr->aDoclist);
   117251       pExpr->isLoaded = 0;
   117252       pExpr->aDoclist = 0;
   117253       pExpr->nDoclist = 0;
   117254       pExpr->pCurrent = 0;
   117255       pExpr->iCurrent = 0;
   117256     }
   117257   }
   117258 }
   117259 
   117260 /*
   117261 ** Delete all cached deferred doclists. Deferred doclists are cached
   117262 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
   117263 */
   117264 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
   117265   Fts3DeferredToken *pDef;
   117266   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
   117267     sqlite3_free(pDef->pList);
   117268     pDef->pList = 0;
   117269   }
   117270   if( pCsr->pDeferred ){
   117271     fts3DeferredDoclistClear(pCsr->pExpr);
   117272   }
   117273 }
   117274 
   117275 /*
   117276 ** Free all entries in the pCsr->pDeffered list. Entries are added to
   117277 ** this list using sqlite3Fts3DeferToken().
   117278 */
   117279 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
   117280   Fts3DeferredToken *pDef;
   117281   Fts3DeferredToken *pNext;
   117282   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
   117283     pNext = pDef->pNext;
   117284     sqlite3_free(pDef->pList);
   117285     sqlite3_free(pDef);
   117286   }
   117287   pCsr->pDeferred = 0;
   117288 }
   117289 
   117290 /*
   117291 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
   117292 ** based on the row that pCsr currently points to.
   117293 **
   117294 ** A deferred-doclist is like any other doclist with position information
   117295 ** included, except that it only contains entries for a single row of the
   117296 ** table, not for all rows.
   117297 */
   117298 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
   117299   int rc = SQLITE_OK;             /* Return code */
   117300   if( pCsr->pDeferred ){
   117301     int i;                        /* Used to iterate through table columns */
   117302     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
   117303     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
   117304 
   117305     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
   117306     sqlite3_tokenizer *pT = p->pTokenizer;
   117307     sqlite3_tokenizer_module const *pModule = pT->pModule;
   117308 
   117309     assert( pCsr->isRequireSeek==0 );
   117310     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
   117311 
   117312     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
   117313       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
   117314       sqlite3_tokenizer_cursor *pTC = 0;
   117315 
   117316       rc = pModule->xOpen(pT, zText, -1, &pTC);
   117317       while( rc==SQLITE_OK ){
   117318         char const *zToken;       /* Buffer containing token */
   117319         int nToken;               /* Number of bytes in token */
   117320         int iDum1, iDum2;         /* Dummy variables */
   117321         int iPos;                 /* Position of token in zText */
   117322 
   117323         pTC->pTokenizer = pT;
   117324         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
   117325         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   117326           Fts3PhraseToken *pPT = pDef->pToken;
   117327           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
   117328            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
   117329            && (0==memcmp(zToken, pPT->z, pPT->n))
   117330           ){
   117331             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
   117332           }
   117333         }
   117334       }
   117335       if( pTC ) pModule->xClose(pTC);
   117336       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   117337     }
   117338 
   117339     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
   117340       if( pDef->pList ){
   117341         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
   117342       }
   117343     }
   117344   }
   117345 
   117346   return rc;
   117347 }
   117348 
   117349 /*
   117350 ** Add an entry for token pToken to the pCsr->pDeferred list.
   117351 */
   117352 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   117353   Fts3Cursor *pCsr,               /* Fts3 table cursor */
   117354   Fts3PhraseToken *pToken,        /* Token to defer */
   117355   int iCol                        /* Column that token must appear in (or -1) */
   117356 ){
   117357   Fts3DeferredToken *pDeferred;
   117358   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
   117359   if( !pDeferred ){
   117360     return SQLITE_NOMEM;
   117361   }
   117362   memset(pDeferred, 0, sizeof(*pDeferred));
   117363   pDeferred->pToken = pToken;
   117364   pDeferred->pNext = pCsr->pDeferred;
   117365   pDeferred->iCol = iCol;
   117366   pCsr->pDeferred = pDeferred;
   117367 
   117368   assert( pToken->pDeferred==0 );
   117369   pToken->pDeferred = pDeferred;
   117370 
   117371   return SQLITE_OK;
   117372 }
   117373 
   117374 
   117375 /*
   117376 ** This function does the work for the xUpdate method of FTS3 virtual
   117377 ** tables.
   117378 */
   117379 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   117380   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
   117381   int nArg,                       /* Size of argument array */
   117382   sqlite3_value **apVal,          /* Array of arguments */
   117383   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
   117384 ){
   117385   Fts3Table *p = (Fts3Table *)pVtab;
   117386   int rc = SQLITE_OK;             /* Return Code */
   117387   int isRemove = 0;               /* True for an UPDATE or DELETE */
   117388   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
   117389   u32 *aSzIns;                    /* Sizes of inserted documents */
   117390   u32 *aSzDel;                    /* Sizes of deleted documents */
   117391   int nChng = 0;                  /* Net change in number of documents */
   117392 
   117393   assert( p->pSegments==0 );
   117394 
   117395   /* Allocate space to hold the change in document sizes */
   117396   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
   117397   if( aSzIns==0 ) return SQLITE_NOMEM;
   117398   aSzDel = &aSzIns[p->nColumn+1];
   117399   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
   117400 
   117401   /* If this is a DELETE or UPDATE operation, remove the old record. */
   117402   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
   117403     int isEmpty = 0;
   117404     rc = fts3IsEmpty(p, apVal, &isEmpty);
   117405     if( rc==SQLITE_OK ){
   117406       if( isEmpty ){
   117407         /* Deleting this row means the whole table is empty. In this case
   117408         ** delete the contents of all three tables and throw away any
   117409         ** data in the pendingTerms hash table.
   117410         */
   117411         rc = fts3DeleteAll(p);
   117412       }else{
   117413         isRemove = 1;
   117414         iRemove = sqlite3_value_int64(apVal[0]);
   117415         rc = fts3PendingTermsDocid(p, iRemove);
   117416         fts3DeleteTerms(&rc, p, apVal, aSzDel);
   117417         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
   117418         if( p->bHasDocsize ){
   117419           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
   117420         }
   117421         nChng--;
   117422       }
   117423     }
   117424   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
   117425     sqlite3_free(aSzIns);
   117426     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
   117427   }
   117428 
   117429   /* If this is an INSERT or UPDATE operation, insert the new record. */
   117430   if( nArg>1 && rc==SQLITE_OK ){
   117431     rc = fts3InsertData(p, apVal, pRowid);
   117432     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
   117433       rc = fts3PendingTermsDocid(p, *pRowid);
   117434     }
   117435     if( rc==SQLITE_OK ){
   117436       rc = fts3InsertTerms(p, apVal, aSzIns);
   117437     }
   117438     if( p->bHasDocsize ){
   117439       fts3InsertDocsize(&rc, p, aSzIns);
   117440     }
   117441     nChng++;
   117442   }
   117443 
   117444   if( p->bHasStat ){
   117445     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
   117446   }
   117447 
   117448   sqlite3_free(aSzIns);
   117449   sqlite3Fts3SegmentsClose(p);
   117450   return rc;
   117451 }
   117452 
   117453 /*
   117454 ** Flush any data in the pending-terms hash table to disk. If successful,
   117455 ** merge all segments in the database (including the new segment, if
   117456 ** there was any data to flush) into a single segment.
   117457 */
   117458 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   117459   int rc;
   117460   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
   117461   if( rc==SQLITE_OK ){
   117462     rc = fts3SegmentMerge(p, -1);
   117463     if( rc==SQLITE_OK ){
   117464       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   117465       if( rc==SQLITE_OK ){
   117466         sqlite3Fts3PendingTermsClear(p);
   117467       }
   117468     }else{
   117469       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
   117470       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
   117471     }
   117472   }
   117473   sqlite3Fts3SegmentsClose(p);
   117474   return rc;
   117475 }
   117476 
   117477 #endif
   117478 
   117479 /************** End of fts3_write.c ******************************************/
   117480 /************** Begin file fts3_snippet.c ************************************/
   117481 /*
   117482 ** 2009 Oct 23
   117483 **
   117484 ** The author disclaims copyright to this source code.  In place of
   117485 ** a legal notice, here is a blessing:
   117486 **
   117487 **    May you do good and not evil.
   117488 **    May you find forgiveness for yourself and forgive others.
   117489 **    May you share freely, never taking more than you give.
   117490 **
   117491 ******************************************************************************
   117492 */
   117493 
   117494 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   117495 
   117496 
   117497 /*
   117498 ** Characters that may appear in the second argument to matchinfo().
   117499 */
   117500 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
   117501 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
   117502 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
   117503 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
   117504 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
   117505 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
   117506 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
   117507 
   117508 /*
   117509 ** The default value for the second argument to matchinfo().
   117510 */
   117511 #define FTS3_MATCHINFO_DEFAULT   "pcx"
   117512 
   117513 
   117514 /*
   117515 ** Used as an fts3ExprIterate() context when loading phrase doclists to
   117516 ** Fts3Expr.aDoclist[]/nDoclist.
   117517 */
   117518 typedef struct LoadDoclistCtx LoadDoclistCtx;
   117519 struct LoadDoclistCtx {
   117520   Fts3Cursor *pCsr;               /* FTS3 Cursor */
   117521   int nPhrase;                    /* Number of phrases seen so far */
   117522   int nToken;                     /* Number of tokens seen so far */
   117523 };
   117524 
   117525 /*
   117526 ** The following types are used as part of the implementation of the
   117527 ** fts3BestSnippet() routine.
   117528 */
   117529 typedef struct SnippetIter SnippetIter;
   117530 typedef struct SnippetPhrase SnippetPhrase;
   117531 typedef struct SnippetFragment SnippetFragment;
   117532 
   117533 struct SnippetIter {
   117534   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
   117535   int iCol;                       /* Extract snippet from this column */
   117536   int nSnippet;                   /* Requested snippet length (in tokens) */
   117537   int nPhrase;                    /* Number of phrases in query */
   117538   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
   117539   int iCurrent;                   /* First token of current snippet */
   117540 };
   117541 
   117542 struct SnippetPhrase {
   117543   int nToken;                     /* Number of tokens in phrase */
   117544   char *pList;                    /* Pointer to start of phrase position list */
   117545   int iHead;                      /* Next value in position list */
   117546   char *pHead;                    /* Position list data following iHead */
   117547   int iTail;                      /* Next value in trailing position list */
   117548   char *pTail;                    /* Position list data following iTail */
   117549 };
   117550 
   117551 struct SnippetFragment {
   117552   int iCol;                       /* Column snippet is extracted from */
   117553   int iPos;                       /* Index of first token in snippet */
   117554   u64 covered;                    /* Mask of query phrases covered */
   117555   u64 hlmask;                     /* Mask of snippet terms to highlight */
   117556 };
   117557 
   117558 /*
   117559 ** This type is used as an fts3ExprIterate() context object while
   117560 ** accumulating the data returned by the matchinfo() function.
   117561 */
   117562 typedef struct MatchInfo MatchInfo;
   117563 struct MatchInfo {
   117564   Fts3Cursor *pCursor;            /* FTS3 Cursor */
   117565   int nCol;                       /* Number of columns in table */
   117566   int nPhrase;                    /* Number of matchable phrases in query */
   117567   sqlite3_int64 nDoc;             /* Number of docs in database */
   117568   u32 *aMatchinfo;                /* Pre-allocated buffer */
   117569 };
   117570 
   117571 
   117572 
   117573 /*
   117574 ** The snippet() and offsets() functions both return text values. An instance
   117575 ** of the following structure is used to accumulate those values while the
   117576 ** functions are running. See fts3StringAppend() for details.
   117577 */
   117578 typedef struct StrBuffer StrBuffer;
   117579 struct StrBuffer {
   117580   char *z;                        /* Pointer to buffer containing string */
   117581   int n;                          /* Length of z in bytes (excl. nul-term) */
   117582   int nAlloc;                     /* Allocated size of buffer z in bytes */
   117583 };
   117584 
   117585 
   117586 /*
   117587 ** This function is used to help iterate through a position-list. A position
   117588 ** list is a list of unique integers, sorted from smallest to largest. Each
   117589 ** element of the list is represented by an FTS3 varint that takes the value
   117590 ** of the difference between the current element and the previous one plus
   117591 ** two. For example, to store the position-list:
   117592 **
   117593 **     4 9 113
   117594 **
   117595 ** the three varints:
   117596 **
   117597 **     6 7 106
   117598 **
   117599 ** are encoded.
   117600 **
   117601 ** When this function is called, *pp points to the start of an element of
   117602 ** the list. *piPos contains the value of the previous entry in the list.
   117603 ** After it returns, *piPos contains the value of the next element of the
   117604 ** list and *pp is advanced to the following varint.
   117605 */
   117606 static void fts3GetDeltaPosition(char **pp, int *piPos){
   117607   int iVal;
   117608   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
   117609   *piPos += (iVal-2);
   117610 }
   117611 
   117612 /*
   117613 ** Helper function for fts3ExprIterate() (see below).
   117614 */
   117615 static int fts3ExprIterate2(
   117616   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   117617   int *piPhrase,                  /* Pointer to phrase counter */
   117618   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   117619   void *pCtx                      /* Second argument to pass to callback */
   117620 ){
   117621   int rc;                         /* Return code */
   117622   int eType = pExpr->eType;       /* Type of expression node pExpr */
   117623 
   117624   if( eType!=FTSQUERY_PHRASE ){
   117625     assert( pExpr->pLeft && pExpr->pRight );
   117626     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
   117627     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
   117628       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
   117629     }
   117630   }else{
   117631     rc = x(pExpr, *piPhrase, pCtx);
   117632     (*piPhrase)++;
   117633   }
   117634   return rc;
   117635 }
   117636 
   117637 /*
   117638 ** Iterate through all phrase nodes in an FTS3 query, except those that
   117639 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
   117640 ** For each phrase node found, the supplied callback function is invoked.
   117641 **
   117642 ** If the callback function returns anything other than SQLITE_OK,
   117643 ** the iteration is abandoned and the error code returned immediately.
   117644 ** Otherwise, SQLITE_OK is returned after a callback has been made for
   117645 ** all eligible phrase nodes.
   117646 */
   117647 static int fts3ExprIterate(
   117648   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
   117649   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
   117650   void *pCtx                      /* Second argument to pass to callback */
   117651 ){
   117652   int iPhrase = 0;                /* Variable used as the phrase counter */
   117653   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
   117654 }
   117655 
   117656 /*
   117657 ** The argument to this function is always a phrase node. Its doclist
   117658 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
   117659 ** to the left of this one in the query tree have already been loaded.
   117660 **
   117661 ** If this phrase node is part of a series of phrase nodes joined by
   117662 ** NEAR operators (and is not the left-most of said series), then elements are
   117663 ** removed from the phrases doclist consistent with the NEAR restriction. If
   117664 ** required, elements may be removed from the doclists of phrases to the
   117665 ** left of this one that are part of the same series of NEAR operator
   117666 ** connected phrases.
   117667 **
   117668 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
   117669 */
   117670 static int fts3ExprNearTrim(Fts3Expr *pExpr){
   117671   int rc = SQLITE_OK;
   117672   Fts3Expr *pParent = pExpr->pParent;
   117673 
   117674   assert( pExpr->eType==FTSQUERY_PHRASE );
   117675   while( rc==SQLITE_OK
   117676    && pParent
   117677    && pParent->eType==FTSQUERY_NEAR
   117678    && pParent->pRight==pExpr
   117679   ){
   117680     /* This expression (pExpr) is the right-hand-side of a NEAR operator.
   117681     ** Find the expression to the left of the same operator.
   117682     */
   117683     int nNear = pParent->nNear;
   117684     Fts3Expr *pLeft = pParent->pLeft;
   117685 
   117686     if( pLeft->eType!=FTSQUERY_PHRASE ){
   117687       assert( pLeft->eType==FTSQUERY_NEAR );
   117688       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
   117689       pLeft = pLeft->pRight;
   117690     }
   117691 
   117692     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
   117693 
   117694     pExpr = pLeft;
   117695     pParent = pExpr->pParent;
   117696   }
   117697 
   117698   return rc;
   117699 }
   117700 
   117701 /*
   117702 ** This is an fts3ExprIterate() callback used while loading the doclists
   117703 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   117704 ** fts3ExprLoadDoclists().
   117705 */
   117706 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
   117707   int rc = SQLITE_OK;
   117708   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
   117709 
   117710   UNUSED_PARAMETER(iPhrase);
   117711 
   117712   p->nPhrase++;
   117713   p->nToken += pExpr->pPhrase->nToken;
   117714 
   117715   if( pExpr->isLoaded==0 ){
   117716     rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
   117717     pExpr->isLoaded = 1;
   117718     if( rc==SQLITE_OK ){
   117719       rc = fts3ExprNearTrim(pExpr);
   117720     }
   117721   }
   117722 
   117723   return rc;
   117724 }
   117725 
   117726 /*
   117727 ** This is an fts3ExprIterate() callback used while loading the doclists
   117728 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
   117729 ** fts3ExprLoadDoclists().
   117730 */
   117731 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
   117732   UNUSED_PARAMETER(iPhrase);
   117733   UNUSED_PARAMETER(ctx);
   117734   if( pExpr->aDoclist ){
   117735     pExpr->pCurrent = pExpr->aDoclist;
   117736     pExpr->iCurrent = 0;
   117737     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
   117738   }
   117739   return SQLITE_OK;
   117740 }
   117741 
   117742 /*
   117743 ** Load the doclists for each phrase in the query associated with FTS3 cursor
   117744 ** pCsr.
   117745 **
   117746 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
   117747 ** phrases in the expression (all phrases except those directly or
   117748 ** indirectly descended from the right-hand-side of a NOT operator). If
   117749 ** pnToken is not NULL, then it is set to the number of tokens in all
   117750 ** matchable phrases of the expression.
   117751 */
   117752 static int fts3ExprLoadDoclists(
   117753   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
   117754   int *pnPhrase,                  /* OUT: Number of phrases in query */
   117755   int *pnToken                    /* OUT: Number of tokens in query */
   117756 ){
   117757   int rc;                         /* Return Code */
   117758   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
   117759   sCtx.pCsr = pCsr;
   117760   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
   117761   if( rc==SQLITE_OK ){
   117762     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
   117763   }
   117764   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
   117765   if( pnToken ) *pnToken = sCtx.nToken;
   117766   return rc;
   117767 }
   117768 
   117769 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
   117770   (*(int *)ctx)++;
   117771   UNUSED_PARAMETER(pExpr);
   117772   UNUSED_PARAMETER(iPhrase);
   117773   return SQLITE_OK;
   117774 }
   117775 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
   117776   int nPhrase = 0;
   117777   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
   117778   return nPhrase;
   117779 }
   117780 
   117781 /*
   117782 ** Advance the position list iterator specified by the first two
   117783 ** arguments so that it points to the first element with a value greater
   117784 ** than or equal to parameter iNext.
   117785 */
   117786 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
   117787   char *pIter = *ppIter;
   117788   if( pIter ){
   117789     int iIter = *piIter;
   117790 
   117791     while( iIter<iNext ){
   117792       if( 0==(*pIter & 0xFE) ){
   117793         iIter = -1;
   117794         pIter = 0;
   117795         break;
   117796       }
   117797       fts3GetDeltaPosition(&pIter, &iIter);
   117798     }
   117799 
   117800     *piIter = iIter;
   117801     *ppIter = pIter;
   117802   }
   117803 }
   117804 
   117805 /*
   117806 ** Advance the snippet iterator to the next candidate snippet.
   117807 */
   117808 static int fts3SnippetNextCandidate(SnippetIter *pIter){
   117809   int i;                          /* Loop counter */
   117810 
   117811   if( pIter->iCurrent<0 ){
   117812     /* The SnippetIter object has just been initialized. The first snippet
   117813     ** candidate always starts at offset 0 (even if this candidate has a
   117814     ** score of 0.0).
   117815     */
   117816     pIter->iCurrent = 0;
   117817 
   117818     /* Advance the 'head' iterator of each phrase to the first offset that
   117819     ** is greater than or equal to (iNext+nSnippet).
   117820     */
   117821     for(i=0; i<pIter->nPhrase; i++){
   117822       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   117823       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
   117824     }
   117825   }else{
   117826     int iStart;
   117827     int iEnd = 0x7FFFFFFF;
   117828 
   117829     for(i=0; i<pIter->nPhrase; i++){
   117830       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   117831       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
   117832         iEnd = pPhrase->iHead;
   117833       }
   117834     }
   117835     if( iEnd==0x7FFFFFFF ){
   117836       return 1;
   117837     }
   117838 
   117839     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
   117840     for(i=0; i<pIter->nPhrase; i++){
   117841       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   117842       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
   117843       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
   117844     }
   117845   }
   117846 
   117847   return 0;
   117848 }
   117849 
   117850 /*
   117851 ** Retrieve information about the current candidate snippet of snippet
   117852 ** iterator pIter.
   117853 */
   117854 static void fts3SnippetDetails(
   117855   SnippetIter *pIter,             /* Snippet iterator */
   117856   u64 mCovered,                   /* Bitmask of phrases already covered */
   117857   int *piToken,                   /* OUT: First token of proposed snippet */
   117858   int *piScore,                   /* OUT: "Score" for this snippet */
   117859   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
   117860   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
   117861 ){
   117862   int iStart = pIter->iCurrent;   /* First token of snippet */
   117863   int iScore = 0;                 /* Score of this snippet */
   117864   int i;                          /* Loop counter */
   117865   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
   117866   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
   117867 
   117868   for(i=0; i<pIter->nPhrase; i++){
   117869     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
   117870     if( pPhrase->pTail ){
   117871       char *pCsr = pPhrase->pTail;
   117872       int iCsr = pPhrase->iTail;
   117873 
   117874       while( iCsr<(iStart+pIter->nSnippet) ){
   117875         int j;
   117876         u64 mPhrase = (u64)1 << i;
   117877         u64 mPos = (u64)1 << (iCsr - iStart);
   117878         assert( iCsr>=iStart );
   117879         if( (mCover|mCovered)&mPhrase ){
   117880           iScore++;
   117881         }else{
   117882           iScore += 1000;
   117883         }
   117884         mCover |= mPhrase;
   117885 
   117886         for(j=0; j<pPhrase->nToken; j++){
   117887           mHighlight |= (mPos>>j);
   117888         }
   117889 
   117890         if( 0==(*pCsr & 0x0FE) ) break;
   117891         fts3GetDeltaPosition(&pCsr, &iCsr);
   117892       }
   117893     }
   117894   }
   117895 
   117896   /* Set the output variables before returning. */
   117897   *piToken = iStart;
   117898   *piScore = iScore;
   117899   *pmCover = mCover;
   117900   *pmHighlight = mHighlight;
   117901 }
   117902 
   117903 /*
   117904 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
   117905 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
   117906 */
   117907 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
   117908   SnippetIter *p = (SnippetIter *)ctx;
   117909   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
   117910   char *pCsr;
   117911 
   117912   pPhrase->nToken = pExpr->pPhrase->nToken;
   117913 
   117914   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
   117915   if( pCsr ){
   117916     int iFirst = 0;
   117917     pPhrase->pList = pCsr;
   117918     fts3GetDeltaPosition(&pCsr, &iFirst);
   117919     pPhrase->pHead = pCsr;
   117920     pPhrase->pTail = pCsr;
   117921     pPhrase->iHead = iFirst;
   117922     pPhrase->iTail = iFirst;
   117923   }else{
   117924     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
   117925   }
   117926 
   117927   return SQLITE_OK;
   117928 }
   117929 
   117930 /*
   117931 ** Select the fragment of text consisting of nFragment contiguous tokens
   117932 ** from column iCol that represent the "best" snippet. The best snippet
   117933 ** is the snippet with the highest score, where scores are calculated
   117934 ** by adding:
   117935 **
   117936 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
   117937 **
   117938 **   (b) +1000 points for the first occurence of each matchable phrase in
   117939 **       the snippet for which the corresponding mCovered bit is not set.
   117940 **
   117941 ** The selected snippet parameters are stored in structure *pFragment before
   117942 ** returning. The score of the selected snippet is stored in *piScore
   117943 ** before returning.
   117944 */
   117945 static int fts3BestSnippet(
   117946   int nSnippet,                   /* Desired snippet length */
   117947   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
   117948   int iCol,                       /* Index of column to create snippet from */
   117949   u64 mCovered,                   /* Mask of phrases already covered */
   117950   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
   117951   SnippetFragment *pFragment,     /* OUT: Best snippet found */
   117952   int *piScore                    /* OUT: Score of snippet pFragment */
   117953 ){
   117954   int rc;                         /* Return Code */
   117955   int nList;                      /* Number of phrases in expression */
   117956   SnippetIter sIter;              /* Iterates through snippet candidates */
   117957   int nByte;                      /* Number of bytes of space to allocate */
   117958   int iBestScore = -1;            /* Best snippet score found so far */
   117959   int i;                          /* Loop counter */
   117960 
   117961   memset(&sIter, 0, sizeof(sIter));
   117962 
   117963   /* Iterate through the phrases in the expression to count them. The same
   117964   ** callback makes sure the doclists are loaded for each phrase.
   117965   */
   117966   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
   117967   if( rc!=SQLITE_OK ){
   117968     return rc;
   117969   }
   117970 
   117971   /* Now that it is known how many phrases there are, allocate and zero
   117972   ** the required space using malloc().
   117973   */
   117974   nByte = sizeof(SnippetPhrase) * nList;
   117975   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
   117976   if( !sIter.aPhrase ){
   117977     return SQLITE_NOMEM;
   117978   }
   117979   memset(sIter.aPhrase, 0, nByte);
   117980 
   117981   /* Initialize the contents of the SnippetIter object. Then iterate through
   117982   ** the set of phrases in the expression to populate the aPhrase[] array.
   117983   */
   117984   sIter.pCsr = pCsr;
   117985   sIter.iCol = iCol;
   117986   sIter.nSnippet = nSnippet;
   117987   sIter.nPhrase = nList;
   117988   sIter.iCurrent = -1;
   117989   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
   117990 
   117991   /* Set the *pmSeen output variable. */
   117992   for(i=0; i<nList; i++){
   117993     if( sIter.aPhrase[i].pHead ){
   117994       *pmSeen |= (u64)1 << i;
   117995     }
   117996   }
   117997 
   117998   /* Loop through all candidate snippets. Store the best snippet in
   117999   ** *pFragment. Store its associated 'score' in iBestScore.
   118000   */
   118001   pFragment->iCol = iCol;
   118002   while( !fts3SnippetNextCandidate(&sIter) ){
   118003     int iPos;
   118004     int iScore;
   118005     u64 mCover;
   118006     u64 mHighlight;
   118007     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
   118008     assert( iScore>=0 );
   118009     if( iScore>iBestScore ){
   118010       pFragment->iPos = iPos;
   118011       pFragment->hlmask = mHighlight;
   118012       pFragment->covered = mCover;
   118013       iBestScore = iScore;
   118014     }
   118015   }
   118016 
   118017   sqlite3_free(sIter.aPhrase);
   118018   *piScore = iBestScore;
   118019   return SQLITE_OK;
   118020 }
   118021 
   118022 
   118023 /*
   118024 ** Append a string to the string-buffer passed as the first argument.
   118025 **
   118026 ** If nAppend is negative, then the length of the string zAppend is
   118027 ** determined using strlen().
   118028 */
   118029 static int fts3StringAppend(
   118030   StrBuffer *pStr,                /* Buffer to append to */
   118031   const char *zAppend,            /* Pointer to data to append to buffer */
   118032   int nAppend                     /* Size of zAppend in bytes (or -1) */
   118033 ){
   118034   if( nAppend<0 ){
   118035     nAppend = (int)strlen(zAppend);
   118036   }
   118037 
   118038   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
   118039   ** to grow the buffer until so that it is big enough to accomadate the
   118040   ** appended data.
   118041   */
   118042   if( pStr->n+nAppend+1>=pStr->nAlloc ){
   118043     int nAlloc = pStr->nAlloc+nAppend+100;
   118044     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
   118045     if( !zNew ){
   118046       return SQLITE_NOMEM;
   118047     }
   118048     pStr->z = zNew;
   118049     pStr->nAlloc = nAlloc;
   118050   }
   118051 
   118052   /* Append the data to the string buffer. */
   118053   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
   118054   pStr->n += nAppend;
   118055   pStr->z[pStr->n] = '\0';
   118056 
   118057   return SQLITE_OK;
   118058 }
   118059 
   118060 /*
   118061 ** The fts3BestSnippet() function often selects snippets that end with a
   118062 ** query term. That is, the final term of the snippet is always a term
   118063 ** that requires highlighting. For example, if 'X' is a highlighted term
   118064 ** and '.' is a non-highlighted term, BestSnippet() may select:
   118065 **
   118066 **     ........X.....X
   118067 **
   118068 ** This function "shifts" the beginning of the snippet forward in the
   118069 ** document so that there are approximately the same number of
   118070 ** non-highlighted terms to the right of the final highlighted term as there
   118071 ** are to the left of the first highlighted term. For example, to this:
   118072 **
   118073 **     ....X.....X....
   118074 **
   118075 ** This is done as part of extracting the snippet text, not when selecting
   118076 ** the snippet. Snippet selection is done based on doclists only, so there
   118077 ** is no way for fts3BestSnippet() to know whether or not the document
   118078 ** actually contains terms that follow the final highlighted term.
   118079 */
   118080 static int fts3SnippetShift(
   118081   Fts3Table *pTab,                /* FTS3 table snippet comes from */
   118082   int nSnippet,                   /* Number of tokens desired for snippet */
   118083   const char *zDoc,               /* Document text to extract snippet from */
   118084   int nDoc,                       /* Size of buffer zDoc in bytes */
   118085   int *piPos,                     /* IN/OUT: First token of snippet */
   118086   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
   118087 ){
   118088   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
   118089 
   118090   if( hlmask ){
   118091     int nLeft;                    /* Tokens to the left of first highlight */
   118092     int nRight;                   /* Tokens to the right of last highlight */
   118093     int nDesired;                 /* Ideal number of tokens to shift forward */
   118094 
   118095     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
   118096     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
   118097     nDesired = (nLeft-nRight)/2;
   118098 
   118099     /* Ideally, the start of the snippet should be pushed forward in the
   118100     ** document nDesired tokens. This block checks if there are actually
   118101     ** nDesired tokens to the right of the snippet. If so, *piPos and
   118102     ** *pHlMask are updated to shift the snippet nDesired tokens to the
   118103     ** right. Otherwise, the snippet is shifted by the number of tokens
   118104     ** available.
   118105     */
   118106     if( nDesired>0 ){
   118107       int nShift;                 /* Number of tokens to shift snippet by */
   118108       int iCurrent = 0;           /* Token counter */
   118109       int rc;                     /* Return Code */
   118110       sqlite3_tokenizer_module *pMod;
   118111       sqlite3_tokenizer_cursor *pC;
   118112       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   118113 
   118114       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
   118115       ** or more tokens in zDoc/nDoc.
   118116       */
   118117       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
   118118       if( rc!=SQLITE_OK ){
   118119         return rc;
   118120       }
   118121       pC->pTokenizer = pTab->pTokenizer;
   118122       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
   118123         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
   118124         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
   118125       }
   118126       pMod->xClose(pC);
   118127       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
   118128 
   118129       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
   118130       assert( nShift<=nDesired );
   118131       if( nShift>0 ){
   118132         *piPos += nShift;
   118133         *pHlmask = hlmask >> nShift;
   118134       }
   118135     }
   118136   }
   118137   return SQLITE_OK;
   118138 }
   118139 
   118140 /*
   118141 ** Extract the snippet text for fragment pFragment from cursor pCsr and
   118142 ** append it to string buffer pOut.
   118143 */
   118144 static int fts3SnippetText(
   118145   Fts3Cursor *pCsr,               /* FTS3 Cursor */
   118146   SnippetFragment *pFragment,     /* Snippet to extract */
   118147   int iFragment,                  /* Fragment number */
   118148   int isLast,                     /* True for final fragment in snippet */
   118149   int nSnippet,                   /* Number of tokens in extracted snippet */
   118150   const char *zOpen,              /* String inserted before highlighted term */
   118151   const char *zClose,             /* String inserted after highlighted term */
   118152   const char *zEllipsis,          /* String inserted between snippets */
   118153   StrBuffer *pOut                 /* Write output here */
   118154 ){
   118155   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   118156   int rc;                         /* Return code */
   118157   const char *zDoc;               /* Document text to extract snippet from */
   118158   int nDoc;                       /* Size of zDoc in bytes */
   118159   int iCurrent = 0;               /* Current token number of document */
   118160   int iEnd = 0;                   /* Byte offset of end of current token */
   118161   int isShiftDone = 0;            /* True after snippet is shifted */
   118162   int iPos = pFragment->iPos;     /* First token of snippet */
   118163   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
   118164   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   118165   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   118166   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
   118167   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
   118168   int DUMMY1;                     /* Dummy argument used with tokenizer */
   118169 
   118170   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   118171   if( zDoc==0 ){
   118172     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
   118173       return SQLITE_NOMEM;
   118174     }
   118175     return SQLITE_OK;
   118176   }
   118177   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
   118178 
   118179   /* Open a token cursor on the document. */
   118180   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
   118181   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
   118182   if( rc!=SQLITE_OK ){
   118183     return rc;
   118184   }
   118185   pC->pTokenizer = pTab->pTokenizer;
   118186 
   118187   while( rc==SQLITE_OK ){
   118188     int iBegin;                   /* Offset in zDoc of start of token */
   118189     int iFin;                     /* Offset in zDoc of end of token */
   118190     int isHighlight;              /* True for highlighted terms */
   118191 
   118192     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
   118193     if( rc!=SQLITE_OK ){
   118194       if( rc==SQLITE_DONE ){
   118195         /* Special case - the last token of the snippet is also the last token
   118196         ** of the column. Append any punctuation that occurred between the end
   118197         ** of the previous token and the end of the document to the output.
   118198         ** Then break out of the loop. */
   118199         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
   118200       }
   118201       break;
   118202     }
   118203     if( iCurrent<iPos ){ continue; }
   118204 
   118205     if( !isShiftDone ){
   118206       int n = nDoc - iBegin;
   118207       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
   118208       isShiftDone = 1;
   118209 
   118210       /* Now that the shift has been done, check if the initial "..." are
   118211       ** required. They are required if (a) this is not the first fragment,
   118212       ** or (b) this fragment does not begin at position 0 of its column.
   118213       */
   118214       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
   118215         rc = fts3StringAppend(pOut, zEllipsis, -1);
   118216       }
   118217       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
   118218     }
   118219 
   118220     if( iCurrent>=(iPos+nSnippet) ){
   118221       if( isLast ){
   118222         rc = fts3StringAppend(pOut, zEllipsis, -1);
   118223       }
   118224       break;
   118225     }
   118226 
   118227     /* Set isHighlight to true if this term should be highlighted. */
   118228     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
   118229 
   118230     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
   118231     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
   118232     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
   118233     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
   118234 
   118235     iEnd = iFin;
   118236   }
   118237 
   118238   pMod->xClose(pC);
   118239   return rc;
   118240 }
   118241 
   118242 
   118243 /*
   118244 ** This function is used to count the entries in a column-list (a
   118245 ** delta-encoded list of term offsets within a single column of a single
   118246 ** row). When this function is called, *ppCollist should point to the
   118247 ** beginning of the first varint in the column-list (the varint that
   118248 ** contains the position of the first matching term in the column data).
   118249 ** Before returning, *ppCollist is set to point to the first byte after
   118250 ** the last varint in the column-list (either the 0x00 signifying the end
   118251 ** of the position-list, or the 0x01 that precedes the column number of
   118252 ** the next column in the position-list).
   118253 **
   118254 ** The number of elements in the column-list is returned.
   118255 */
   118256 static int fts3ColumnlistCount(char **ppCollist){
   118257   char *pEnd = *ppCollist;
   118258   char c = 0;
   118259   int nEntry = 0;
   118260 
   118261   /* A column-list is terminated by either a 0x01 or 0x00. */
   118262   while( 0xFE & (*pEnd | c) ){
   118263     c = *pEnd++ & 0x80;
   118264     if( !c ) nEntry++;
   118265   }
   118266 
   118267   *ppCollist = pEnd;
   118268   return nEntry;
   118269 }
   118270 
   118271 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
   118272   char *pCsr = *pp;
   118273   while( *pCsr ){
   118274     int nHit;
   118275     sqlite3_int64 iCol = 0;
   118276     if( *pCsr==0x01 ){
   118277       pCsr++;
   118278       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
   118279     }
   118280     nHit = fts3ColumnlistCount(&pCsr);
   118281     assert( nHit>0 );
   118282     if( isGlobal ){
   118283       aOut[iCol*3+1]++;
   118284     }
   118285     aOut[iCol*3] += nHit;
   118286   }
   118287   pCsr++;
   118288   *pp = pCsr;
   118289 }
   118290 
   118291 /*
   118292 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
   118293 ** for a single query.
   118294 **
   118295 ** fts3ExprIterate() callback to load the 'global' elements of a
   118296 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
   118297 ** of the matchinfo array that are constant for all rows returned by the
   118298 ** current query.
   118299 **
   118300 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
   118301 ** function populates Matchinfo.aMatchinfo[] as follows:
   118302 **
   118303 **   for(iCol=0; iCol<nCol; iCol++){
   118304 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
   118305 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
   118306 **   }
   118307 **
   118308 ** where X is the number of matches for phrase iPhrase is column iCol of all
   118309 ** rows of the table. Y is the number of rows for which column iCol contains
   118310 ** at least one instance of phrase iPhrase.
   118311 **
   118312 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
   118313 ** Y values are set to nDoc, where nDoc is the number of documents in the
   118314 ** file system. This is done because the full-text index doclist is required
   118315 ** to calculate these values properly, and the full-text index doclist is
   118316 ** not available for deferred tokens.
   118317 */
   118318 static int fts3ExprGlobalHitsCb(
   118319   Fts3Expr *pExpr,                /* Phrase expression node */
   118320   int iPhrase,                    /* Phrase number (numbered from zero) */
   118321   void *pCtx                      /* Pointer to MatchInfo structure */
   118322 ){
   118323   MatchInfo *p = (MatchInfo *)pCtx;
   118324   Fts3Cursor *pCsr = p->pCursor;
   118325   char *pIter;
   118326   char *pEnd;
   118327   char *pFree = 0;
   118328   u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
   118329 
   118330   assert( pExpr->isLoaded );
   118331   assert( pExpr->eType==FTSQUERY_PHRASE );
   118332 
   118333   if( pCsr->pDeferred ){
   118334     Fts3Phrase *pPhrase = pExpr->pPhrase;
   118335     int ii;
   118336     for(ii=0; ii<pPhrase->nToken; ii++){
   118337       if( pPhrase->aToken[ii].bFulltext ) break;
   118338     }
   118339     if( ii<pPhrase->nToken ){
   118340       int nFree = 0;
   118341       int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
   118342       if( rc!=SQLITE_OK ) return rc;
   118343       pIter = pFree;
   118344       pEnd = &pFree[nFree];
   118345     }else{
   118346       int iCol;                   /* Column index */
   118347       for(iCol=0; iCol<p->nCol; iCol++){
   118348         aOut[iCol*3 + 1] = (u32)p->nDoc;
   118349         aOut[iCol*3 + 2] = (u32)p->nDoc;
   118350       }
   118351       return SQLITE_OK;
   118352     }
   118353   }else{
   118354     pIter = pExpr->aDoclist;
   118355     pEnd = &pExpr->aDoclist[pExpr->nDoclist];
   118356   }
   118357 
   118358   /* Fill in the global hit count matrix row for this phrase. */
   118359   while( pIter<pEnd ){
   118360     while( *pIter++ & 0x80 );      /* Skip past docid. */
   118361     fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
   118362   }
   118363 
   118364   sqlite3_free(pFree);
   118365   return SQLITE_OK;
   118366 }
   118367 
   118368 /*
   118369 ** fts3ExprIterate() callback used to collect the "local" part of the
   118370 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
   118371 ** array that are different for each row returned by the query.
   118372 */
   118373 static int fts3ExprLocalHitsCb(
   118374   Fts3Expr *pExpr,                /* Phrase expression node */
   118375   int iPhrase,                    /* Phrase number */
   118376   void *pCtx                      /* Pointer to MatchInfo structure */
   118377 ){
   118378   MatchInfo *p = (MatchInfo *)pCtx;
   118379 
   118380   if( pExpr->aDoclist ){
   118381     char *pCsr;
   118382     int iStart = iPhrase * p->nCol * 3;
   118383     int i;
   118384 
   118385     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
   118386 
   118387     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
   118388     if( pCsr ){
   118389       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
   118390     }
   118391   }
   118392 
   118393   return SQLITE_OK;
   118394 }
   118395 
   118396 static int fts3MatchinfoCheck(
   118397   Fts3Table *pTab,
   118398   char cArg,
   118399   char **pzErr
   118400 ){
   118401   if( (cArg==FTS3_MATCHINFO_NPHRASE)
   118402    || (cArg==FTS3_MATCHINFO_NCOL)
   118403    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
   118404    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
   118405    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
   118406    || (cArg==FTS3_MATCHINFO_LCS)
   118407    || (cArg==FTS3_MATCHINFO_HITS)
   118408   ){
   118409     return SQLITE_OK;
   118410   }
   118411   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
   118412   return SQLITE_ERROR;
   118413 }
   118414 
   118415 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
   118416   int nVal;                       /* Number of integers output by cArg */
   118417 
   118418   switch( cArg ){
   118419     case FTS3_MATCHINFO_NDOC:
   118420     case FTS3_MATCHINFO_NPHRASE:
   118421     case FTS3_MATCHINFO_NCOL:
   118422       nVal = 1;
   118423       break;
   118424 
   118425     case FTS3_MATCHINFO_AVGLENGTH:
   118426     case FTS3_MATCHINFO_LENGTH:
   118427     case FTS3_MATCHINFO_LCS:
   118428       nVal = pInfo->nCol;
   118429       break;
   118430 
   118431     default:
   118432       assert( cArg==FTS3_MATCHINFO_HITS );
   118433       nVal = pInfo->nCol * pInfo->nPhrase * 3;
   118434       break;
   118435   }
   118436 
   118437   return nVal;
   118438 }
   118439 
   118440 static int fts3MatchinfoSelectDoctotal(
   118441   Fts3Table *pTab,
   118442   sqlite3_stmt **ppStmt,
   118443   sqlite3_int64 *pnDoc,
   118444   const char **paLen
   118445 ){
   118446   sqlite3_stmt *pStmt;
   118447   const char *a;
   118448   sqlite3_int64 nDoc;
   118449 
   118450   if( !*ppStmt ){
   118451     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
   118452     if( rc!=SQLITE_OK ) return rc;
   118453   }
   118454   pStmt = *ppStmt;
   118455 
   118456   a = sqlite3_column_blob(pStmt, 0);
   118457   a += sqlite3Fts3GetVarint(a, &nDoc);
   118458   *pnDoc = (u32)nDoc;
   118459 
   118460   if( paLen ) *paLen = a;
   118461   return SQLITE_OK;
   118462 }
   118463 
   118464 /*
   118465 ** An instance of the following structure is used to store state while
   118466 ** iterating through a multi-column position-list corresponding to the
   118467 ** hits for a single phrase on a single row in order to calculate the
   118468 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
   118469 */
   118470 typedef struct LcsIterator LcsIterator;
   118471 struct LcsIterator {
   118472   Fts3Expr *pExpr;                /* Pointer to phrase expression */
   118473   char *pRead;                    /* Cursor used to iterate through aDoclist */
   118474   int iPosOffset;                 /* Tokens count up to end of this phrase */
   118475   int iCol;                       /* Current column number */
   118476   int iPos;                       /* Current position */
   118477 };
   118478 
   118479 /*
   118480 ** If LcsIterator.iCol is set to the following value, the iterator has
   118481 ** finished iterating through all offsets for all columns.
   118482 */
   118483 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
   118484 
   118485 static int fts3MatchinfoLcsCb(
   118486   Fts3Expr *pExpr,                /* Phrase expression node */
   118487   int iPhrase,                    /* Phrase number (numbered from zero) */
   118488   void *pCtx                      /* Pointer to MatchInfo structure */
   118489 ){
   118490   LcsIterator *aIter = (LcsIterator *)pCtx;
   118491   aIter[iPhrase].pExpr = pExpr;
   118492   return SQLITE_OK;
   118493 }
   118494 
   118495 /*
   118496 ** Advance the iterator passed as an argument to the next position. Return
   118497 ** 1 if the iterator is at EOF or if it now points to the start of the
   118498 ** position list for the next column.
   118499 */
   118500 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   118501   char *pRead = pIter->pRead;
   118502   sqlite3_int64 iRead;
   118503   int rc = 0;
   118504 
   118505   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   118506   if( iRead==0 ){
   118507     pIter->iCol = LCS_ITERATOR_FINISHED;
   118508     rc = 1;
   118509   }else{
   118510     if( iRead==1 ){
   118511       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   118512       pIter->iCol = (int)iRead;
   118513       pIter->iPos = pIter->iPosOffset;
   118514       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
   118515       rc = 1;
   118516     }
   118517     pIter->iPos += (int)(iRead-2);
   118518   }
   118519 
   118520   pIter->pRead = pRead;
   118521   return rc;
   118522 }
   118523 
   118524 /*
   118525 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
   118526 **
   118527 ** If the call is successful, the longest-common-substring lengths for each
   118528 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
   118529 ** array before returning. SQLITE_OK is returned in this case.
   118530 **
   118531 ** Otherwise, if an error occurs, an SQLite error code is returned and the
   118532 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
   118533 ** undefined.
   118534 */
   118535 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
   118536   LcsIterator *aIter;
   118537   int i;
   118538   int iCol;
   118539   int nToken = 0;
   118540 
   118541   /* Allocate and populate the array of LcsIterator objects. The array
   118542   ** contains one element for each matchable phrase in the query.
   118543   **/
   118544   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
   118545   if( !aIter ) return SQLITE_NOMEM;
   118546   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
   118547   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
   118548   for(i=0; i<pInfo->nPhrase; i++){
   118549     LcsIterator *pIter = &aIter[i];
   118550     nToken -= pIter->pExpr->pPhrase->nToken;
   118551     pIter->iPosOffset = nToken;
   118552     pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
   118553     if( pIter->pRead ){
   118554       pIter->iPos = pIter->iPosOffset;
   118555       fts3LcsIteratorAdvance(&aIter[i]);
   118556     }else{
   118557       pIter->iCol = LCS_ITERATOR_FINISHED;
   118558     }
   118559   }
   118560 
   118561   for(iCol=0; iCol<pInfo->nCol; iCol++){
   118562     int nLcs = 0;                 /* LCS value for this column */
   118563     int nLive = 0;                /* Number of iterators in aIter not at EOF */
   118564 
   118565     /* Loop through the iterators in aIter[]. Set nLive to the number of
   118566     ** iterators that point to a position-list corresponding to column iCol.
   118567     */
   118568     for(i=0; i<pInfo->nPhrase; i++){
   118569       assert( aIter[i].iCol>=iCol );
   118570       if( aIter[i].iCol==iCol ) nLive++;
   118571     }
   118572 
   118573     /* The following loop runs until all iterators in aIter[] have finished
   118574     ** iterating through positions in column iCol. Exactly one of the
   118575     ** iterators is advanced each time the body of the loop is run.
   118576     */
   118577     while( nLive>0 ){
   118578       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
   118579       int nThisLcs = 0;           /* LCS for the current iterator positions */
   118580 
   118581       for(i=0; i<pInfo->nPhrase; i++){
   118582         LcsIterator *pIter = &aIter[i];
   118583         if( iCol!=pIter->iCol ){
   118584           /* This iterator is already at EOF for this column. */
   118585           nThisLcs = 0;
   118586         }else{
   118587           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
   118588             pAdv = pIter;
   118589           }
   118590           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
   118591             nThisLcs++;
   118592           }else{
   118593             nThisLcs = 1;
   118594           }
   118595           if( nThisLcs>nLcs ) nLcs = nThisLcs;
   118596         }
   118597       }
   118598       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
   118599     }
   118600 
   118601     pInfo->aMatchinfo[iCol] = nLcs;
   118602   }
   118603 
   118604   sqlite3_free(aIter);
   118605   return SQLITE_OK;
   118606 }
   118607 
   118608 /*
   118609 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
   118610 ** be returned by the matchinfo() function. Argument zArg contains the
   118611 ** format string passed as the second argument to matchinfo (or the
   118612 ** default value "pcx" if no second argument was specified). The format
   118613 ** string has already been validated and the pInfo->aMatchinfo[] array
   118614 ** is guaranteed to be large enough for the output.
   118615 **
   118616 ** If bGlobal is true, then populate all fields of the matchinfo() output.
   118617 ** If it is false, then assume that those fields that do not change between
   118618 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
   118619 ** have already been populated.
   118620 **
   118621 ** Return SQLITE_OK if successful, or an SQLite error code if an error
   118622 ** occurs. If a value other than SQLITE_OK is returned, the state the
   118623 ** pInfo->aMatchinfo[] buffer is left in is undefined.
   118624 */
   118625 static int fts3MatchinfoValues(
   118626   Fts3Cursor *pCsr,               /* FTS3 cursor object */
   118627   int bGlobal,                    /* True to grab the global stats */
   118628   MatchInfo *pInfo,               /* Matchinfo context object */
   118629   const char *zArg                /* Matchinfo format string */
   118630 ){
   118631   int rc = SQLITE_OK;
   118632   int i;
   118633   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   118634   sqlite3_stmt *pSelect = 0;
   118635 
   118636   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
   118637 
   118638     switch( zArg[i] ){
   118639       case FTS3_MATCHINFO_NPHRASE:
   118640         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
   118641         break;
   118642 
   118643       case FTS3_MATCHINFO_NCOL:
   118644         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
   118645         break;
   118646 
   118647       case FTS3_MATCHINFO_NDOC:
   118648         if( bGlobal ){
   118649           sqlite3_int64 nDoc;
   118650           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
   118651           pInfo->aMatchinfo[0] = (u32)nDoc;
   118652         }
   118653         break;
   118654 
   118655       case FTS3_MATCHINFO_AVGLENGTH:
   118656         if( bGlobal ){
   118657           sqlite3_int64 nDoc;     /* Number of rows in table */
   118658           const char *a;          /* Aggregate column length array */
   118659 
   118660           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
   118661           if( rc==SQLITE_OK ){
   118662             int iCol;
   118663             for(iCol=0; iCol<pInfo->nCol; iCol++){
   118664               sqlite3_int64 nToken;
   118665               a += sqlite3Fts3GetVarint(a, &nToken);
   118666               pInfo->aMatchinfo[iCol] = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
   118667             }
   118668           }
   118669         }
   118670         break;
   118671 
   118672       case FTS3_MATCHINFO_LENGTH: {
   118673         sqlite3_stmt *pSelectDocsize = 0;
   118674         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
   118675         if( rc==SQLITE_OK ){
   118676           int iCol;
   118677           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
   118678           for(iCol=0; iCol<pInfo->nCol; iCol++){
   118679             sqlite3_int64 nToken;
   118680             a += sqlite3Fts3GetVarint(a, &nToken);
   118681             pInfo->aMatchinfo[iCol] = (u32)nToken;
   118682           }
   118683         }
   118684         sqlite3_reset(pSelectDocsize);
   118685         break;
   118686       }
   118687 
   118688       case FTS3_MATCHINFO_LCS:
   118689         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   118690         if( rc==SQLITE_OK ){
   118691           rc = fts3MatchinfoLcs(pCsr, pInfo);
   118692         }
   118693         break;
   118694 
   118695       default: {
   118696         Fts3Expr *pExpr;
   118697         assert( zArg[i]==FTS3_MATCHINFO_HITS );
   118698         pExpr = pCsr->pExpr;
   118699         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
   118700         if( rc!=SQLITE_OK ) break;
   118701         if( bGlobal ){
   118702           if( pCsr->pDeferred ){
   118703             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
   118704             if( rc!=SQLITE_OK ) break;
   118705           }
   118706           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
   118707           if( rc!=SQLITE_OK ) break;
   118708         }
   118709         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
   118710         break;
   118711       }
   118712     }
   118713 
   118714     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
   118715   }
   118716 
   118717   sqlite3_reset(pSelect);
   118718   return rc;
   118719 }
   118720 
   118721 
   118722 /*
   118723 ** Populate pCsr->aMatchinfo[] with data for the current row. The
   118724 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
   118725 */
   118726 static int fts3GetMatchinfo(
   118727   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
   118728   const char *zArg                /* Second argument to matchinfo() function */
   118729 ){
   118730   MatchInfo sInfo;
   118731   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   118732   int rc = SQLITE_OK;
   118733   int bGlobal = 0;                /* Collect 'global' stats as well as local */
   118734 
   118735   memset(&sInfo, 0, sizeof(MatchInfo));
   118736   sInfo.pCursor = pCsr;
   118737   sInfo.nCol = pTab->nColumn;
   118738 
   118739   /* If there is cached matchinfo() data, but the format string for the
   118740   ** cache does not match the format string for this request, discard
   118741   ** the cached data. */
   118742   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
   118743     assert( pCsr->aMatchinfo );
   118744     sqlite3_free(pCsr->aMatchinfo);
   118745     pCsr->zMatchinfo = 0;
   118746     pCsr->aMatchinfo = 0;
   118747   }
   118748 
   118749   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
   118750   ** matchinfo function has been called for this query. In this case
   118751   ** allocate the array used to accumulate the matchinfo data and
   118752   ** initialize those elements that are constant for every row.
   118753   */
   118754   if( pCsr->aMatchinfo==0 ){
   118755     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
   118756     int nArg;                     /* Bytes in zArg */
   118757     int i;                        /* Used to iterate through zArg */
   118758 
   118759     /* Determine the number of phrases in the query */
   118760     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
   118761     sInfo.nPhrase = pCsr->nPhrase;
   118762 
   118763     /* Determine the number of integers in the buffer returned by this call. */
   118764     for(i=0; zArg[i]; i++){
   118765       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
   118766     }
   118767 
   118768     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
   118769     nArg = (int)strlen(zArg);
   118770     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
   118771     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
   118772 
   118773     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
   118774     pCsr->nMatchinfo = nMatchinfo;
   118775     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
   118776     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
   118777     pCsr->isMatchinfoNeeded = 1;
   118778     bGlobal = 1;
   118779   }
   118780 
   118781   sInfo.aMatchinfo = pCsr->aMatchinfo;
   118782   sInfo.nPhrase = pCsr->nPhrase;
   118783   if( pCsr->isMatchinfoNeeded ){
   118784     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
   118785     pCsr->isMatchinfoNeeded = 0;
   118786   }
   118787 
   118788   return rc;
   118789 }
   118790 
   118791 /*
   118792 ** Implementation of snippet() function.
   118793 */
   118794 SQLITE_PRIVATE void sqlite3Fts3Snippet(
   118795   sqlite3_context *pCtx,          /* SQLite function call context */
   118796   Fts3Cursor *pCsr,               /* Cursor object */
   118797   const char *zStart,             /* Snippet start text - "<b>" */
   118798   const char *zEnd,               /* Snippet end text - "</b>" */
   118799   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
   118800   int iCol,                       /* Extract snippet from this column */
   118801   int nToken                      /* Approximate number of tokens in snippet */
   118802 ){
   118803   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   118804   int rc = SQLITE_OK;
   118805   int i;
   118806   StrBuffer res = {0, 0, 0};
   118807 
   118808   /* The returned text includes up to four fragments of text extracted from
   118809   ** the data in the current row. The first iteration of the for(...) loop
   118810   ** below attempts to locate a single fragment of text nToken tokens in
   118811   ** size that contains at least one instance of all phrases in the query
   118812   ** expression that appear in the current row. If such a fragment of text
   118813   ** cannot be found, the second iteration of the loop attempts to locate
   118814   ** a pair of fragments, and so on.
   118815   */
   118816   int nSnippet = 0;               /* Number of fragments in this snippet */
   118817   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
   118818   int nFToken = -1;               /* Number of tokens in each fragment */
   118819 
   118820   if( !pCsr->pExpr ){
   118821     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   118822     return;
   118823   }
   118824 
   118825   for(nSnippet=1; 1; nSnippet++){
   118826 
   118827     int iSnip;                    /* Loop counter 0..nSnippet-1 */
   118828     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
   118829     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
   118830 
   118831     if( nToken>=0 ){
   118832       nFToken = (nToken+nSnippet-1) / nSnippet;
   118833     }else{
   118834       nFToken = -1 * nToken;
   118835     }
   118836 
   118837     for(iSnip=0; iSnip<nSnippet; iSnip++){
   118838       int iBestScore = -1;        /* Best score of columns checked so far */
   118839       int iRead;                  /* Used to iterate through columns */
   118840       SnippetFragment *pFragment = &aSnippet[iSnip];
   118841 
   118842       memset(pFragment, 0, sizeof(*pFragment));
   118843 
   118844       /* Loop through all columns of the table being considered for snippets.
   118845       ** If the iCol argument to this function was negative, this means all
   118846       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
   118847       */
   118848       for(iRead=0; iRead<pTab->nColumn; iRead++){
   118849         SnippetFragment sF = {0, 0, 0, 0};
   118850         int iS;
   118851         if( iCol>=0 && iRead!=iCol ) continue;
   118852 
   118853         /* Find the best snippet of nFToken tokens in column iRead. */
   118854         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
   118855         if( rc!=SQLITE_OK ){
   118856           goto snippet_out;
   118857         }
   118858         if( iS>iBestScore ){
   118859           *pFragment = sF;
   118860           iBestScore = iS;
   118861         }
   118862       }
   118863 
   118864       mCovered |= pFragment->covered;
   118865     }
   118866 
   118867     /* If all query phrases seen by fts3BestSnippet() are present in at least
   118868     ** one of the nSnippet snippet fragments, break out of the loop.
   118869     */
   118870     assert( (mCovered&mSeen)==mCovered );
   118871     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
   118872   }
   118873 
   118874   assert( nFToken>0 );
   118875 
   118876   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
   118877     rc = fts3SnippetText(pCsr, &aSnippet[i],
   118878         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
   118879     );
   118880   }
   118881 
   118882  snippet_out:
   118883   sqlite3Fts3SegmentsClose(pTab);
   118884   if( rc!=SQLITE_OK ){
   118885     sqlite3_result_error_code(pCtx, rc);
   118886     sqlite3_free(res.z);
   118887   }else{
   118888     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
   118889   }
   118890 }
   118891 
   118892 
   118893 typedef struct TermOffset TermOffset;
   118894 typedef struct TermOffsetCtx TermOffsetCtx;
   118895 
   118896 struct TermOffset {
   118897   char *pList;                    /* Position-list */
   118898   int iPos;                       /* Position just read from pList */
   118899   int iOff;                       /* Offset of this term from read positions */
   118900 };
   118901 
   118902 struct TermOffsetCtx {
   118903   int iCol;                       /* Column of table to populate aTerm for */
   118904   int iTerm;
   118905   sqlite3_int64 iDocid;
   118906   TermOffset *aTerm;
   118907 };
   118908 
   118909 /*
   118910 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
   118911 */
   118912 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
   118913   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
   118914   int nTerm;                      /* Number of tokens in phrase */
   118915   int iTerm;                      /* For looping through nTerm phrase terms */
   118916   char *pList;                    /* Pointer to position list for phrase */
   118917   int iPos = 0;                   /* First position in position-list */
   118918 
   118919   UNUSED_PARAMETER(iPhrase);
   118920   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
   118921   nTerm = pExpr->pPhrase->nToken;
   118922   if( pList ){
   118923     fts3GetDeltaPosition(&pList, &iPos);
   118924     assert( iPos>=0 );
   118925   }
   118926 
   118927   for(iTerm=0; iTerm<nTerm; iTerm++){
   118928     TermOffset *pT = &p->aTerm[p->iTerm++];
   118929     pT->iOff = nTerm-iTerm-1;
   118930     pT->pList = pList;
   118931     pT->iPos = iPos;
   118932   }
   118933 
   118934   return SQLITE_OK;
   118935 }
   118936 
   118937 /*
   118938 ** Implementation of offsets() function.
   118939 */
   118940 SQLITE_PRIVATE void sqlite3Fts3Offsets(
   118941   sqlite3_context *pCtx,          /* SQLite function call context */
   118942   Fts3Cursor *pCsr                /* Cursor object */
   118943 ){
   118944   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   118945   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
   118946   const char *ZDUMMY;             /* Dummy argument used with xNext() */
   118947   int NDUMMY;                     /* Dummy argument used with xNext() */
   118948   int rc;                         /* Return Code */
   118949   int nToken;                     /* Number of tokens in query */
   118950   int iCol;                       /* Column currently being processed */
   118951   StrBuffer res = {0, 0, 0};      /* Result string */
   118952   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
   118953 
   118954   if( !pCsr->pExpr ){
   118955     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
   118956     return;
   118957   }
   118958 
   118959   memset(&sCtx, 0, sizeof(sCtx));
   118960   assert( pCsr->isRequireSeek==0 );
   118961 
   118962   /* Count the number of terms in the query */
   118963   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
   118964   if( rc!=SQLITE_OK ) goto offsets_out;
   118965 
   118966   /* Allocate the array of TermOffset iterators. */
   118967   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
   118968   if( 0==sCtx.aTerm ){
   118969     rc = SQLITE_NOMEM;
   118970     goto offsets_out;
   118971   }
   118972   sCtx.iDocid = pCsr->iPrevId;
   118973 
   118974   /* Loop through the table columns, appending offset information to
   118975   ** string-buffer res for each column.
   118976   */
   118977   for(iCol=0; iCol<pTab->nColumn; iCol++){
   118978     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
   118979     int iStart;
   118980     int iEnd;
   118981     int iCurrent;
   118982     const char *zDoc;
   118983     int nDoc;
   118984 
   118985     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
   118986     ** no way that this operation can fail, so the return code from
   118987     ** fts3ExprIterate() can be discarded.
   118988     */
   118989     sCtx.iCol = iCol;
   118990     sCtx.iTerm = 0;
   118991     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
   118992 
   118993     /* Retreive the text stored in column iCol. If an SQL NULL is stored
   118994     ** in column iCol, jump immediately to the next iteration of the loop.
   118995     ** If an OOM occurs while retrieving the data (this can happen if SQLite
   118996     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
   118997     ** to the caller.
   118998     */
   118999     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
   119000     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
   119001     if( zDoc==0 ){
   119002       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
   119003         continue;
   119004       }
   119005       rc = SQLITE_NOMEM;
   119006       goto offsets_out;
   119007     }
   119008 
   119009     /* Initialize a tokenizer iterator to iterate through column iCol. */
   119010     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
   119011     if( rc!=SQLITE_OK ) goto offsets_out;
   119012     pC->pTokenizer = pTab->pTokenizer;
   119013 
   119014     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   119015     while( rc==SQLITE_OK ){
   119016       int i;                      /* Used to loop through terms */
   119017       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
   119018       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
   119019 
   119020       for(i=0; i<nToken; i++){
   119021         TermOffset *pT = &sCtx.aTerm[i];
   119022         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
   119023           iMinPos = pT->iPos-pT->iOff;
   119024           pTerm = pT;
   119025         }
   119026       }
   119027 
   119028       if( !pTerm ){
   119029         /* All offsets for this column have been gathered. */
   119030         break;
   119031       }else{
   119032         assert( iCurrent<=iMinPos );
   119033         if( 0==(0xFE&*pTerm->pList) ){
   119034           pTerm->pList = 0;
   119035         }else{
   119036           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
   119037         }
   119038         while( rc==SQLITE_OK && iCurrent<iMinPos ){
   119039           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
   119040         }
   119041         if( rc==SQLITE_OK ){
   119042           char aBuffer[64];
   119043           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
   119044               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
   119045           );
   119046           rc = fts3StringAppend(&res, aBuffer, -1);
   119047         }else if( rc==SQLITE_DONE ){
   119048           rc = SQLITE_CORRUPT;
   119049         }
   119050       }
   119051     }
   119052     if( rc==SQLITE_DONE ){
   119053       rc = SQLITE_OK;
   119054     }
   119055 
   119056     pMod->xClose(pC);
   119057     if( rc!=SQLITE_OK ) goto offsets_out;
   119058   }
   119059 
   119060  offsets_out:
   119061   sqlite3_free(sCtx.aTerm);
   119062   assert( rc!=SQLITE_DONE );
   119063   sqlite3Fts3SegmentsClose(pTab);
   119064   if( rc!=SQLITE_OK ){
   119065     sqlite3_result_error_code(pCtx,  rc);
   119066     sqlite3_free(res.z);
   119067   }else{
   119068     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
   119069   }
   119070   return;
   119071 }
   119072 
   119073 /*
   119074 ** Implementation of matchinfo() function.
   119075 */
   119076 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
   119077   sqlite3_context *pContext,      /* Function call context */
   119078   Fts3Cursor *pCsr,               /* FTS3 table cursor */
   119079   const char *zArg                /* Second arg to matchinfo() function */
   119080 ){
   119081   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
   119082   int rc;
   119083   int i;
   119084   const char *zFormat;
   119085 
   119086   if( zArg ){
   119087     for(i=0; zArg[i]; i++){
   119088       char *zErr = 0;
   119089       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
   119090         sqlite3_result_error(pContext, zErr, -1);
   119091         sqlite3_free(zErr);
   119092         return;
   119093       }
   119094     }
   119095     zFormat = zArg;
   119096   }else{
   119097     zFormat = FTS3_MATCHINFO_DEFAULT;
   119098   }
   119099 
   119100   if( !pCsr->pExpr ){
   119101     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
   119102     return;
   119103   }
   119104 
   119105   /* Retrieve matchinfo() data. */
   119106   rc = fts3GetMatchinfo(pCsr, zFormat);
   119107   sqlite3Fts3SegmentsClose(pTab);
   119108 
   119109   if( rc!=SQLITE_OK ){
   119110     sqlite3_result_error_code(pContext, rc);
   119111   }else{
   119112     int n = pCsr->nMatchinfo * sizeof(u32);
   119113     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
   119114   }
   119115 }
   119116 
   119117 #endif
   119118 
   119119 /************** End of fts3_snippet.c ****************************************/
   119120 /************** Begin file rtree.c *******************************************/
   119121 /*
   119122 ** 2001 September 15
   119123 **
   119124 ** The author disclaims copyright to this source code.  In place of
   119125 ** a legal notice, here is a blessing:
   119126 **
   119127 **    May you do good and not evil.
   119128 **    May you find forgiveness for yourself and forgive others.
   119129 **    May you share freely, never taking more than you give.
   119130 **
   119131 *************************************************************************
   119132 ** This file contains code for implementations of the r-tree and r*-tree
   119133 ** algorithms packaged as an SQLite virtual table module.
   119134 */
   119135 
   119136 /*
   119137 ** Database Format of R-Tree Tables
   119138 ** --------------------------------
   119139 **
   119140 ** The data structure for a single virtual r-tree table is stored in three
   119141 ** native SQLite tables declared as follows. In each case, the '%' character
   119142 ** in the table name is replaced with the user-supplied name of the r-tree
   119143 ** table.
   119144 **
   119145 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
   119146 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
   119147 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
   119148 **
   119149 ** The data for each node of the r-tree structure is stored in the %_node
   119150 ** table. For each node that is not the root node of the r-tree, there is
   119151 ** an entry in the %_parent table associating the node with its parent.
   119152 ** And for each row of data in the table, there is an entry in the %_rowid
   119153 ** table that maps from the entries rowid to the id of the node that it
   119154 ** is stored on.
   119155 **
   119156 ** The root node of an r-tree always exists, even if the r-tree table is
   119157 ** empty. The nodeno of the root node is always 1. All other nodes in the
   119158 ** table must be the same size as the root node. The content of each node
   119159 ** is formatted as follows:
   119160 **
   119161 **   1. If the node is the root node (node 1), then the first 2 bytes
   119162 **      of the node contain the tree depth as a big-endian integer.
   119163 **      For non-root nodes, the first 2 bytes are left unused.
   119164 **
   119165 **   2. The next 2 bytes contain the number of entries currently
   119166 **      stored in the node.
   119167 **
   119168 **   3. The remainder of the node contains the node entries. Each entry
   119169 **      consists of a single 8-byte integer followed by an even number
   119170 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
   119171 **      of a record. For internal nodes it is the node number of a
   119172 **      child page.
   119173 */
   119174 
   119175 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
   119176 
   119177 /*
   119178 ** This file contains an implementation of a couple of different variants
   119179 ** of the r-tree algorithm. See the README file for further details. The
   119180 ** same data-structure is used for all, but the algorithms for insert and
   119181 ** delete operations vary. The variants used are selected at compile time
   119182 ** by defining the following symbols:
   119183 */
   119184 
   119185 /* Either, both or none of the following may be set to activate
   119186 ** r*tree variant algorithms.
   119187 */
   119188 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
   119189 #define VARIANT_RSTARTREE_REINSERT      1
   119190 
   119191 /*
   119192 ** Exactly one of the following must be set to 1.
   119193 */
   119194 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
   119195 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
   119196 #define VARIANT_RSTARTREE_SPLIT         1
   119197 
   119198 #define VARIANT_GUTTMAN_SPLIT \
   119199         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
   119200 
   119201 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   119202   #define PickNext QuadraticPickNext
   119203   #define PickSeeds QuadraticPickSeeds
   119204   #define AssignCells splitNodeGuttman
   119205 #endif
   119206 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   119207   #define PickNext LinearPickNext
   119208   #define PickSeeds LinearPickSeeds
   119209   #define AssignCells splitNodeGuttman
   119210 #endif
   119211 #if VARIANT_RSTARTREE_SPLIT
   119212   #define AssignCells splitNodeStartree
   119213 #endif
   119214 
   119215 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
   119216 # define NDEBUG 1
   119217 #endif
   119218 
   119219 #ifndef SQLITE_CORE
   119220   SQLITE_EXTENSION_INIT1
   119221 #else
   119222 #endif
   119223 
   119224 
   119225 #ifndef SQLITE_AMALGAMATION
   119226 #include "sqlite3rtree.h"
   119227 typedef sqlite3_int64 i64;
   119228 typedef unsigned char u8;
   119229 typedef unsigned int u32;
   119230 #endif
   119231 
   119232 /*  The following macro is used to suppress compiler warnings.
   119233 */
   119234 #ifndef UNUSED_PARAMETER
   119235 # define UNUSED_PARAMETER(x) (void)(x)
   119236 #endif
   119237 
   119238 typedef struct Rtree Rtree;
   119239 typedef struct RtreeCursor RtreeCursor;
   119240 typedef struct RtreeNode RtreeNode;
   119241 typedef struct RtreeCell RtreeCell;
   119242 typedef struct RtreeConstraint RtreeConstraint;
   119243 typedef struct RtreeMatchArg RtreeMatchArg;
   119244 typedef struct RtreeGeomCallback RtreeGeomCallback;
   119245 typedef union RtreeCoord RtreeCoord;
   119246 
   119247 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
   119248 #define RTREE_MAX_DIMENSIONS 5
   119249 
   119250 /* Size of hash table Rtree.aHash. This hash table is not expected to
   119251 ** ever contain very many entries, so a fixed number of buckets is
   119252 ** used.
   119253 */
   119254 #define HASHSIZE 128
   119255 
   119256 /*
   119257 ** An rtree virtual-table object.
   119258 */
   119259 struct Rtree {
   119260   sqlite3_vtab base;
   119261   sqlite3 *db;                /* Host database connection */
   119262   int iNodeSize;              /* Size in bytes of each node in the node table */
   119263   int nDim;                   /* Number of dimensions */
   119264   int nBytesPerCell;          /* Bytes consumed per cell */
   119265   int iDepth;                 /* Current depth of the r-tree structure */
   119266   char *zDb;                  /* Name of database containing r-tree table */
   119267   char *zName;                /* Name of r-tree table */
   119268   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
   119269   int nBusy;                  /* Current number of users of this structure */
   119270 
   119271   /* List of nodes removed during a CondenseTree operation. List is
   119272   ** linked together via the pointer normally used for hash chains -
   119273   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   119274   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   119275   */
   119276   RtreeNode *pDeleted;
   119277   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
   119278 
   119279   /* Statements to read/write/delete a record from xxx_node */
   119280   sqlite3_stmt *pReadNode;
   119281   sqlite3_stmt *pWriteNode;
   119282   sqlite3_stmt *pDeleteNode;
   119283 
   119284   /* Statements to read/write/delete a record from xxx_rowid */
   119285   sqlite3_stmt *pReadRowid;
   119286   sqlite3_stmt *pWriteRowid;
   119287   sqlite3_stmt *pDeleteRowid;
   119288 
   119289   /* Statements to read/write/delete a record from xxx_parent */
   119290   sqlite3_stmt *pReadParent;
   119291   sqlite3_stmt *pWriteParent;
   119292   sqlite3_stmt *pDeleteParent;
   119293 
   119294   int eCoordType;
   119295 };
   119296 
   119297 /* Possible values for eCoordType: */
   119298 #define RTREE_COORD_REAL32 0
   119299 #define RTREE_COORD_INT32  1
   119300 
   119301 /*
   119302 ** The minimum number of cells allowed for a node is a third of the
   119303 ** maximum. In Gutman's notation:
   119304 **
   119305 **     m = M/3
   119306 **
   119307 ** If an R*-tree "Reinsert" operation is required, the same number of
   119308 ** cells are removed from the overfull node and reinserted into the tree.
   119309 */
   119310 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
   119311 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
   119312 #define RTREE_MAXCELLS 51
   119313 
   119314 /*
   119315 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
   119316 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
   119317 ** Therefore all non-root nodes must contain at least 3 entries. Since
   119318 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
   119319 ** 40 or less.
   119320 */
   119321 #define RTREE_MAX_DEPTH 40
   119322 
   119323 /*
   119324 ** An rtree cursor object.
   119325 */
   119326 struct RtreeCursor {
   119327   sqlite3_vtab_cursor base;
   119328   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
   119329   int iCell;                        /* Index of current cell in pNode */
   119330   int iStrategy;                    /* Copy of idxNum search parameter */
   119331   int nConstraint;                  /* Number of entries in aConstraint */
   119332   RtreeConstraint *aConstraint;     /* Search constraints. */
   119333 };
   119334 
   119335 union RtreeCoord {
   119336   float f;
   119337   int i;
   119338 };
   119339 
   119340 /*
   119341 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
   119342 ** formatted as a double. This macro assumes that local variable pRtree points
   119343 ** to the Rtree structure associated with the RtreeCoord.
   119344 */
   119345 #define DCOORD(coord) (                           \
   119346   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
   119347     ((double)coord.f) :                           \
   119348     ((double)coord.i)                             \
   119349 )
   119350 
   119351 /*
   119352 ** A search constraint.
   119353 */
   119354 struct RtreeConstraint {
   119355   int iCoord;                     /* Index of constrained coordinate */
   119356   int op;                         /* Constraining operation */
   119357   double rValue;                  /* Constraint value. */
   119358   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   119359   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
   119360 };
   119361 
   119362 /* Possible values for RtreeConstraint.op */
   119363 #define RTREE_EQ    0x41
   119364 #define RTREE_LE    0x42
   119365 #define RTREE_LT    0x43
   119366 #define RTREE_GE    0x44
   119367 #define RTREE_GT    0x45
   119368 #define RTREE_MATCH 0x46
   119369 
   119370 /*
   119371 ** An rtree structure node.
   119372 */
   119373 struct RtreeNode {
   119374   RtreeNode *pParent;               /* Parent node */
   119375   i64 iNode;
   119376   int nRef;
   119377   int isDirty;
   119378   u8 *zData;
   119379   RtreeNode *pNext;                 /* Next node in this hash chain */
   119380 };
   119381 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
   119382 
   119383 /*
   119384 ** Structure to store a deserialized rtree record.
   119385 */
   119386 struct RtreeCell {
   119387   i64 iRowid;
   119388   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
   119389 };
   119390 
   119391 
   119392 /*
   119393 ** Value for the first field of every RtreeMatchArg object. The MATCH
   119394 ** operator tests that the first field of a blob operand matches this
   119395 ** value to avoid operating on invalid blobs (which could cause a segfault).
   119396 */
   119397 #define RTREE_GEOMETRY_MAGIC 0x891245AB
   119398 
   119399 /*
   119400 ** An instance of this structure must be supplied as a blob argument to
   119401 ** the right-hand-side of an SQL MATCH operator used to constrain an
   119402 ** r-tree query.
   119403 */
   119404 struct RtreeMatchArg {
   119405   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
   119406   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   119407   void *pContext;
   119408   int nParam;
   119409   double aParam[1];
   119410 };
   119411 
   119412 /*
   119413 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
   119414 ** a single instance of the following structure is allocated. It is used
   119415 ** as the context for the user-function created by by s_r_g_c(). The object
   119416 ** is eventually deleted by the destructor mechanism provided by
   119417 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
   119418 ** the geometry callback function).
   119419 */
   119420 struct RtreeGeomCallback {
   119421   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
   119422   void *pContext;
   119423 };
   119424 
   119425 #ifndef MAX
   119426 # define MAX(x,y) ((x) < (y) ? (y) : (x))
   119427 #endif
   119428 #ifndef MIN
   119429 # define MIN(x,y) ((x) > (y) ? (y) : (x))
   119430 #endif
   119431 
   119432 /*
   119433 ** Functions to deserialize a 16 bit integer, 32 bit real number and
   119434 ** 64 bit integer. The deserialized value is returned.
   119435 */
   119436 static int readInt16(u8 *p){
   119437   return (p[0]<<8) + p[1];
   119438 }
   119439 static void readCoord(u8 *p, RtreeCoord *pCoord){
   119440   u32 i = (
   119441     (((u32)p[0]) << 24) +
   119442     (((u32)p[1]) << 16) +
   119443     (((u32)p[2]) <<  8) +
   119444     (((u32)p[3]) <<  0)
   119445   );
   119446   *(u32 *)pCoord = i;
   119447 }
   119448 static i64 readInt64(u8 *p){
   119449   return (
   119450     (((i64)p[0]) << 56) +
   119451     (((i64)p[1]) << 48) +
   119452     (((i64)p[2]) << 40) +
   119453     (((i64)p[3]) << 32) +
   119454     (((i64)p[4]) << 24) +
   119455     (((i64)p[5]) << 16) +
   119456     (((i64)p[6]) <<  8) +
   119457     (((i64)p[7]) <<  0)
   119458   );
   119459 }
   119460 
   119461 /*
   119462 ** Functions to serialize a 16 bit integer, 32 bit real number and
   119463 ** 64 bit integer. The value returned is the number of bytes written
   119464 ** to the argument buffer (always 2, 4 and 8 respectively).
   119465 */
   119466 static int writeInt16(u8 *p, int i){
   119467   p[0] = (i>> 8)&0xFF;
   119468   p[1] = (i>> 0)&0xFF;
   119469   return 2;
   119470 }
   119471 static int writeCoord(u8 *p, RtreeCoord *pCoord){
   119472   u32 i;
   119473   assert( sizeof(RtreeCoord)==4 );
   119474   assert( sizeof(u32)==4 );
   119475   i = *(u32 *)pCoord;
   119476   p[0] = (i>>24)&0xFF;
   119477   p[1] = (i>>16)&0xFF;
   119478   p[2] = (i>> 8)&0xFF;
   119479   p[3] = (i>> 0)&0xFF;
   119480   return 4;
   119481 }
   119482 static int writeInt64(u8 *p, i64 i){
   119483   p[0] = (i>>56)&0xFF;
   119484   p[1] = (i>>48)&0xFF;
   119485   p[2] = (i>>40)&0xFF;
   119486   p[3] = (i>>32)&0xFF;
   119487   p[4] = (i>>24)&0xFF;
   119488   p[5] = (i>>16)&0xFF;
   119489   p[6] = (i>> 8)&0xFF;
   119490   p[7] = (i>> 0)&0xFF;
   119491   return 8;
   119492 }
   119493 
   119494 /*
   119495 ** Increment the reference count of node p.
   119496 */
   119497 static void nodeReference(RtreeNode *p){
   119498   if( p ){
   119499     p->nRef++;
   119500   }
   119501 }
   119502 
   119503 /*
   119504 ** Clear the content of node p (set all bytes to 0x00).
   119505 */
   119506 static void nodeZero(Rtree *pRtree, RtreeNode *p){
   119507   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
   119508   p->isDirty = 1;
   119509 }
   119510 
   119511 /*
   119512 ** Given a node number iNode, return the corresponding key to use
   119513 ** in the Rtree.aHash table.
   119514 */
   119515 static int nodeHash(i64 iNode){
   119516   return (
   119517     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
   119518     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
   119519   ) % HASHSIZE;
   119520 }
   119521 
   119522 /*
   119523 ** Search the node hash table for node iNode. If found, return a pointer
   119524 ** to it. Otherwise, return 0.
   119525 */
   119526 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
   119527   RtreeNode *p;
   119528   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
   119529   return p;
   119530 }
   119531 
   119532 /*
   119533 ** Add node pNode to the node hash table.
   119534 */
   119535 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
   119536   int iHash;
   119537   assert( pNode->pNext==0 );
   119538   iHash = nodeHash(pNode->iNode);
   119539   pNode->pNext = pRtree->aHash[iHash];
   119540   pRtree->aHash[iHash] = pNode;
   119541 }
   119542 
   119543 /*
   119544 ** Remove node pNode from the node hash table.
   119545 */
   119546 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
   119547   RtreeNode **pp;
   119548   if( pNode->iNode!=0 ){
   119549     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
   119550     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
   119551     *pp = pNode->pNext;
   119552     pNode->pNext = 0;
   119553   }
   119554 }
   119555 
   119556 /*
   119557 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
   119558 ** indicating that node has not yet been assigned a node number. It is
   119559 ** assigned a node number when nodeWrite() is called to write the
   119560 ** node contents out to the database.
   119561 */
   119562 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
   119563   RtreeNode *pNode;
   119564   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
   119565   if( pNode ){
   119566     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
   119567     pNode->zData = (u8 *)&pNode[1];
   119568     pNode->nRef = 1;
   119569     pNode->pParent = pParent;
   119570     pNode->isDirty = 1;
   119571     nodeReference(pParent);
   119572   }
   119573   return pNode;
   119574 }
   119575 
   119576 /*
   119577 ** Obtain a reference to an r-tree node.
   119578 */
   119579 static int
   119580 nodeAcquire(
   119581   Rtree *pRtree,             /* R-tree structure */
   119582   i64 iNode,                 /* Node number to load */
   119583   RtreeNode *pParent,        /* Either the parent node or NULL */
   119584   RtreeNode **ppNode         /* OUT: Acquired node */
   119585 ){
   119586   int rc;
   119587   int rc2 = SQLITE_OK;
   119588   RtreeNode *pNode;
   119589 
   119590   /* Check if the requested node is already in the hash table. If so,
   119591   ** increase its reference count and return it.
   119592   */
   119593   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
   119594     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
   119595     if( pParent && !pNode->pParent ){
   119596       nodeReference(pParent);
   119597       pNode->pParent = pParent;
   119598     }
   119599     pNode->nRef++;
   119600     *ppNode = pNode;
   119601     return SQLITE_OK;
   119602   }
   119603 
   119604   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
   119605   rc = sqlite3_step(pRtree->pReadNode);
   119606   if( rc==SQLITE_ROW ){
   119607     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
   119608     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
   119609       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
   119610       if( !pNode ){
   119611         rc2 = SQLITE_NOMEM;
   119612       }else{
   119613         pNode->pParent = pParent;
   119614         pNode->zData = (u8 *)&pNode[1];
   119615         pNode->nRef = 1;
   119616         pNode->iNode = iNode;
   119617         pNode->isDirty = 0;
   119618         pNode->pNext = 0;
   119619         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
   119620         nodeReference(pParent);
   119621       }
   119622     }
   119623   }
   119624   rc = sqlite3_reset(pRtree->pReadNode);
   119625   if( rc==SQLITE_OK ) rc = rc2;
   119626 
   119627   /* If the root node was just loaded, set pRtree->iDepth to the height
   119628   ** of the r-tree structure. A height of zero means all data is stored on
   119629   ** the root node. A height of one means the children of the root node
   119630   ** are the leaves, and so on. If the depth as specified on the root node
   119631   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   119632   */
   119633   if( pNode && iNode==1 ){
   119634     pRtree->iDepth = readInt16(pNode->zData);
   119635     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
   119636       rc = SQLITE_CORRUPT;
   119637     }
   119638   }
   119639 
   119640   /* If no error has occurred so far, check if the "number of entries"
   119641   ** field on the node is too large. If so, set the return code to
   119642   ** SQLITE_CORRUPT.
   119643   */
   119644   if( pNode && rc==SQLITE_OK ){
   119645     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
   119646       rc = SQLITE_CORRUPT;
   119647     }
   119648   }
   119649 
   119650   if( rc==SQLITE_OK ){
   119651     if( pNode!=0 ){
   119652       nodeHashInsert(pRtree, pNode);
   119653     }else{
   119654       rc = SQLITE_CORRUPT;
   119655     }
   119656     *ppNode = pNode;
   119657   }else{
   119658     sqlite3_free(pNode);
   119659     *ppNode = 0;
   119660   }
   119661 
   119662   return rc;
   119663 }
   119664 
   119665 /*
   119666 ** Overwrite cell iCell of node pNode with the contents of pCell.
   119667 */
   119668 static void nodeOverwriteCell(
   119669   Rtree *pRtree,
   119670   RtreeNode *pNode,
   119671   RtreeCell *pCell,
   119672   int iCell
   119673 ){
   119674   int ii;
   119675   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   119676   p += writeInt64(p, pCell->iRowid);
   119677   for(ii=0; ii<(pRtree->nDim*2); ii++){
   119678     p += writeCoord(p, &pCell->aCoord[ii]);
   119679   }
   119680   pNode->isDirty = 1;
   119681 }
   119682 
   119683 /*
   119684 ** Remove cell the cell with index iCell from node pNode.
   119685 */
   119686 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
   119687   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
   119688   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
   119689   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
   119690   memmove(pDst, pSrc, nByte);
   119691   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
   119692   pNode->isDirty = 1;
   119693 }
   119694 
   119695 /*
   119696 ** Insert the contents of cell pCell into node pNode. If the insert
   119697 ** is successful, return SQLITE_OK.
   119698 **
   119699 ** If there is not enough free space in pNode, return SQLITE_FULL.
   119700 */
   119701 static int
   119702 nodeInsertCell(
   119703   Rtree *pRtree,
   119704   RtreeNode *pNode,
   119705   RtreeCell *pCell
   119706 ){
   119707   int nCell;                    /* Current number of cells in pNode */
   119708   int nMaxCell;                 /* Maximum number of cells for pNode */
   119709 
   119710   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
   119711   nCell = NCELL(pNode);
   119712 
   119713   assert( nCell<=nMaxCell );
   119714   if( nCell<nMaxCell ){
   119715     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
   119716     writeInt16(&pNode->zData[2], nCell+1);
   119717     pNode->isDirty = 1;
   119718   }
   119719 
   119720   return (nCell==nMaxCell);
   119721 }
   119722 
   119723 /*
   119724 ** If the node is dirty, write it out to the database.
   119725 */
   119726 static int
   119727 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
   119728   int rc = SQLITE_OK;
   119729   if( pNode->isDirty ){
   119730     sqlite3_stmt *p = pRtree->pWriteNode;
   119731     if( pNode->iNode ){
   119732       sqlite3_bind_int64(p, 1, pNode->iNode);
   119733     }else{
   119734       sqlite3_bind_null(p, 1);
   119735     }
   119736     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
   119737     sqlite3_step(p);
   119738     pNode->isDirty = 0;
   119739     rc = sqlite3_reset(p);
   119740     if( pNode->iNode==0 && rc==SQLITE_OK ){
   119741       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
   119742       nodeHashInsert(pRtree, pNode);
   119743     }
   119744   }
   119745   return rc;
   119746 }
   119747 
   119748 /*
   119749 ** Release a reference to a node. If the node is dirty and the reference
   119750 ** count drops to zero, the node data is written to the database.
   119751 */
   119752 static int
   119753 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
   119754   int rc = SQLITE_OK;
   119755   if( pNode ){
   119756     assert( pNode->nRef>0 );
   119757     pNode->nRef--;
   119758     if( pNode->nRef==0 ){
   119759       if( pNode->iNode==1 ){
   119760         pRtree->iDepth = -1;
   119761       }
   119762       if( pNode->pParent ){
   119763         rc = nodeRelease(pRtree, pNode->pParent);
   119764       }
   119765       if( rc==SQLITE_OK ){
   119766         rc = nodeWrite(pRtree, pNode);
   119767       }
   119768       nodeHashDelete(pRtree, pNode);
   119769       sqlite3_free(pNode);
   119770     }
   119771   }
   119772   return rc;
   119773 }
   119774 
   119775 /*
   119776 ** Return the 64-bit integer value associated with cell iCell of
   119777 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
   119778 ** an internal node, then the 64-bit integer is a child page number.
   119779 */
   119780 static i64 nodeGetRowid(
   119781   Rtree *pRtree,
   119782   RtreeNode *pNode,
   119783   int iCell
   119784 ){
   119785   assert( iCell<NCELL(pNode) );
   119786   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
   119787 }
   119788 
   119789 /*
   119790 ** Return coordinate iCoord from cell iCell in node pNode.
   119791 */
   119792 static void nodeGetCoord(
   119793   Rtree *pRtree,
   119794   RtreeNode *pNode,
   119795   int iCell,
   119796   int iCoord,
   119797   RtreeCoord *pCoord           /* Space to write result to */
   119798 ){
   119799   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
   119800 }
   119801 
   119802 /*
   119803 ** Deserialize cell iCell of node pNode. Populate the structure pointed
   119804 ** to by pCell with the results.
   119805 */
   119806 static void nodeGetCell(
   119807   Rtree *pRtree,
   119808   RtreeNode *pNode,
   119809   int iCell,
   119810   RtreeCell *pCell
   119811 ){
   119812   int ii;
   119813   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
   119814   for(ii=0; ii<pRtree->nDim*2; ii++){
   119815     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
   119816   }
   119817 }
   119818 
   119819 
   119820 /* Forward declaration for the function that does the work of
   119821 ** the virtual table module xCreate() and xConnect() methods.
   119822 */
   119823 static int rtreeInit(
   119824   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
   119825 );
   119826 
   119827 /*
   119828 ** Rtree virtual table module xCreate method.
   119829 */
   119830 static int rtreeCreate(
   119831   sqlite3 *db,
   119832   void *pAux,
   119833   int argc, const char *const*argv,
   119834   sqlite3_vtab **ppVtab,
   119835   char **pzErr
   119836 ){
   119837   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
   119838 }
   119839 
   119840 /*
   119841 ** Rtree virtual table module xConnect method.
   119842 */
   119843 static int rtreeConnect(
   119844   sqlite3 *db,
   119845   void *pAux,
   119846   int argc, const char *const*argv,
   119847   sqlite3_vtab **ppVtab,
   119848   char **pzErr
   119849 ){
   119850   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
   119851 }
   119852 
   119853 /*
   119854 ** Increment the r-tree reference count.
   119855 */
   119856 static void rtreeReference(Rtree *pRtree){
   119857   pRtree->nBusy++;
   119858 }
   119859 
   119860 /*
   119861 ** Decrement the r-tree reference count. When the reference count reaches
   119862 ** zero the structure is deleted.
   119863 */
   119864 static void rtreeRelease(Rtree *pRtree){
   119865   pRtree->nBusy--;
   119866   if( pRtree->nBusy==0 ){
   119867     sqlite3_finalize(pRtree->pReadNode);
   119868     sqlite3_finalize(pRtree->pWriteNode);
   119869     sqlite3_finalize(pRtree->pDeleteNode);
   119870     sqlite3_finalize(pRtree->pReadRowid);
   119871     sqlite3_finalize(pRtree->pWriteRowid);
   119872     sqlite3_finalize(pRtree->pDeleteRowid);
   119873     sqlite3_finalize(pRtree->pReadParent);
   119874     sqlite3_finalize(pRtree->pWriteParent);
   119875     sqlite3_finalize(pRtree->pDeleteParent);
   119876     sqlite3_free(pRtree);
   119877   }
   119878 }
   119879 
   119880 /*
   119881 ** Rtree virtual table module xDisconnect method.
   119882 */
   119883 static int rtreeDisconnect(sqlite3_vtab *pVtab){
   119884   rtreeRelease((Rtree *)pVtab);
   119885   return SQLITE_OK;
   119886 }
   119887 
   119888 /*
   119889 ** Rtree virtual table module xDestroy method.
   119890 */
   119891 static int rtreeDestroy(sqlite3_vtab *pVtab){
   119892   Rtree *pRtree = (Rtree *)pVtab;
   119893   int rc;
   119894   char *zCreate = sqlite3_mprintf(
   119895     "DROP TABLE '%q'.'%q_node';"
   119896     "DROP TABLE '%q'.'%q_rowid';"
   119897     "DROP TABLE '%q'.'%q_parent';",
   119898     pRtree->zDb, pRtree->zName,
   119899     pRtree->zDb, pRtree->zName,
   119900     pRtree->zDb, pRtree->zName
   119901   );
   119902   if( !zCreate ){
   119903     rc = SQLITE_NOMEM;
   119904   }else{
   119905     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
   119906     sqlite3_free(zCreate);
   119907   }
   119908   if( rc==SQLITE_OK ){
   119909     rtreeRelease(pRtree);
   119910   }
   119911 
   119912   return rc;
   119913 }
   119914 
   119915 /*
   119916 ** Rtree virtual table module xOpen method.
   119917 */
   119918 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   119919   int rc = SQLITE_NOMEM;
   119920   RtreeCursor *pCsr;
   119921 
   119922   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
   119923   if( pCsr ){
   119924     memset(pCsr, 0, sizeof(RtreeCursor));
   119925     pCsr->base.pVtab = pVTab;
   119926     rc = SQLITE_OK;
   119927   }
   119928   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
   119929 
   119930   return rc;
   119931 }
   119932 
   119933 
   119934 /*
   119935 ** Free the RtreeCursor.aConstraint[] array and its contents.
   119936 */
   119937 static void freeCursorConstraints(RtreeCursor *pCsr){
   119938   if( pCsr->aConstraint ){
   119939     int i;                        /* Used to iterate through constraint array */
   119940     for(i=0; i<pCsr->nConstraint; i++){
   119941       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
   119942       if( pGeom ){
   119943         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
   119944         sqlite3_free(pGeom);
   119945       }
   119946     }
   119947     sqlite3_free(pCsr->aConstraint);
   119948     pCsr->aConstraint = 0;
   119949   }
   119950 }
   119951 
   119952 /*
   119953 ** Rtree virtual table module xClose method.
   119954 */
   119955 static int rtreeClose(sqlite3_vtab_cursor *cur){
   119956   Rtree *pRtree = (Rtree *)(cur->pVtab);
   119957   int rc;
   119958   RtreeCursor *pCsr = (RtreeCursor *)cur;
   119959   freeCursorConstraints(pCsr);
   119960   rc = nodeRelease(pRtree, pCsr->pNode);
   119961   sqlite3_free(pCsr);
   119962   return rc;
   119963 }
   119964 
   119965 /*
   119966 ** Rtree virtual table module xEof method.
   119967 **
   119968 ** Return non-zero if the cursor does not currently point to a valid
   119969 ** record (i.e if the scan has finished), or zero otherwise.
   119970 */
   119971 static int rtreeEof(sqlite3_vtab_cursor *cur){
   119972   RtreeCursor *pCsr = (RtreeCursor *)cur;
   119973   return (pCsr->pNode==0);
   119974 }
   119975 
   119976 /*
   119977 ** The r-tree constraint passed as the second argument to this function is
   119978 ** guaranteed to be a MATCH constraint.
   119979 */
   119980 static int testRtreeGeom(
   119981   Rtree *pRtree,                  /* R-Tree object */
   119982   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
   119983   RtreeCell *pCell,               /* Cell to test */
   119984   int *pbRes                      /* OUT: Test result */
   119985 ){
   119986   int i;
   119987   double aCoord[RTREE_MAX_DIMENSIONS*2];
   119988   int nCoord = pRtree->nDim*2;
   119989 
   119990   assert( pConstraint->op==RTREE_MATCH );
   119991   assert( pConstraint->pGeom );
   119992 
   119993   for(i=0; i<nCoord; i++){
   119994     aCoord[i] = DCOORD(pCell->aCoord[i]);
   119995   }
   119996   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
   119997 }
   119998 
   119999 /*
   120000 ** Cursor pCursor currently points to a cell in a non-leaf page.
   120001 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
   120002 ** (excluded) by the constraints in the pCursor->aConstraint[]
   120003 ** array, or false otherwise.
   120004 **
   120005 ** Return SQLITE_OK if successful or an SQLite error code if an error
   120006 ** occurs within a geometry callback.
   120007 */
   120008 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   120009   RtreeCell cell;
   120010   int ii;
   120011   int bRes = 0;
   120012   int rc = SQLITE_OK;
   120013 
   120014   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   120015   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
   120016     RtreeConstraint *p = &pCursor->aConstraint[ii];
   120017     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
   120018     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
   120019 
   120020     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   120021         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   120022     );
   120023 
   120024     switch( p->op ){
   120025       case RTREE_LE: case RTREE_LT:
   120026         bRes = p->rValue<cell_min;
   120027         break;
   120028 
   120029       case RTREE_GE: case RTREE_GT:
   120030         bRes = p->rValue>cell_max;
   120031         break;
   120032 
   120033       case RTREE_EQ:
   120034         bRes = (p->rValue>cell_max || p->rValue<cell_min);
   120035         break;
   120036 
   120037       default: {
   120038         assert( p->op==RTREE_MATCH );
   120039         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
   120040         bRes = !bRes;
   120041         break;
   120042       }
   120043     }
   120044   }
   120045 
   120046   *pbEof = bRes;
   120047   return rc;
   120048 }
   120049 
   120050 /*
   120051 ** Test if the cell that cursor pCursor currently points to
   120052 ** would be filtered (excluded) by the constraints in the
   120053 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
   120054 ** returning. If the cell is not filtered (excluded) by the constraints,
   120055 ** set pbEof to zero.
   120056 **
   120057 ** Return SQLITE_OK if successful or an SQLite error code if an error
   120058 ** occurs within a geometry callback.
   120059 **
   120060 ** This function assumes that the cell is part of a leaf node.
   120061 */
   120062 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
   120063   RtreeCell cell;
   120064   int ii;
   120065   *pbEof = 0;
   120066 
   120067   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
   120068   for(ii=0; ii<pCursor->nConstraint; ii++){
   120069     RtreeConstraint *p = &pCursor->aConstraint[ii];
   120070     double coord = DCOORD(cell.aCoord[p->iCoord]);
   120071     int res;
   120072     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
   120073         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
   120074     );
   120075     switch( p->op ){
   120076       case RTREE_LE: res = (coord<=p->rValue); break;
   120077       case RTREE_LT: res = (coord<p->rValue);  break;
   120078       case RTREE_GE: res = (coord>=p->rValue); break;
   120079       case RTREE_GT: res = (coord>p->rValue);  break;
   120080       case RTREE_EQ: res = (coord==p->rValue); break;
   120081       default: {
   120082         int rc;
   120083         assert( p->op==RTREE_MATCH );
   120084         rc = testRtreeGeom(pRtree, p, &cell, &res);
   120085         if( rc!=SQLITE_OK ){
   120086           return rc;
   120087         }
   120088         break;
   120089       }
   120090     }
   120091 
   120092     if( !res ){
   120093       *pbEof = 1;
   120094       return SQLITE_OK;
   120095     }
   120096   }
   120097 
   120098   return SQLITE_OK;
   120099 }
   120100 
   120101 /*
   120102 ** Cursor pCursor currently points at a node that heads a sub-tree of
   120103 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
   120104 ** to point to the left-most cell of the sub-tree that matches the
   120105 ** configured constraints.
   120106 */
   120107 static int descendToCell(
   120108   Rtree *pRtree,
   120109   RtreeCursor *pCursor,
   120110   int iHeight,
   120111   int *pEof                 /* OUT: Set to true if cannot descend */
   120112 ){
   120113   int isEof;
   120114   int rc;
   120115   int ii;
   120116   RtreeNode *pChild;
   120117   sqlite3_int64 iRowid;
   120118 
   120119   RtreeNode *pSavedNode = pCursor->pNode;
   120120   int iSavedCell = pCursor->iCell;
   120121 
   120122   assert( iHeight>=0 );
   120123 
   120124   if( iHeight==0 ){
   120125     rc = testRtreeEntry(pRtree, pCursor, &isEof);
   120126   }else{
   120127     rc = testRtreeCell(pRtree, pCursor, &isEof);
   120128   }
   120129   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
   120130     goto descend_to_cell_out;
   120131   }
   120132 
   120133   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
   120134   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
   120135   if( rc!=SQLITE_OK ){
   120136     goto descend_to_cell_out;
   120137   }
   120138 
   120139   nodeRelease(pRtree, pCursor->pNode);
   120140   pCursor->pNode = pChild;
   120141   isEof = 1;
   120142   for(ii=0; isEof && ii<NCELL(pChild); ii++){
   120143     pCursor->iCell = ii;
   120144     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
   120145     if( rc!=SQLITE_OK ){
   120146       goto descend_to_cell_out;
   120147     }
   120148   }
   120149 
   120150   if( isEof ){
   120151     assert( pCursor->pNode==pChild );
   120152     nodeReference(pSavedNode);
   120153     nodeRelease(pRtree, pChild);
   120154     pCursor->pNode = pSavedNode;
   120155     pCursor->iCell = iSavedCell;
   120156   }
   120157 
   120158 descend_to_cell_out:
   120159   *pEof = isEof;
   120160   return rc;
   120161 }
   120162 
   120163 /*
   120164 ** One of the cells in node pNode is guaranteed to have a 64-bit
   120165 ** integer value equal to iRowid. Return the index of this cell.
   120166 */
   120167 static int nodeRowidIndex(
   120168   Rtree *pRtree,
   120169   RtreeNode *pNode,
   120170   i64 iRowid,
   120171   int *piIndex
   120172 ){
   120173   int ii;
   120174   int nCell = NCELL(pNode);
   120175   for(ii=0; ii<nCell; ii++){
   120176     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
   120177       *piIndex = ii;
   120178       return SQLITE_OK;
   120179     }
   120180   }
   120181   return SQLITE_CORRUPT;
   120182 }
   120183 
   120184 /*
   120185 ** Return the index of the cell containing a pointer to node pNode
   120186 ** in its parent. If pNode is the root node, return -1.
   120187 */
   120188 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
   120189   RtreeNode *pParent = pNode->pParent;
   120190   if( pParent ){
   120191     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
   120192   }
   120193   *piIndex = -1;
   120194   return SQLITE_OK;
   120195 }
   120196 
   120197 /*
   120198 ** Rtree virtual table module xNext method.
   120199 */
   120200 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   120201   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
   120202   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   120203   int rc = SQLITE_OK;
   120204 
   120205   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
   120206   ** already at EOF. It is against the rules to call the xNext() method of
   120207   ** a cursor that has already reached EOF.
   120208   */
   120209   assert( pCsr->pNode );
   120210 
   120211   if( pCsr->iStrategy==1 ){
   120212     /* This "scan" is a direct lookup by rowid. There is no next entry. */
   120213     nodeRelease(pRtree, pCsr->pNode);
   120214     pCsr->pNode = 0;
   120215   }else{
   120216     /* Move to the next entry that matches the configured constraints. */
   120217     int iHeight = 0;
   120218     while( pCsr->pNode ){
   120219       RtreeNode *pNode = pCsr->pNode;
   120220       int nCell = NCELL(pNode);
   120221       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
   120222         int isEof;
   120223         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
   120224         if( rc!=SQLITE_OK || !isEof ){
   120225           return rc;
   120226         }
   120227       }
   120228       pCsr->pNode = pNode->pParent;
   120229       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
   120230       if( rc!=SQLITE_OK ){
   120231         return rc;
   120232       }
   120233       nodeReference(pCsr->pNode);
   120234       nodeRelease(pRtree, pNode);
   120235       iHeight++;
   120236     }
   120237   }
   120238 
   120239   return rc;
   120240 }
   120241 
   120242 /*
   120243 ** Rtree virtual table module xRowid method.
   120244 */
   120245 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   120246   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   120247   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   120248 
   120249   assert(pCsr->pNode);
   120250   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   120251 
   120252   return SQLITE_OK;
   120253 }
   120254 
   120255 /*
   120256 ** Rtree virtual table module xColumn method.
   120257 */
   120258 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
   120259   Rtree *pRtree = (Rtree *)cur->pVtab;
   120260   RtreeCursor *pCsr = (RtreeCursor *)cur;
   120261 
   120262   if( i==0 ){
   120263     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
   120264     sqlite3_result_int64(ctx, iRowid);
   120265   }else{
   120266     RtreeCoord c;
   120267     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
   120268     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   120269       sqlite3_result_double(ctx, c.f);
   120270     }else{
   120271       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
   120272       sqlite3_result_int(ctx, c.i);
   120273     }
   120274   }
   120275 
   120276   return SQLITE_OK;
   120277 }
   120278 
   120279 /*
   120280 ** Use nodeAcquire() to obtain the leaf node containing the record with
   120281 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
   120282 ** return SQLITE_OK. If there is no such record in the table, set
   120283 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
   120284 ** to zero and return an SQLite error code.
   120285 */
   120286 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
   120287   int rc;
   120288   *ppLeaf = 0;
   120289   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
   120290   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
   120291     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
   120292     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
   120293     sqlite3_reset(pRtree->pReadRowid);
   120294   }else{
   120295     rc = sqlite3_reset(pRtree->pReadRowid);
   120296   }
   120297   return rc;
   120298 }
   120299 
   120300 /*
   120301 ** This function is called to configure the RtreeConstraint object passed
   120302 ** as the second argument for a MATCH constraint. The value passed as the
   120303 ** first argument to this function is the right-hand operand to the MATCH
   120304 ** operator.
   120305 */
   120306 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   120307   RtreeMatchArg *p;
   120308   sqlite3_rtree_geometry *pGeom;
   120309   int nBlob;
   120310 
   120311   /* Check that value is actually a blob. */
   120312   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
   120313 
   120314   /* Check that the blob is roughly the right size. */
   120315   nBlob = sqlite3_value_bytes(pValue);
   120316   if( nBlob<(int)sizeof(RtreeMatchArg)
   120317    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
   120318   ){
   120319     return SQLITE_ERROR;
   120320   }
   120321 
   120322   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
   120323       sizeof(sqlite3_rtree_geometry) + nBlob
   120324   );
   120325   if( !pGeom ) return SQLITE_NOMEM;
   120326   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
   120327   p = (RtreeMatchArg *)&pGeom[1];
   120328 
   120329   memcpy(p, sqlite3_value_blob(pValue), nBlob);
   120330   if( p->magic!=RTREE_GEOMETRY_MAGIC
   120331    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
   120332   ){
   120333     sqlite3_free(pGeom);
   120334     return SQLITE_ERROR;
   120335   }
   120336 
   120337   pGeom->pContext = p->pContext;
   120338   pGeom->nParam = p->nParam;
   120339   pGeom->aParam = p->aParam;
   120340 
   120341   pCons->xGeom = p->xGeom;
   120342   pCons->pGeom = pGeom;
   120343   return SQLITE_OK;
   120344 }
   120345 
   120346 /*
   120347 ** Rtree virtual table module xFilter method.
   120348 */
   120349 static int rtreeFilter(
   120350   sqlite3_vtab_cursor *pVtabCursor,
   120351   int idxNum, const char *idxStr,
   120352   int argc, sqlite3_value **argv
   120353 ){
   120354   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
   120355   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
   120356 
   120357   RtreeNode *pRoot = 0;
   120358   int ii;
   120359   int rc = SQLITE_OK;
   120360 
   120361   rtreeReference(pRtree);
   120362 
   120363   freeCursorConstraints(pCsr);
   120364   pCsr->iStrategy = idxNum;
   120365 
   120366   if( idxNum==1 ){
   120367     /* Special case - lookup by rowid. */
   120368     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
   120369     i64 iRowid = sqlite3_value_int64(argv[0]);
   120370     rc = findLeafNode(pRtree, iRowid, &pLeaf);
   120371     pCsr->pNode = pLeaf;
   120372     if( pLeaf ){
   120373       assert( rc==SQLITE_OK );
   120374       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
   120375     }
   120376   }else{
   120377     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
   120378     ** with the configured constraints.
   120379     */
   120380     if( argc>0 ){
   120381       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
   120382       pCsr->nConstraint = argc;
   120383       if( !pCsr->aConstraint ){
   120384         rc = SQLITE_NOMEM;
   120385       }else{
   120386         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
   120387         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
   120388         for(ii=0; ii<argc; ii++){
   120389           RtreeConstraint *p = &pCsr->aConstraint[ii];
   120390           p->op = idxStr[ii*2];
   120391           p->iCoord = idxStr[ii*2+1]-'a';
   120392           if( p->op==RTREE_MATCH ){
   120393             /* A MATCH operator. The right-hand-side must be a blob that
   120394             ** can be cast into an RtreeMatchArg object. One created using
   120395             ** an sqlite3_rtree_geometry_callback() SQL user function.
   120396             */
   120397             rc = deserializeGeometry(argv[ii], p);
   120398             if( rc!=SQLITE_OK ){
   120399               break;
   120400             }
   120401           }else{
   120402             p->rValue = sqlite3_value_double(argv[ii]);
   120403           }
   120404         }
   120405       }
   120406     }
   120407 
   120408     if( rc==SQLITE_OK ){
   120409       pCsr->pNode = 0;
   120410       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   120411     }
   120412     if( rc==SQLITE_OK ){
   120413       int isEof = 1;
   120414       int nCell = NCELL(pRoot);
   120415       pCsr->pNode = pRoot;
   120416       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
   120417         assert( pCsr->pNode==pRoot );
   120418         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
   120419         if( !isEof ){
   120420           break;
   120421         }
   120422       }
   120423       if( rc==SQLITE_OK && isEof ){
   120424         assert( pCsr->pNode==pRoot );
   120425         nodeRelease(pRtree, pRoot);
   120426         pCsr->pNode = 0;
   120427       }
   120428       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
   120429     }
   120430   }
   120431 
   120432   rtreeRelease(pRtree);
   120433   return rc;
   120434 }
   120435 
   120436 /*
   120437 ** Rtree virtual table module xBestIndex method. There are three
   120438 ** table scan strategies to choose from (in order from most to
   120439 ** least desirable):
   120440 **
   120441 **   idxNum     idxStr        Strategy
   120442 **   ------------------------------------------------
   120443 **     1        Unused        Direct lookup by rowid.
   120444 **     2        See below     R-tree query or full-table scan.
   120445 **   ------------------------------------------------
   120446 **
   120447 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
   120448 ** 2 is used, idxStr is formatted to contain 2 bytes for each
   120449 ** constraint used. The first two bytes of idxStr correspond to
   120450 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
   120451 ** (argvIndex==1) etc.
   120452 **
   120453 ** The first of each pair of bytes in idxStr identifies the constraint
   120454 ** operator as follows:
   120455 **
   120456 **   Operator    Byte Value
   120457 **   ----------------------
   120458 **      =        0x41 ('A')
   120459 **     <=        0x42 ('B')
   120460 **      <        0x43 ('C')
   120461 **     >=        0x44 ('D')
   120462 **      >        0x45 ('E')
   120463 **   MATCH       0x46 ('F')
   120464 **   ----------------------
   120465 **
   120466 ** The second of each pair of bytes identifies the coordinate column
   120467 ** to which the constraint applies. The leftmost coordinate column
   120468 ** is 'a', the second from the left 'b' etc.
   120469 */
   120470 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   120471   int rc = SQLITE_OK;
   120472   int ii, cCol;
   120473 
   120474   int iIdx = 0;
   120475   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
   120476   memset(zIdxStr, 0, sizeof(zIdxStr));
   120477   UNUSED_PARAMETER(tab);
   120478 
   120479   assert( pIdxInfo->idxStr==0 );
   120480   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
   120481     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
   120482 
   120483     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
   120484       /* We have an equality constraint on the rowid. Use strategy 1. */
   120485       int jj;
   120486       for(jj=0; jj<ii; jj++){
   120487         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
   120488         pIdxInfo->aConstraintUsage[jj].omit = 0;
   120489       }
   120490       pIdxInfo->idxNum = 1;
   120491       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
   120492       pIdxInfo->aConstraintUsage[jj].omit = 1;
   120493 
   120494       /* This strategy involves a two rowid lookups on an B-Tree structures
   120495       ** and then a linear search of an R-Tree node. This should be
   120496       ** considered almost as quick as a direct rowid lookup (for which
   120497       ** sqlite uses an internal cost of 0.0).
   120498       */
   120499       pIdxInfo->estimatedCost = 10.0;
   120500       return SQLITE_OK;
   120501     }
   120502 
   120503     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
   120504       int j, opmsk;
   120505       static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
   120506       u8 op = 0;
   120507       switch( p->op ){
   120508         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
   120509         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
   120510         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
   120511         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
   120512         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
   120513         default:
   120514           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
   120515           op = RTREE_MATCH;
   120516           break;
   120517       }
   120518       assert( op!=0 );
   120519 
   120520       /* Make sure this particular constraint has not been used before.
   120521       ** If it has been used before, ignore it.
   120522       **
   120523       ** A <= or < can be used if there is a prior >= or >.
   120524       ** A >= or > can be used if there is a prior < or <=.
   120525       ** A <= or < is disqualified if there is a prior <=, <, or ==.
   120526       ** A >= or > is disqualified if there is a prior >=, >, or ==.
   120527       ** A == is disqualifed if there is any prior constraint.
   120528       */
   120529       assert( compatible[RTREE_EQ & 7]==0 );
   120530       assert( compatible[RTREE_LT & 7]==1 );
   120531       assert( compatible[RTREE_LE & 7]==1 );
   120532       assert( compatible[RTREE_GT & 7]==2 );
   120533       assert( compatible[RTREE_GE & 7]==2 );
   120534       cCol = p->iColumn - 1 + 'a';
   120535       opmsk = compatible[op & 7];
   120536       for(j=0; j<iIdx; j+=2){
   120537         if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
   120538           op = 0;
   120539           break;
   120540         }
   120541       }
   120542       if( op ){
   120543         assert( iIdx<sizeof(zIdxStr)-1 );
   120544         zIdxStr[iIdx++] = op;
   120545         zIdxStr[iIdx++] = cCol;
   120546         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
   120547         pIdxInfo->aConstraintUsage[ii].omit = 1;
   120548       }
   120549     }
   120550   }
   120551 
   120552   pIdxInfo->idxNum = 2;
   120553   pIdxInfo->needToFreeIdxStr = 1;
   120554   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
   120555     return SQLITE_NOMEM;
   120556   }
   120557   assert( iIdx>=0 );
   120558   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
   120559   return rc;
   120560 }
   120561 
   120562 /*
   120563 ** Return the N-dimensional volumn of the cell stored in *p.
   120564 */
   120565 static float cellArea(Rtree *pRtree, RtreeCell *p){
   120566   float area = 1.0;
   120567   int ii;
   120568   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   120569     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   120570   }
   120571   return area;
   120572 }
   120573 
   120574 /*
   120575 ** Return the margin length of cell p. The margin length is the sum
   120576 ** of the objects size in each dimension.
   120577 */
   120578 static float cellMargin(Rtree *pRtree, RtreeCell *p){
   120579   float margin = 0.0;
   120580   int ii;
   120581   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   120582     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
   120583   }
   120584   return margin;
   120585 }
   120586 
   120587 /*
   120588 ** Store the union of cells p1 and p2 in p1.
   120589 */
   120590 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   120591   int ii;
   120592   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   120593     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   120594       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
   120595       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
   120596     }
   120597   }else{
   120598     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   120599       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
   120600       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
   120601     }
   120602   }
   120603 }
   120604 
   120605 /*
   120606 ** Return true if the area covered by p2 is a subset of the area covered
   120607 ** by p1. False otherwise.
   120608 */
   120609 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   120610   int ii;
   120611   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
   120612   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   120613     RtreeCoord *a1 = &p1->aCoord[ii];
   120614     RtreeCoord *a2 = &p2->aCoord[ii];
   120615     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
   120616      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
   120617     ){
   120618       return 0;
   120619     }
   120620   }
   120621   return 1;
   120622 }
   120623 
   120624 /*
   120625 ** Return the amount cell p would grow by if it were unioned with pCell.
   120626 */
   120627 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
   120628   float area;
   120629   RtreeCell cell;
   120630   memcpy(&cell, p, sizeof(RtreeCell));
   120631   area = cellArea(pRtree, &cell);
   120632   cellUnion(pRtree, &cell, pCell);
   120633   return (cellArea(pRtree, &cell)-area);
   120634 }
   120635 
   120636 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
   120637 static float cellOverlap(
   120638   Rtree *pRtree,
   120639   RtreeCell *p,
   120640   RtreeCell *aCell,
   120641   int nCell,
   120642   int iExclude
   120643 ){
   120644   int ii;
   120645   float overlap = 0.0;
   120646   for(ii=0; ii<nCell; ii++){
   120647 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   120648     if( ii!=iExclude )
   120649 #else
   120650     assert( iExclude==-1 );
   120651     UNUSED_PARAMETER(iExclude);
   120652 #endif
   120653     {
   120654       int jj;
   120655       float o = 1.0;
   120656       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
   120657         double x1;
   120658         double x2;
   120659 
   120660         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
   120661         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
   120662 
   120663         if( x2<x1 ){
   120664           o = 0.0;
   120665           break;
   120666         }else{
   120667           o = o * (x2-x1);
   120668         }
   120669       }
   120670       overlap += o;
   120671     }
   120672   }
   120673   return overlap;
   120674 }
   120675 #endif
   120676 
   120677 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   120678 static float cellOverlapEnlargement(
   120679   Rtree *pRtree,
   120680   RtreeCell *p,
   120681   RtreeCell *pInsert,
   120682   RtreeCell *aCell,
   120683   int nCell,
   120684   int iExclude
   120685 ){
   120686   float before;
   120687   float after;
   120688   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   120689   cellUnion(pRtree, p, pInsert);
   120690   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
   120691   return after-before;
   120692 }
   120693 #endif
   120694 
   120695 
   120696 /*
   120697 ** This function implements the ChooseLeaf algorithm from Gutman[84].
   120698 ** ChooseSubTree in r*tree terminology.
   120699 */
   120700 static int ChooseLeaf(
   120701   Rtree *pRtree,               /* Rtree table */
   120702   RtreeCell *pCell,            /* Cell to insert into rtree */
   120703   int iHeight,                 /* Height of sub-tree rooted at pCell */
   120704   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
   120705 ){
   120706   int rc;
   120707   int ii;
   120708   RtreeNode *pNode;
   120709   rc = nodeAcquire(pRtree, 1, 0, &pNode);
   120710 
   120711   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
   120712     int iCell;
   120713     sqlite3_int64 iBest;
   120714 
   120715     float fMinGrowth;
   120716     float fMinArea;
   120717     float fMinOverlap;
   120718 
   120719     int nCell = NCELL(pNode);
   120720     RtreeCell cell;
   120721     RtreeNode *pChild;
   120722 
   120723     RtreeCell *aCell = 0;
   120724 
   120725 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   120726     if( ii==(pRtree->iDepth-1) ){
   120727       int jj;
   120728       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
   120729       if( !aCell ){
   120730         rc = SQLITE_NOMEM;
   120731         nodeRelease(pRtree, pNode);
   120732         pNode = 0;
   120733         continue;
   120734       }
   120735       for(jj=0; jj<nCell; jj++){
   120736         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
   120737       }
   120738     }
   120739 #endif
   120740 
   120741     /* Select the child node which will be enlarged the least if pCell
   120742     ** is inserted into it. Resolve ties by choosing the entry with
   120743     ** the smallest area.
   120744     */
   120745     for(iCell=0; iCell<nCell; iCell++){
   120746       int bBest = 0;
   120747       float growth;
   120748       float area;
   120749       float overlap = 0.0;
   120750       nodeGetCell(pRtree, pNode, iCell, &cell);
   120751       growth = cellGrowth(pRtree, &cell, pCell);
   120752       area = cellArea(pRtree, &cell);
   120753 
   120754 #if VARIANT_RSTARTREE_CHOOSESUBTREE
   120755       if( ii==(pRtree->iDepth-1) ){
   120756         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
   120757       }
   120758       if( (iCell==0)
   120759        || (overlap<fMinOverlap)
   120760        || (overlap==fMinOverlap && growth<fMinGrowth)
   120761        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
   120762       ){
   120763         bBest = 1;
   120764       }
   120765 #else
   120766       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
   120767         bBest = 1;
   120768       }
   120769 #endif
   120770       if( bBest ){
   120771         fMinOverlap = overlap;
   120772         fMinGrowth = growth;
   120773         fMinArea = area;
   120774         iBest = cell.iRowid;
   120775       }
   120776     }
   120777 
   120778     sqlite3_free(aCell);
   120779     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
   120780     nodeRelease(pRtree, pNode);
   120781     pNode = pChild;
   120782   }
   120783 
   120784   *ppLeaf = pNode;
   120785   return rc;
   120786 }
   120787 
   120788 /*
   120789 ** A cell with the same content as pCell has just been inserted into
   120790 ** the node pNode. This function updates the bounding box cells in
   120791 ** all ancestor elements.
   120792 */
   120793 static int AdjustTree(
   120794   Rtree *pRtree,                    /* Rtree table */
   120795   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
   120796   RtreeCell *pCell                  /* This cell was just inserted */
   120797 ){
   120798   RtreeNode *p = pNode;
   120799   while( p->pParent ){
   120800     RtreeNode *pParent = p->pParent;
   120801     RtreeCell cell;
   120802     int iCell;
   120803 
   120804     if( nodeParentIndex(pRtree, p, &iCell) ){
   120805       return SQLITE_CORRUPT;
   120806     }
   120807 
   120808     nodeGetCell(pRtree, pParent, iCell, &cell);
   120809     if( !cellContains(pRtree, &cell, pCell) ){
   120810       cellUnion(pRtree, &cell, pCell);
   120811       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
   120812     }
   120813 
   120814     p = pParent;
   120815   }
   120816   return SQLITE_OK;
   120817 }
   120818 
   120819 /*
   120820 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
   120821 */
   120822 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
   120823   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
   120824   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
   120825   sqlite3_step(pRtree->pWriteRowid);
   120826   return sqlite3_reset(pRtree->pWriteRowid);
   120827 }
   120828 
   120829 /*
   120830 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
   120831 */
   120832 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
   120833   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
   120834   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
   120835   sqlite3_step(pRtree->pWriteParent);
   120836   return sqlite3_reset(pRtree->pWriteParent);
   120837 }
   120838 
   120839 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
   120840 
   120841 #if VARIANT_GUTTMAN_LINEAR_SPLIT
   120842 /*
   120843 ** Implementation of the linear variant of the PickNext() function from
   120844 ** Guttman[84].
   120845 */
   120846 static RtreeCell *LinearPickNext(
   120847   Rtree *pRtree,
   120848   RtreeCell *aCell,
   120849   int nCell,
   120850   RtreeCell *pLeftBox,
   120851   RtreeCell *pRightBox,
   120852   int *aiUsed
   120853 ){
   120854   int ii;
   120855   for(ii=0; aiUsed[ii]; ii++);
   120856   aiUsed[ii] = 1;
   120857   return &aCell[ii];
   120858 }
   120859 
   120860 /*
   120861 ** Implementation of the linear variant of the PickSeeds() function from
   120862 ** Guttman[84].
   120863 */
   120864 static void LinearPickSeeds(
   120865   Rtree *pRtree,
   120866   RtreeCell *aCell,
   120867   int nCell,
   120868   int *piLeftSeed,
   120869   int *piRightSeed
   120870 ){
   120871   int i;
   120872   int iLeftSeed = 0;
   120873   int iRightSeed = 1;
   120874   float maxNormalInnerWidth = 0.0;
   120875 
   120876   /* Pick two "seed" cells from the array of cells. The algorithm used
   120877   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
   120878   ** indices of the two seed cells in the array are stored in local
   120879   ** variables iLeftSeek and iRightSeed.
   120880   */
   120881   for(i=0; i<pRtree->nDim; i++){
   120882     float x1 = DCOORD(aCell[0].aCoord[i*2]);
   120883     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
   120884     float x3 = x1;
   120885     float x4 = x2;
   120886     int jj;
   120887 
   120888     int iCellLeft = 0;
   120889     int iCellRight = 0;
   120890 
   120891     for(jj=1; jj<nCell; jj++){
   120892       float left = DCOORD(aCell[jj].aCoord[i*2]);
   120893       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
   120894 
   120895       if( left<x1 ) x1 = left;
   120896       if( right>x4 ) x4 = right;
   120897       if( left>x3 ){
   120898         x3 = left;
   120899         iCellRight = jj;
   120900       }
   120901       if( right<x2 ){
   120902         x2 = right;
   120903         iCellLeft = jj;
   120904       }
   120905     }
   120906 
   120907     if( x4!=x1 ){
   120908       float normalwidth = (x3 - x2) / (x4 - x1);
   120909       if( normalwidth>maxNormalInnerWidth ){
   120910         iLeftSeed = iCellLeft;
   120911         iRightSeed = iCellRight;
   120912       }
   120913     }
   120914   }
   120915 
   120916   *piLeftSeed = iLeftSeed;
   120917   *piRightSeed = iRightSeed;
   120918 }
   120919 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
   120920 
   120921 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
   120922 /*
   120923 ** Implementation of the quadratic variant of the PickNext() function from
   120924 ** Guttman[84].
   120925 */
   120926 static RtreeCell *QuadraticPickNext(
   120927   Rtree *pRtree,
   120928   RtreeCell *aCell,
   120929   int nCell,
   120930   RtreeCell *pLeftBox,
   120931   RtreeCell *pRightBox,
   120932   int *aiUsed
   120933 ){
   120934   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
   120935 
   120936   int iSelect = -1;
   120937   float fDiff;
   120938   int ii;
   120939   for(ii=0; ii<nCell; ii++){
   120940     if( aiUsed[ii]==0 ){
   120941       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   120942       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
   120943       float diff = FABS(right-left);
   120944       if( iSelect<0 || diff>fDiff ){
   120945         fDiff = diff;
   120946         iSelect = ii;
   120947       }
   120948     }
   120949   }
   120950   aiUsed[iSelect] = 1;
   120951   return &aCell[iSelect];
   120952 }
   120953 
   120954 /*
   120955 ** Implementation of the quadratic variant of the PickSeeds() function from
   120956 ** Guttman[84].
   120957 */
   120958 static void QuadraticPickSeeds(
   120959   Rtree *pRtree,
   120960   RtreeCell *aCell,
   120961   int nCell,
   120962   int *piLeftSeed,
   120963   int *piRightSeed
   120964 ){
   120965   int ii;
   120966   int jj;
   120967 
   120968   int iLeftSeed = 0;
   120969   int iRightSeed = 1;
   120970   float fWaste = 0.0;
   120971 
   120972   for(ii=0; ii<nCell; ii++){
   120973     for(jj=ii+1; jj<nCell; jj++){
   120974       float right = cellArea(pRtree, &aCell[jj]);
   120975       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
   120976       float waste = growth - right;
   120977 
   120978       if( waste>fWaste ){
   120979         iLeftSeed = ii;
   120980         iRightSeed = jj;
   120981         fWaste = waste;
   120982       }
   120983     }
   120984   }
   120985 
   120986   *piLeftSeed = iLeftSeed;
   120987   *piRightSeed = iRightSeed;
   120988 }
   120989 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
   120990 
   120991 /*
   120992 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
   120993 ** nIdx. The aIdx array contains the set of integers from 0 to
   120994 ** (nIdx-1) in no particular order. This function sorts the values
   120995 ** in aIdx according to the indexed values in aDistance. For
   120996 ** example, assuming the inputs:
   120997 **
   120998 **   aIdx      = { 0,   1,   2,   3 }
   120999 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
   121000 **
   121001 ** this function sets the aIdx array to contain:
   121002 **
   121003 **   aIdx      = { 0,   1,   2,   3 }
   121004 **
   121005 ** The aSpare array is used as temporary working space by the
   121006 ** sorting algorithm.
   121007 */
   121008 static void SortByDistance(
   121009   int *aIdx,
   121010   int nIdx,
   121011   float *aDistance,
   121012   int *aSpare
   121013 ){
   121014   if( nIdx>1 ){
   121015     int iLeft = 0;
   121016     int iRight = 0;
   121017 
   121018     int nLeft = nIdx/2;
   121019     int nRight = nIdx-nLeft;
   121020     int *aLeft = aIdx;
   121021     int *aRight = &aIdx[nLeft];
   121022 
   121023     SortByDistance(aLeft, nLeft, aDistance, aSpare);
   121024     SortByDistance(aRight, nRight, aDistance, aSpare);
   121025 
   121026     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   121027     aLeft = aSpare;
   121028 
   121029     while( iLeft<nLeft || iRight<nRight ){
   121030       if( iLeft==nLeft ){
   121031         aIdx[iLeft+iRight] = aRight[iRight];
   121032         iRight++;
   121033       }else if( iRight==nRight ){
   121034         aIdx[iLeft+iRight] = aLeft[iLeft];
   121035         iLeft++;
   121036       }else{
   121037         float fLeft = aDistance[aLeft[iLeft]];
   121038         float fRight = aDistance[aRight[iRight]];
   121039         if( fLeft<fRight ){
   121040           aIdx[iLeft+iRight] = aLeft[iLeft];
   121041           iLeft++;
   121042         }else{
   121043           aIdx[iLeft+iRight] = aRight[iRight];
   121044           iRight++;
   121045         }
   121046       }
   121047     }
   121048 
   121049 #if 0
   121050     /* Check that the sort worked */
   121051     {
   121052       int jj;
   121053       for(jj=1; jj<nIdx; jj++){
   121054         float left = aDistance[aIdx[jj-1]];
   121055         float right = aDistance[aIdx[jj]];
   121056         assert( left<=right );
   121057       }
   121058     }
   121059 #endif
   121060   }
   121061 }
   121062 
   121063 /*
   121064 ** Arguments aIdx, aCell and aSpare all point to arrays of size
   121065 ** nIdx. The aIdx array contains the set of integers from 0 to
   121066 ** (nIdx-1) in no particular order. This function sorts the values
   121067 ** in aIdx according to dimension iDim of the cells in aCell. The
   121068 ** minimum value of dimension iDim is considered first, the
   121069 ** maximum used to break ties.
   121070 **
   121071 ** The aSpare array is used as temporary working space by the
   121072 ** sorting algorithm.
   121073 */
   121074 static void SortByDimension(
   121075   Rtree *pRtree,
   121076   int *aIdx,
   121077   int nIdx,
   121078   int iDim,
   121079   RtreeCell *aCell,
   121080   int *aSpare
   121081 ){
   121082   if( nIdx>1 ){
   121083 
   121084     int iLeft = 0;
   121085     int iRight = 0;
   121086 
   121087     int nLeft = nIdx/2;
   121088     int nRight = nIdx-nLeft;
   121089     int *aLeft = aIdx;
   121090     int *aRight = &aIdx[nLeft];
   121091 
   121092     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
   121093     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
   121094 
   121095     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
   121096     aLeft = aSpare;
   121097     while( iLeft<nLeft || iRight<nRight ){
   121098       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
   121099       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
   121100       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
   121101       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
   121102       if( (iLeft!=nLeft) && ((iRight==nRight)
   121103        || (xleft1<xright1)
   121104        || (xleft1==xright1 && xleft2<xright2)
   121105       )){
   121106         aIdx[iLeft+iRight] = aLeft[iLeft];
   121107         iLeft++;
   121108       }else{
   121109         aIdx[iLeft+iRight] = aRight[iRight];
   121110         iRight++;
   121111       }
   121112     }
   121113 
   121114 #if 0
   121115     /* Check that the sort worked */
   121116     {
   121117       int jj;
   121118       for(jj=1; jj<nIdx; jj++){
   121119         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
   121120         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
   121121         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
   121122         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
   121123         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
   121124       }
   121125     }
   121126 #endif
   121127   }
   121128 }
   121129 
   121130 #if VARIANT_RSTARTREE_SPLIT
   121131 /*
   121132 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
   121133 */
   121134 static int splitNodeStartree(
   121135   Rtree *pRtree,
   121136   RtreeCell *aCell,
   121137   int nCell,
   121138   RtreeNode *pLeft,
   121139   RtreeNode *pRight,
   121140   RtreeCell *pBboxLeft,
   121141   RtreeCell *pBboxRight
   121142 ){
   121143   int **aaSorted;
   121144   int *aSpare;
   121145   int ii;
   121146 
   121147   int iBestDim;
   121148   int iBestSplit;
   121149   float fBestMargin;
   121150 
   121151   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
   121152 
   121153   aaSorted = (int **)sqlite3_malloc(nByte);
   121154   if( !aaSorted ){
   121155     return SQLITE_NOMEM;
   121156   }
   121157 
   121158   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
   121159   memset(aaSorted, 0, nByte);
   121160   for(ii=0; ii<pRtree->nDim; ii++){
   121161     int jj;
   121162     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
   121163     for(jj=0; jj<nCell; jj++){
   121164       aaSorted[ii][jj] = jj;
   121165     }
   121166     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
   121167   }
   121168 
   121169   for(ii=0; ii<pRtree->nDim; ii++){
   121170     float margin = 0.0;
   121171     float fBestOverlap;
   121172     float fBestArea;
   121173     int iBestLeft;
   121174     int nLeft;
   121175 
   121176     for(
   121177       nLeft=RTREE_MINCELLS(pRtree);
   121178       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
   121179       nLeft++
   121180     ){
   121181       RtreeCell left;
   121182       RtreeCell right;
   121183       int kk;
   121184       float overlap;
   121185       float area;
   121186 
   121187       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
   121188       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
   121189       for(kk=1; kk<(nCell-1); kk++){
   121190         if( kk<nLeft ){
   121191           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
   121192         }else{
   121193           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
   121194         }
   121195       }
   121196       margin += cellMargin(pRtree, &left);
   121197       margin += cellMargin(pRtree, &right);
   121198       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
   121199       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
   121200       if( (nLeft==RTREE_MINCELLS(pRtree))
   121201        || (overlap<fBestOverlap)
   121202        || (overlap==fBestOverlap && area<fBestArea)
   121203       ){
   121204         iBestLeft = nLeft;
   121205         fBestOverlap = overlap;
   121206         fBestArea = area;
   121207       }
   121208     }
   121209 
   121210     if( ii==0 || margin<fBestMargin ){
   121211       iBestDim = ii;
   121212       fBestMargin = margin;
   121213       iBestSplit = iBestLeft;
   121214     }
   121215   }
   121216 
   121217   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
   121218   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
   121219   for(ii=0; ii<nCell; ii++){
   121220     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
   121221     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
   121222     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
   121223     nodeInsertCell(pRtree, pTarget, pCell);
   121224     cellUnion(pRtree, pBbox, pCell);
   121225   }
   121226 
   121227   sqlite3_free(aaSorted);
   121228   return SQLITE_OK;
   121229 }
   121230 #endif
   121231 
   121232 #if VARIANT_GUTTMAN_SPLIT
   121233 /*
   121234 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
   121235 */
   121236 static int splitNodeGuttman(
   121237   Rtree *pRtree,
   121238   RtreeCell *aCell,
   121239   int nCell,
   121240   RtreeNode *pLeft,
   121241   RtreeNode *pRight,
   121242   RtreeCell *pBboxLeft,
   121243   RtreeCell *pBboxRight
   121244 ){
   121245   int iLeftSeed = 0;
   121246   int iRightSeed = 1;
   121247   int *aiUsed;
   121248   int i;
   121249 
   121250   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
   121251   if( !aiUsed ){
   121252     return SQLITE_NOMEM;
   121253   }
   121254   memset(aiUsed, 0, sizeof(int)*nCell);
   121255 
   121256   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
   121257 
   121258   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
   121259   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
   121260   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
   121261   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
   121262   aiUsed[iLeftSeed] = 1;
   121263   aiUsed[iRightSeed] = 1;
   121264 
   121265   for(i=nCell-2; i>0; i--){
   121266     RtreeCell *pNext;
   121267     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
   121268     float diff =
   121269       cellGrowth(pRtree, pBboxLeft, pNext) -
   121270       cellGrowth(pRtree, pBboxRight, pNext)
   121271     ;
   121272     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
   121273      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
   121274     ){
   121275       nodeInsertCell(pRtree, pRight, pNext);
   121276       cellUnion(pRtree, pBboxRight, pNext);
   121277     }else{
   121278       nodeInsertCell(pRtree, pLeft, pNext);
   121279       cellUnion(pRtree, pBboxLeft, pNext);
   121280     }
   121281   }
   121282 
   121283   sqlite3_free(aiUsed);
   121284   return SQLITE_OK;
   121285 }
   121286 #endif
   121287 
   121288 static int updateMapping(
   121289   Rtree *pRtree,
   121290   i64 iRowid,
   121291   RtreeNode *pNode,
   121292   int iHeight
   121293 ){
   121294   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
   121295   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
   121296   if( iHeight>0 ){
   121297     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
   121298     if( pChild ){
   121299       nodeRelease(pRtree, pChild->pParent);
   121300       nodeReference(pNode);
   121301       pChild->pParent = pNode;
   121302     }
   121303   }
   121304   return xSetMapping(pRtree, iRowid, pNode->iNode);
   121305 }
   121306 
   121307 static int SplitNode(
   121308   Rtree *pRtree,
   121309   RtreeNode *pNode,
   121310   RtreeCell *pCell,
   121311   int iHeight
   121312 ){
   121313   int i;
   121314   int newCellIsRight = 0;
   121315 
   121316   int rc = SQLITE_OK;
   121317   int nCell = NCELL(pNode);
   121318   RtreeCell *aCell;
   121319   int *aiUsed;
   121320 
   121321   RtreeNode *pLeft = 0;
   121322   RtreeNode *pRight = 0;
   121323 
   121324   RtreeCell leftbbox;
   121325   RtreeCell rightbbox;
   121326 
   121327   /* Allocate an array and populate it with a copy of pCell and
   121328   ** all cells from node pLeft. Then zero the original node.
   121329   */
   121330   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
   121331   if( !aCell ){
   121332     rc = SQLITE_NOMEM;
   121333     goto splitnode_out;
   121334   }
   121335   aiUsed = (int *)&aCell[nCell+1];
   121336   memset(aiUsed, 0, sizeof(int)*(nCell+1));
   121337   for(i=0; i<nCell; i++){
   121338     nodeGetCell(pRtree, pNode, i, &aCell[i]);
   121339   }
   121340   nodeZero(pRtree, pNode);
   121341   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
   121342   nCell++;
   121343 
   121344   if( pNode->iNode==1 ){
   121345     pRight = nodeNew(pRtree, pNode);
   121346     pLeft = nodeNew(pRtree, pNode);
   121347     pRtree->iDepth++;
   121348     pNode->isDirty = 1;
   121349     writeInt16(pNode->zData, pRtree->iDepth);
   121350   }else{
   121351     pLeft = pNode;
   121352     pRight = nodeNew(pRtree, pLeft->pParent);
   121353     nodeReference(pLeft);
   121354   }
   121355 
   121356   if( !pLeft || !pRight ){
   121357     rc = SQLITE_NOMEM;
   121358     goto splitnode_out;
   121359   }
   121360 
   121361   memset(pLeft->zData, 0, pRtree->iNodeSize);
   121362   memset(pRight->zData, 0, pRtree->iNodeSize);
   121363 
   121364   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
   121365   if( rc!=SQLITE_OK ){
   121366     goto splitnode_out;
   121367   }
   121368 
   121369   /* Ensure both child nodes have node numbers assigned to them by calling
   121370   ** nodeWrite(). Node pRight always needs a node number, as it was created
   121371   ** by nodeNew() above. But node pLeft sometimes already has a node number.
   121372   ** In this case avoid the all to nodeWrite().
   121373   */
   121374   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
   121375    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
   121376   ){
   121377     goto splitnode_out;
   121378   }
   121379 
   121380   rightbbox.iRowid = pRight->iNode;
   121381   leftbbox.iRowid = pLeft->iNode;
   121382 
   121383   if( pNode->iNode==1 ){
   121384     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
   121385     if( rc!=SQLITE_OK ){
   121386       goto splitnode_out;
   121387     }
   121388   }else{
   121389     RtreeNode *pParent = pLeft->pParent;
   121390     int iCell;
   121391     rc = nodeParentIndex(pRtree, pLeft, &iCell);
   121392     if( rc==SQLITE_OK ){
   121393       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
   121394       rc = AdjustTree(pRtree, pParent, &leftbbox);
   121395     }
   121396     if( rc!=SQLITE_OK ){
   121397       goto splitnode_out;
   121398     }
   121399   }
   121400   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
   121401     goto splitnode_out;
   121402   }
   121403 
   121404   for(i=0; i<NCELL(pRight); i++){
   121405     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
   121406     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
   121407     if( iRowid==pCell->iRowid ){
   121408       newCellIsRight = 1;
   121409     }
   121410     if( rc!=SQLITE_OK ){
   121411       goto splitnode_out;
   121412     }
   121413   }
   121414   if( pNode->iNode==1 ){
   121415     for(i=0; i<NCELL(pLeft); i++){
   121416       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
   121417       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
   121418       if( rc!=SQLITE_OK ){
   121419         goto splitnode_out;
   121420       }
   121421     }
   121422   }else if( newCellIsRight==0 ){
   121423     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
   121424   }
   121425 
   121426   if( rc==SQLITE_OK ){
   121427     rc = nodeRelease(pRtree, pRight);
   121428     pRight = 0;
   121429   }
   121430   if( rc==SQLITE_OK ){
   121431     rc = nodeRelease(pRtree, pLeft);
   121432     pLeft = 0;
   121433   }
   121434 
   121435 splitnode_out:
   121436   nodeRelease(pRtree, pRight);
   121437   nodeRelease(pRtree, pLeft);
   121438   sqlite3_free(aCell);
   121439   return rc;
   121440 }
   121441 
   121442 /*
   121443 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
   121444 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
   121445 ** the pLeaf->pParent chain all the way up to the root node.
   121446 **
   121447 ** This operation is required when a row is deleted (or updated - an update
   121448 ** is implemented as a delete followed by an insert). SQLite provides the
   121449 ** rowid of the row to delete, which can be used to find the leaf on which
   121450 ** the entry resides (argument pLeaf). Once the leaf is located, this
   121451 ** function is called to determine its ancestry.
   121452 */
   121453 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
   121454   int rc = SQLITE_OK;
   121455   RtreeNode *pChild = pLeaf;
   121456   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
   121457     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
   121458     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
   121459     rc = sqlite3_step(pRtree->pReadParent);
   121460     if( rc==SQLITE_ROW ){
   121461       RtreeNode *pTest;           /* Used to test for reference loops */
   121462       i64 iNode;                  /* Node number of parent node */
   121463 
   121464       /* Before setting pChild->pParent, test that we are not creating a
   121465       ** loop of references (as we would if, say, pChild==pParent). We don't
   121466       ** want to do this as it leads to a memory leak when trying to delete
   121467       ** the referenced counted node structures.
   121468       */
   121469       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
   121470       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
   121471       if( !pTest ){
   121472         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
   121473       }
   121474     }
   121475     rc = sqlite3_reset(pRtree->pReadParent);
   121476     if( rc==SQLITE_OK ) rc = rc2;
   121477     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
   121478     pChild = pChild->pParent;
   121479   }
   121480   return rc;
   121481 }
   121482 
   121483 static int deleteCell(Rtree *, RtreeNode *, int, int);
   121484 
   121485 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   121486   int rc;
   121487   int rc2;
   121488   RtreeNode *pParent;
   121489   int iCell;
   121490 
   121491   assert( pNode->nRef==1 );
   121492 
   121493   /* Remove the entry in the parent cell. */
   121494   rc = nodeParentIndex(pRtree, pNode, &iCell);
   121495   if( rc==SQLITE_OK ){
   121496     pParent = pNode->pParent;
   121497     pNode->pParent = 0;
   121498     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
   121499   }
   121500   rc2 = nodeRelease(pRtree, pParent);
   121501   if( rc==SQLITE_OK ){
   121502     rc = rc2;
   121503   }
   121504   if( rc!=SQLITE_OK ){
   121505     return rc;
   121506   }
   121507 
   121508   /* Remove the xxx_node entry. */
   121509   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
   121510   sqlite3_step(pRtree->pDeleteNode);
   121511   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
   121512     return rc;
   121513   }
   121514 
   121515   /* Remove the xxx_parent entry. */
   121516   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
   121517   sqlite3_step(pRtree->pDeleteParent);
   121518   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
   121519     return rc;
   121520   }
   121521 
   121522   /* Remove the node from the in-memory hash table and link it into
   121523   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   121524   */
   121525   nodeHashDelete(pRtree, pNode);
   121526   pNode->iNode = iHeight;
   121527   pNode->pNext = pRtree->pDeleted;
   121528   pNode->nRef++;
   121529   pRtree->pDeleted = pNode;
   121530 
   121531   return SQLITE_OK;
   121532 }
   121533 
   121534 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   121535   RtreeNode *pParent = pNode->pParent;
   121536   int rc = SQLITE_OK;
   121537   if( pParent ){
   121538     int ii;
   121539     int nCell = NCELL(pNode);
   121540     RtreeCell box;                            /* Bounding box for pNode */
   121541     nodeGetCell(pRtree, pNode, 0, &box);
   121542     for(ii=1; ii<nCell; ii++){
   121543       RtreeCell cell;
   121544       nodeGetCell(pRtree, pNode, ii, &cell);
   121545       cellUnion(pRtree, &box, &cell);
   121546     }
   121547     box.iRowid = pNode->iNode;
   121548     rc = nodeParentIndex(pRtree, pNode, &ii);
   121549     if( rc==SQLITE_OK ){
   121550       nodeOverwriteCell(pRtree, pParent, &box, ii);
   121551       rc = fixBoundingBox(pRtree, pParent);
   121552     }
   121553   }
   121554   return rc;
   121555 }
   121556 
   121557 /*
   121558 ** Delete the cell at index iCell of node pNode. After removing the
   121559 ** cell, adjust the r-tree data structure if required.
   121560 */
   121561 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
   121562   RtreeNode *pParent;
   121563   int rc;
   121564 
   121565   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
   121566     return rc;
   121567   }
   121568 
   121569   /* Remove the cell from the node. This call just moves bytes around
   121570   ** the in-memory node image, so it cannot fail.
   121571   */
   121572   nodeDeleteCell(pRtree, pNode, iCell);
   121573 
   121574   /* If the node is not the tree root and now has less than the minimum
   121575   ** number of cells, remove it from the tree. Otherwise, update the
   121576   ** cell in the parent node so that it tightly contains the updated
   121577   ** node.
   121578   */
   121579   pParent = pNode->pParent;
   121580   assert( pParent || pNode->iNode==1 );
   121581   if( pParent ){
   121582     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
   121583       rc = removeNode(pRtree, pNode, iHeight);
   121584     }else{
   121585       rc = fixBoundingBox(pRtree, pNode);
   121586     }
   121587   }
   121588 
   121589   return rc;
   121590 }
   121591 
   121592 static int Reinsert(
   121593   Rtree *pRtree,
   121594   RtreeNode *pNode,
   121595   RtreeCell *pCell,
   121596   int iHeight
   121597 ){
   121598   int *aOrder;
   121599   int *aSpare;
   121600   RtreeCell *aCell;
   121601   float *aDistance;
   121602   int nCell;
   121603   float aCenterCoord[RTREE_MAX_DIMENSIONS];
   121604   int iDim;
   121605   int ii;
   121606   int rc = SQLITE_OK;
   121607 
   121608   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
   121609 
   121610   nCell = NCELL(pNode)+1;
   121611 
   121612   /* Allocate the buffers used by this operation. The allocation is
   121613   ** relinquished before this function returns.
   121614   */
   121615   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
   121616     sizeof(RtreeCell) +         /* aCell array */
   121617     sizeof(int)       +         /* aOrder array */
   121618     sizeof(int)       +         /* aSpare array */
   121619     sizeof(float)               /* aDistance array */
   121620   ));
   121621   if( !aCell ){
   121622     return SQLITE_NOMEM;
   121623   }
   121624   aOrder    = (int *)&aCell[nCell];
   121625   aSpare    = (int *)&aOrder[nCell];
   121626   aDistance = (float *)&aSpare[nCell];
   121627 
   121628   for(ii=0; ii<nCell; ii++){
   121629     if( ii==(nCell-1) ){
   121630       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
   121631     }else{
   121632       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
   121633     }
   121634     aOrder[ii] = ii;
   121635     for(iDim=0; iDim<pRtree->nDim; iDim++){
   121636       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
   121637       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
   121638     }
   121639   }
   121640   for(iDim=0; iDim<pRtree->nDim; iDim++){
   121641     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
   121642   }
   121643 
   121644   for(ii=0; ii<nCell; ii++){
   121645     aDistance[ii] = 0.0;
   121646     for(iDim=0; iDim<pRtree->nDim; iDim++){
   121647       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
   121648           DCOORD(aCell[ii].aCoord[iDim*2]);
   121649       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
   121650     }
   121651   }
   121652 
   121653   SortByDistance(aOrder, nCell, aDistance, aSpare);
   121654   nodeZero(pRtree, pNode);
   121655 
   121656   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
   121657     RtreeCell *p = &aCell[aOrder[ii]];
   121658     nodeInsertCell(pRtree, pNode, p);
   121659     if( p->iRowid==pCell->iRowid ){
   121660       if( iHeight==0 ){
   121661         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
   121662       }else{
   121663         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
   121664       }
   121665     }
   121666   }
   121667   if( rc==SQLITE_OK ){
   121668     rc = fixBoundingBox(pRtree, pNode);
   121669   }
   121670   for(; rc==SQLITE_OK && ii<nCell; ii++){
   121671     /* Find a node to store this cell in. pNode->iNode currently contains
   121672     ** the height of the sub-tree headed by the cell.
   121673     */
   121674     RtreeNode *pInsert;
   121675     RtreeCell *p = &aCell[aOrder[ii]];
   121676     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
   121677     if( rc==SQLITE_OK ){
   121678       int rc2;
   121679       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
   121680       rc2 = nodeRelease(pRtree, pInsert);
   121681       if( rc==SQLITE_OK ){
   121682         rc = rc2;
   121683       }
   121684     }
   121685   }
   121686 
   121687   sqlite3_free(aCell);
   121688   return rc;
   121689 }
   121690 
   121691 /*
   121692 ** Insert cell pCell into node pNode. Node pNode is the head of a
   121693 ** subtree iHeight high (leaf nodes have iHeight==0).
   121694 */
   121695 static int rtreeInsertCell(
   121696   Rtree *pRtree,
   121697   RtreeNode *pNode,
   121698   RtreeCell *pCell,
   121699   int iHeight
   121700 ){
   121701   int rc = SQLITE_OK;
   121702   if( iHeight>0 ){
   121703     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
   121704     if( pChild ){
   121705       nodeRelease(pRtree, pChild->pParent);
   121706       nodeReference(pNode);
   121707       pChild->pParent = pNode;
   121708     }
   121709   }
   121710   if( nodeInsertCell(pRtree, pNode, pCell) ){
   121711 #if VARIANT_RSTARTREE_REINSERT
   121712     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
   121713       rc = SplitNode(pRtree, pNode, pCell, iHeight);
   121714     }else{
   121715       pRtree->iReinsertHeight = iHeight;
   121716       rc = Reinsert(pRtree, pNode, pCell, iHeight);
   121717     }
   121718 #else
   121719     rc = SplitNode(pRtree, pNode, pCell, iHeight);
   121720 #endif
   121721   }else{
   121722     rc = AdjustTree(pRtree, pNode, pCell);
   121723     if( rc==SQLITE_OK ){
   121724       if( iHeight==0 ){
   121725         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
   121726       }else{
   121727         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
   121728       }
   121729     }
   121730   }
   121731   return rc;
   121732 }
   121733 
   121734 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
   121735   int ii;
   121736   int rc = SQLITE_OK;
   121737   int nCell = NCELL(pNode);
   121738 
   121739   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
   121740     RtreeNode *pInsert;
   121741     RtreeCell cell;
   121742     nodeGetCell(pRtree, pNode, ii, &cell);
   121743 
   121744     /* Find a node to store this cell in. pNode->iNode currently contains
   121745     ** the height of the sub-tree headed by the cell.
   121746     */
   121747     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
   121748     if( rc==SQLITE_OK ){
   121749       int rc2;
   121750       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
   121751       rc2 = nodeRelease(pRtree, pInsert);
   121752       if( rc==SQLITE_OK ){
   121753         rc = rc2;
   121754       }
   121755     }
   121756   }
   121757   return rc;
   121758 }
   121759 
   121760 /*
   121761 ** Select a currently unused rowid for a new r-tree record.
   121762 */
   121763 static int newRowid(Rtree *pRtree, i64 *piRowid){
   121764   int rc;
   121765   sqlite3_bind_null(pRtree->pWriteRowid, 1);
   121766   sqlite3_bind_null(pRtree->pWriteRowid, 2);
   121767   sqlite3_step(pRtree->pWriteRowid);
   121768   rc = sqlite3_reset(pRtree->pWriteRowid);
   121769   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
   121770   return rc;
   121771 }
   121772 
   121773 /*
   121774 ** The xUpdate method for rtree module virtual tables.
   121775 */
   121776 static int rtreeUpdate(
   121777   sqlite3_vtab *pVtab,
   121778   int nData,
   121779   sqlite3_value **azData,
   121780   sqlite_int64 *pRowid
   121781 ){
   121782   Rtree *pRtree = (Rtree *)pVtab;
   121783   int rc = SQLITE_OK;
   121784 
   121785   rtreeReference(pRtree);
   121786 
   121787   assert(nData>=1);
   121788 
   121789   /* If azData[0] is not an SQL NULL value, it is the rowid of a
   121790   ** record to delete from the r-tree table. The following block does
   121791   ** just that.
   121792   */
   121793   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
   121794     i64 iDelete;                /* The rowid to delete */
   121795     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
   121796     int iCell;                  /* Index of iDelete cell in pLeaf */
   121797     RtreeNode *pRoot;
   121798 
   121799     /* Obtain a reference to the root node to initialise Rtree.iDepth */
   121800     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
   121801 
   121802     /* Obtain a reference to the leaf node that contains the entry
   121803     ** about to be deleted.
   121804     */
   121805     if( rc==SQLITE_OK ){
   121806       iDelete = sqlite3_value_int64(azData[0]);
   121807       rc = findLeafNode(pRtree, iDelete, &pLeaf);
   121808     }
   121809 
   121810     /* Delete the cell in question from the leaf node. */
   121811     if( rc==SQLITE_OK ){
   121812       int rc2;
   121813       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
   121814       if( rc==SQLITE_OK ){
   121815         rc = deleteCell(pRtree, pLeaf, iCell, 0);
   121816       }
   121817       rc2 = nodeRelease(pRtree, pLeaf);
   121818       if( rc==SQLITE_OK ){
   121819         rc = rc2;
   121820       }
   121821     }
   121822 
   121823     /* Delete the corresponding entry in the <rtree>_rowid table. */
   121824     if( rc==SQLITE_OK ){
   121825       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
   121826       sqlite3_step(pRtree->pDeleteRowid);
   121827       rc = sqlite3_reset(pRtree->pDeleteRowid);
   121828     }
   121829 
   121830     /* Check if the root node now has exactly one child. If so, remove
   121831     ** it, schedule the contents of the child for reinsertion and
   121832     ** reduce the tree height by one.
   121833     **
   121834     ** This is equivalent to copying the contents of the child into
   121835     ** the root node (the operation that Gutman's paper says to perform
   121836     ** in this scenario).
   121837     */
   121838     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
   121839       int rc2;
   121840       RtreeNode *pChild;
   121841       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
   121842       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
   121843       if( rc==SQLITE_OK ){
   121844         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
   121845       }
   121846       rc2 = nodeRelease(pRtree, pChild);
   121847       if( rc==SQLITE_OK ) rc = rc2;
   121848       if( rc==SQLITE_OK ){
   121849         pRtree->iDepth--;
   121850         writeInt16(pRoot->zData, pRtree->iDepth);
   121851         pRoot->isDirty = 1;
   121852       }
   121853     }
   121854 
   121855     /* Re-insert the contents of any underfull nodes removed from the tree. */
   121856     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
   121857       if( rc==SQLITE_OK ){
   121858         rc = reinsertNodeContent(pRtree, pLeaf);
   121859       }
   121860       pRtree->pDeleted = pLeaf->pNext;
   121861       sqlite3_free(pLeaf);
   121862     }
   121863 
   121864     /* Release the reference to the root node. */
   121865     if( rc==SQLITE_OK ){
   121866       rc = nodeRelease(pRtree, pRoot);
   121867     }else{
   121868       nodeRelease(pRtree, pRoot);
   121869     }
   121870   }
   121871 
   121872   /* If the azData[] array contains more than one element, elements
   121873   ** (azData[2]..azData[argc-1]) contain a new record to insert into
   121874   ** the r-tree structure.
   121875   */
   121876   if( rc==SQLITE_OK && nData>1 ){
   121877     /* Insert a new record into the r-tree */
   121878     RtreeCell cell;
   121879     int ii;
   121880     RtreeNode *pLeaf;
   121881 
   121882     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
   121883     assert( nData==(pRtree->nDim*2 + 3) );
   121884     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
   121885       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   121886         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
   121887         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
   121888         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
   121889           rc = SQLITE_CONSTRAINT;
   121890           goto constraint;
   121891         }
   121892       }
   121893     }else{
   121894       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
   121895         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
   121896         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
   121897         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
   121898           rc = SQLITE_CONSTRAINT;
   121899           goto constraint;
   121900         }
   121901       }
   121902     }
   121903 
   121904     /* Figure out the rowid of the new row. */
   121905     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
   121906       rc = newRowid(pRtree, &cell.iRowid);
   121907     }else{
   121908       cell.iRowid = sqlite3_value_int64(azData[2]);
   121909       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
   121910       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
   121911         sqlite3_reset(pRtree->pReadRowid);
   121912         rc = SQLITE_CONSTRAINT;
   121913         goto constraint;
   121914       }
   121915       rc = sqlite3_reset(pRtree->pReadRowid);
   121916     }
   121917     *pRowid = cell.iRowid;
   121918 
   121919     if( rc==SQLITE_OK ){
   121920       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
   121921     }
   121922     if( rc==SQLITE_OK ){
   121923       int rc2;
   121924       pRtree->iReinsertHeight = -1;
   121925       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
   121926       rc2 = nodeRelease(pRtree, pLeaf);
   121927       if( rc==SQLITE_OK ){
   121928         rc = rc2;
   121929       }
   121930     }
   121931   }
   121932 
   121933 constraint:
   121934   rtreeRelease(pRtree);
   121935   return rc;
   121936 }
   121937 
   121938 /*
   121939 ** The xRename method for rtree module virtual tables.
   121940 */
   121941 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
   121942   Rtree *pRtree = (Rtree *)pVtab;
   121943   int rc = SQLITE_NOMEM;
   121944   char *zSql = sqlite3_mprintf(
   121945     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
   121946     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
   121947     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
   121948     , pRtree->zDb, pRtree->zName, zNewName
   121949     , pRtree->zDb, pRtree->zName, zNewName
   121950     , pRtree->zDb, pRtree->zName, zNewName
   121951   );
   121952   if( zSql ){
   121953     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
   121954     sqlite3_free(zSql);
   121955   }
   121956   return rc;
   121957 }
   121958 
   121959 static sqlite3_module rtreeModule = {
   121960   0,                         /* iVersion */
   121961   rtreeCreate,                /* xCreate - create a table */
   121962   rtreeConnect,               /* xConnect - connect to an existing table */
   121963   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
   121964   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
   121965   rtreeDestroy,               /* xDestroy - Drop a table */
   121966   rtreeOpen,                  /* xOpen - open a cursor */
   121967   rtreeClose,                 /* xClose - close a cursor */
   121968   rtreeFilter,                /* xFilter - configure scan constraints */
   121969   rtreeNext,                  /* xNext - advance a cursor */
   121970   rtreeEof,                   /* xEof */
   121971   rtreeColumn,                /* xColumn - read data */
   121972   rtreeRowid,                 /* xRowid - read data */
   121973   rtreeUpdate,                /* xUpdate - write data */
   121974   0,                          /* xBegin - begin transaction */
   121975   0,                          /* xSync - sync transaction */
   121976   0,                          /* xCommit - commit transaction */
   121977   0,                          /* xRollback - rollback transaction */
   121978   0,                          /* xFindFunction - function overloading */
   121979   rtreeRename                 /* xRename - rename the table */
   121980 };
   121981 
   121982 static int rtreeSqlInit(
   121983   Rtree *pRtree,
   121984   sqlite3 *db,
   121985   const char *zDb,
   121986   const char *zPrefix,
   121987   int isCreate
   121988 ){
   121989   int rc = SQLITE_OK;
   121990 
   121991   #define N_STATEMENT 9
   121992   static const char *azSql[N_STATEMENT] = {
   121993     /* Read and write the xxx_node table */
   121994     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
   121995     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
   121996     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
   121997 
   121998     /* Read and write the xxx_rowid table */
   121999     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
   122000     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
   122001     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
   122002 
   122003     /* Read and write the xxx_parent table */
   122004     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
   122005     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
   122006     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
   122007   };
   122008   sqlite3_stmt **appStmt[N_STATEMENT];
   122009   int i;
   122010 
   122011   pRtree->db = db;
   122012 
   122013   if( isCreate ){
   122014     char *zCreate = sqlite3_mprintf(
   122015 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
   122016 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
   122017 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
   122018 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
   122019       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
   122020     );
   122021     if( !zCreate ){
   122022       return SQLITE_NOMEM;
   122023     }
   122024     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
   122025     sqlite3_free(zCreate);
   122026     if( rc!=SQLITE_OK ){
   122027       return rc;
   122028     }
   122029   }
   122030 
   122031   appStmt[0] = &pRtree->pReadNode;
   122032   appStmt[1] = &pRtree->pWriteNode;
   122033   appStmt[2] = &pRtree->pDeleteNode;
   122034   appStmt[3] = &pRtree->pReadRowid;
   122035   appStmt[4] = &pRtree->pWriteRowid;
   122036   appStmt[5] = &pRtree->pDeleteRowid;
   122037   appStmt[6] = &pRtree->pReadParent;
   122038   appStmt[7] = &pRtree->pWriteParent;
   122039   appStmt[8] = &pRtree->pDeleteParent;
   122040 
   122041   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
   122042     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
   122043     if( zSql ){
   122044       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
   122045     }else{
   122046       rc = SQLITE_NOMEM;
   122047     }
   122048     sqlite3_free(zSql);
   122049   }
   122050 
   122051   return rc;
   122052 }
   122053 
   122054 /*
   122055 ** The second argument to this function contains the text of an SQL statement
   122056 ** that returns a single integer value. The statement is compiled and executed
   122057 ** using database connection db. If successful, the integer value returned
   122058 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
   122059 ** code is returned and the value of *piVal after returning is not defined.
   122060 */
   122061 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
   122062   int rc = SQLITE_NOMEM;
   122063   if( zSql ){
   122064     sqlite3_stmt *pStmt = 0;
   122065     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
   122066     if( rc==SQLITE_OK ){
   122067       if( SQLITE_ROW==sqlite3_step(pStmt) ){
   122068         *piVal = sqlite3_column_int(pStmt, 0);
   122069       }
   122070       rc = sqlite3_finalize(pStmt);
   122071     }
   122072   }
   122073   return rc;
   122074 }
   122075 
   122076 /*
   122077 ** This function is called from within the xConnect() or xCreate() method to
   122078 ** determine the node-size used by the rtree table being created or connected
   122079 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
   122080 ** Otherwise, an SQLite error code is returned.
   122081 **
   122082 ** If this function is being called as part of an xConnect(), then the rtree
   122083 ** table already exists. In this case the node-size is determined by inspecting
   122084 ** the root node of the tree.
   122085 **
   122086 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
   122087 ** This ensures that each node is stored on a single database page. If the
   122088 ** database page-size is so large that more than RTREE_MAXCELLS entries
   122089 ** would fit in a single node, use a smaller node-size.
   122090 */
   122091 static int getNodeSize(
   122092   sqlite3 *db,                    /* Database handle */
   122093   Rtree *pRtree,                  /* Rtree handle */
   122094   int isCreate                    /* True for xCreate, false for xConnect */
   122095 ){
   122096   int rc;
   122097   char *zSql;
   122098   if( isCreate ){
   122099     int iPageSize;
   122100     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
   122101     rc = getIntFromStmt(db, zSql, &iPageSize);
   122102     if( rc==SQLITE_OK ){
   122103       pRtree->iNodeSize = iPageSize-64;
   122104       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
   122105         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
   122106       }
   122107     }
   122108   }else{
   122109     zSql = sqlite3_mprintf(
   122110         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
   122111         pRtree->zDb, pRtree->zName
   122112     );
   122113     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
   122114   }
   122115 
   122116   sqlite3_free(zSql);
   122117   return rc;
   122118 }
   122119 
   122120 /*
   122121 ** This function is the implementation of both the xConnect and xCreate
   122122 ** methods of the r-tree virtual table.
   122123 **
   122124 **   argv[0]   -> module name
   122125 **   argv[1]   -> database name
   122126 **   argv[2]   -> table name
   122127 **   argv[...] -> column names...
   122128 */
   122129 static int rtreeInit(
   122130   sqlite3 *db,                        /* Database connection */
   122131   void *pAux,                         /* One of the RTREE_COORD_* constants */
   122132   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
   122133   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
   122134   char **pzErr,                       /* OUT: Error message, if any */
   122135   int isCreate                        /* True for xCreate, false for xConnect */
   122136 ){
   122137   int rc = SQLITE_OK;
   122138   Rtree *pRtree;
   122139   int nDb;              /* Length of string argv[1] */
   122140   int nName;            /* Length of string argv[2] */
   122141   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
   122142 
   122143   const char *aErrMsg[] = {
   122144     0,                                                    /* 0 */
   122145     "Wrong number of columns for an rtree table",         /* 1 */
   122146     "Too few columns for an rtree table",                 /* 2 */
   122147     "Too many columns for an rtree table"                 /* 3 */
   122148   };
   122149 
   122150   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
   122151   if( aErrMsg[iErr] ){
   122152     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
   122153     return SQLITE_ERROR;
   122154   }
   122155 
   122156   /* Allocate the sqlite3_vtab structure */
   122157   nDb = strlen(argv[1]);
   122158   nName = strlen(argv[2]);
   122159   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
   122160   if( !pRtree ){
   122161     return SQLITE_NOMEM;
   122162   }
   122163   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
   122164   pRtree->nBusy = 1;
   122165   pRtree->base.pModule = &rtreeModule;
   122166   pRtree->zDb = (char *)&pRtree[1];
   122167   pRtree->zName = &pRtree->zDb[nDb+1];
   122168   pRtree->nDim = (argc-4)/2;
   122169   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
   122170   pRtree->eCoordType = eCoordType;
   122171   memcpy(pRtree->zDb, argv[1], nDb);
   122172   memcpy(pRtree->zName, argv[2], nName);
   122173 
   122174   /* Figure out the node size to use. */
   122175   rc = getNodeSize(db, pRtree, isCreate);
   122176 
   122177   /* Create/Connect to the underlying relational database schema. If
   122178   ** that is successful, call sqlite3_declare_vtab() to configure
   122179   ** the r-tree table schema.
   122180   */
   122181   if( rc==SQLITE_OK ){
   122182     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
   122183       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   122184     }else{
   122185       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
   122186       char *zTmp;
   122187       int ii;
   122188       for(ii=4; zSql && ii<argc; ii++){
   122189         zTmp = zSql;
   122190         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
   122191         sqlite3_free(zTmp);
   122192       }
   122193       if( zSql ){
   122194         zTmp = zSql;
   122195         zSql = sqlite3_mprintf("%s);", zTmp);
   122196         sqlite3_free(zTmp);
   122197       }
   122198       if( !zSql ){
   122199         rc = SQLITE_NOMEM;
   122200       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
   122201         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
   122202       }
   122203       sqlite3_free(zSql);
   122204     }
   122205   }
   122206 
   122207   if( rc==SQLITE_OK ){
   122208     *ppVtab = (sqlite3_vtab *)pRtree;
   122209   }else{
   122210     rtreeRelease(pRtree);
   122211   }
   122212   return rc;
   122213 }
   122214 
   122215 
   122216 /*
   122217 ** Implementation of a scalar function that decodes r-tree nodes to
   122218 ** human readable strings. This can be used for debugging and analysis.
   122219 **
   122220 ** The scalar function takes two arguments, a blob of data containing
   122221 ** an r-tree node, and the number of dimensions the r-tree indexes.
   122222 ** For a two-dimensional r-tree structure called "rt", to deserialize
   122223 ** all nodes, a statement like:
   122224 **
   122225 **   SELECT rtreenode(2, data) FROM rt_node;
   122226 **
   122227 ** The human readable string takes the form of a Tcl list with one
   122228 ** entry for each cell in the r-tree node. Each entry is itself a
   122229 ** list, containing the 8-byte rowid/pageno followed by the
   122230 ** <num-dimension>*2 coordinates.
   122231 */
   122232 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   122233   char *zText = 0;
   122234   RtreeNode node;
   122235   Rtree tree;
   122236   int ii;
   122237 
   122238   UNUSED_PARAMETER(nArg);
   122239   memset(&node, 0, sizeof(RtreeNode));
   122240   memset(&tree, 0, sizeof(Rtree));
   122241   tree.nDim = sqlite3_value_int(apArg[0]);
   122242   tree.nBytesPerCell = 8 + 8 * tree.nDim;
   122243   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
   122244 
   122245   for(ii=0; ii<NCELL(&node); ii++){
   122246     char zCell[512];
   122247     int nCell = 0;
   122248     RtreeCell cell;
   122249     int jj;
   122250 
   122251     nodeGetCell(&tree, &node, ii, &cell);
   122252     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
   122253     nCell = strlen(zCell);
   122254     for(jj=0; jj<tree.nDim*2; jj++){
   122255       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
   122256       nCell = strlen(zCell);
   122257     }
   122258 
   122259     if( zText ){
   122260       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
   122261       sqlite3_free(zText);
   122262       zText = zTextNew;
   122263     }else{
   122264       zText = sqlite3_mprintf("{%s}", zCell);
   122265     }
   122266   }
   122267 
   122268   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
   122269 }
   122270 
   122271 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   122272   UNUSED_PARAMETER(nArg);
   122273   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
   122274    || sqlite3_value_bytes(apArg[0])<2
   122275   ){
   122276     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   122277   }else{
   122278     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
   122279     sqlite3_result_int(ctx, readInt16(zBlob));
   122280   }
   122281 }
   122282 
   122283 /*
   122284 ** Register the r-tree module with database handle db. This creates the
   122285 ** virtual table module "rtree" and the debugging/analysis scalar
   122286 ** function "rtreenode".
   122287 */
   122288 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
   122289   const int utf8 = SQLITE_UTF8;
   122290   int rc;
   122291 
   122292   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
   122293   if( rc==SQLITE_OK ){
   122294     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
   122295   }
   122296   if( rc==SQLITE_OK ){
   122297     void *c = (void *)RTREE_COORD_REAL32;
   122298     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
   122299   }
   122300   if( rc==SQLITE_OK ){
   122301     void *c = (void *)RTREE_COORD_INT32;
   122302     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
   122303   }
   122304 
   122305   return rc;
   122306 }
   122307 
   122308 /*
   122309 ** A version of sqlite3_free() that can be used as a callback. This is used
   122310 ** in two places - as the destructor for the blob value returned by the
   122311 ** invocation of a geometry function, and as the destructor for the geometry
   122312 ** functions themselves.
   122313 */
   122314 static void doSqlite3Free(void *p){
   122315   sqlite3_free(p);
   122316 }
   122317 
   122318 /*
   122319 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
   122320 ** scalar user function. This C function is the callback used for all such
   122321 ** registered SQL functions.
   122322 **
   122323 ** The scalar user functions return a blob that is interpreted by r-tree
   122324 ** table MATCH operators.
   122325 */
   122326 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
   122327   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
   122328   RtreeMatchArg *pBlob;
   122329   int nBlob;
   122330 
   122331   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
   122332   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
   122333   if( !pBlob ){
   122334     sqlite3_result_error_nomem(ctx);
   122335   }else{
   122336     int i;
   122337     pBlob->magic = RTREE_GEOMETRY_MAGIC;
   122338     pBlob->xGeom = pGeomCtx->xGeom;
   122339     pBlob->pContext = pGeomCtx->pContext;
   122340     pBlob->nParam = nArg;
   122341     for(i=0; i<nArg; i++){
   122342       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
   122343     }
   122344     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
   122345   }
   122346 }
   122347 
   122348 /*
   122349 ** Register a new geometry function for use with the r-tree MATCH operator.
   122350 */
   122351 SQLITE_API int sqlite3_rtree_geometry_callback(
   122352   sqlite3 *db,
   122353   const char *zGeom,
   122354   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
   122355   void *pContext
   122356 ){
   122357   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
   122358 
   122359   /* Allocate and populate the context object. */
   122360   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
   122361   if( !pGeomCtx ) return SQLITE_NOMEM;
   122362   pGeomCtx->xGeom = xGeom;
   122363   pGeomCtx->pContext = pContext;
   122364 
   122365   /* Create the new user-function. Register a destructor function to delete
   122366   ** the context object when it is no longer required.  */
   122367   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
   122368       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
   122369   );
   122370 }
   122371 
   122372 #if !SQLITE_CORE
   122373 SQLITE_API int sqlite3_extension_init(
   122374   sqlite3 *db,
   122375   char **pzErrMsg,
   122376   const sqlite3_api_routines *pApi
   122377 ){
   122378   SQLITE_EXTENSION_INIT2(pApi)
   122379   return sqlite3RtreeInit(db);
   122380 }
   122381 #endif
   122382 
   122383 #endif
   122384 
   122385 /************** End of rtree.c ***********************************************/
   122386 /************** Begin file icu.c *********************************************/
   122387 /*
   122388 ** 2007 May 6
   122389 **
   122390 ** The author disclaims copyright to this source code.  In place of
   122391 ** a legal notice, here is a blessing:
   122392 **
   122393 **    May you do good and not evil.
   122394 **    May you find forgiveness for yourself and forgive others.
   122395 **    May you share freely, never taking more than you give.
   122396 **
   122397 *************************************************************************
   122398 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
   122399 **
   122400 ** This file implements an integration between the ICU library
   122401 ** ("International Components for Unicode", an open-source library
   122402 ** for handling unicode data) and SQLite. The integration uses
   122403 ** ICU to provide the following to SQLite:
   122404 **
   122405 **   * An implementation of the SQL regexp() function (and hence REGEXP
   122406 **     operator) using the ICU uregex_XX() APIs.
   122407 **
   122408 **   * Implementations of the SQL scalar upper() and lower() functions
   122409 **     for case mapping.
   122410 **
   122411 **   * Integration of ICU and SQLite collation seqences.
   122412 **
   122413 **   * An implementation of the LIKE operator that uses ICU to
   122414 **     provide case-independent matching.
   122415 */
   122416 
   122417 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
   122418 
   122419 /* Include ICU headers */
   122420 #include <unicode/utypes.h>
   122421 #include <unicode/uregex.h>
   122422 #include <unicode/ustring.h>
   122423 #include <unicode/ucol.h>
   122424 
   122425 
   122426 #ifndef SQLITE_CORE
   122427   SQLITE_EXTENSION_INIT1
   122428 #else
   122429 #endif
   122430 
   122431 /*
   122432 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   122433 ** operator.
   122434 */
   122435 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   122436 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   122437 #endif
   122438 
   122439 /*
   122440 ** Version of sqlite3_free() that is always a function, never a macro.
   122441 */
   122442 static void xFree(void *p){
   122443   sqlite3_free(p);
   122444 }
   122445 
   122446 /*
   122447 ** Compare two UTF-8 strings for equality where the first string is
   122448 ** a "LIKE" expression. Return true (1) if they are the same and
   122449 ** false (0) if they are different.
   122450 */
   122451 static int icuLikeCompare(
   122452   const uint8_t *zPattern,   /* LIKE pattern */
   122453   const uint8_t *zString,    /* The UTF-8 string to compare against */
   122454   const UChar32 uEsc         /* The escape character */
   122455 ){
   122456   static const int MATCH_ONE = (UChar32)'_';
   122457   static const int MATCH_ALL = (UChar32)'%';
   122458 
   122459   int iPattern = 0;       /* Current byte index in zPattern */
   122460   int iString = 0;        /* Current byte index in zString */
   122461 
   122462   int prevEscape = 0;     /* True if the previous character was uEsc */
   122463 
   122464   while( zPattern[iPattern]!=0 ){
   122465 
   122466     /* Read (and consume) the next character from the input pattern. */
   122467     UChar32 uPattern;
   122468     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
   122469     assert(uPattern!=0);
   122470 
   122471     /* There are now 4 possibilities:
   122472     **
   122473     **     1. uPattern is an unescaped match-all character "%",
   122474     **     2. uPattern is an unescaped match-one character "_",
   122475     **     3. uPattern is an unescaped escape character, or
   122476     **     4. uPattern is to be handled as an ordinary character
   122477     */
   122478     if( !prevEscape && uPattern==MATCH_ALL ){
   122479       /* Case 1. */
   122480       uint8_t c;
   122481 
   122482       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
   122483       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
   122484       ** test string.
   122485       */
   122486       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
   122487         if( c==MATCH_ONE ){
   122488           if( zString[iString]==0 ) return 0;
   122489           U8_FWD_1_UNSAFE(zString, iString);
   122490         }
   122491         iPattern++;
   122492       }
   122493 
   122494       if( zPattern[iPattern]==0 ) return 1;
   122495 
   122496       while( zString[iString] ){
   122497         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
   122498           return 1;
   122499         }
   122500         U8_FWD_1_UNSAFE(zString, iString);
   122501       }
   122502       return 0;
   122503 
   122504     }else if( !prevEscape && uPattern==MATCH_ONE ){
   122505       /* Case 2. */
   122506       if( zString[iString]==0 ) return 0;
   122507       U8_FWD_1_UNSAFE(zString, iString);
   122508 
   122509     }else if( !prevEscape && uPattern==uEsc){
   122510       /* Case 3. */
   122511       prevEscape = 1;
   122512 
   122513     }else{
   122514       /* Case 4. */
   122515       UChar32 uString;
   122516       U8_NEXT_UNSAFE(zString, iString, uString);
   122517       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
   122518       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
   122519       if( uString!=uPattern ){
   122520         return 0;
   122521       }
   122522       prevEscape = 0;
   122523     }
   122524   }
   122525 
   122526   return zString[iString]==0;
   122527 }
   122528 
   122529 /*
   122530 ** Implementation of the like() SQL function.  This function implements
   122531 ** the build-in LIKE operator.  The first argument to the function is the
   122532 ** pattern and the second argument is the string.  So, the SQL statements:
   122533 **
   122534 **       A LIKE B
   122535 **
   122536 ** is implemented as like(B, A). If there is an escape character E,
   122537 **
   122538 **       A LIKE B ESCAPE E
   122539 **
   122540 ** is mapped to like(B, A, E).
   122541 */
   122542 static void icuLikeFunc(
   122543   sqlite3_context *context,
   122544   int argc,
   122545   sqlite3_value **argv
   122546 ){
   122547   const unsigned char *zA = sqlite3_value_text(argv[0]);
   122548   const unsigned char *zB = sqlite3_value_text(argv[1]);
   122549   UChar32 uEsc = 0;
   122550 
   122551   /* Limit the length of the LIKE or GLOB pattern to avoid problems
   122552   ** of deep recursion and N*N behavior in patternCompare().
   122553   */
   122554   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
   122555     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
   122556     return;
   122557   }
   122558 
   122559 
   122560   if( argc==3 ){
   122561     /* The escape character string must consist of a single UTF-8 character.
   122562     ** Otherwise, return an error.
   122563     */
   122564     int nE= sqlite3_value_bytes(argv[2]);
   122565     const unsigned char *zE = sqlite3_value_text(argv[2]);
   122566     int i = 0;
   122567     if( zE==0 ) return;
   122568     U8_NEXT(zE, i, nE, uEsc);
   122569     if( i!=nE){
   122570       sqlite3_result_error(context,
   122571           "ESCAPE expression must be a single character", -1);
   122572       return;
   122573     }
   122574   }
   122575 
   122576   if( zA && zB ){
   122577     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
   122578   }
   122579 }
   122580 
   122581 /*
   122582 ** This function is called when an ICU function called from within
   122583 ** the implementation of an SQL scalar function returns an error.
   122584 **
   122585 ** The scalar function context passed as the first argument is
   122586 ** loaded with an error message based on the following two args.
   122587 */
   122588 static void icuFunctionError(
   122589   sqlite3_context *pCtx,       /* SQLite scalar function context */
   122590   const char *zName,           /* Name of ICU function that failed */
   122591   UErrorCode e                 /* Error code returned by ICU function */
   122592 ){
   122593   char zBuf[128];
   122594   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
   122595   zBuf[127] = '\0';
   122596   sqlite3_result_error(pCtx, zBuf, -1);
   122597 }
   122598 
   122599 /*
   122600 ** Function to delete compiled regexp objects. Registered as
   122601 ** a destructor function with sqlite3_set_auxdata().
   122602 */
   122603 static void icuRegexpDelete(void *p){
   122604   URegularExpression *pExpr = (URegularExpression *)p;
   122605   uregex_close(pExpr);
   122606 }
   122607 
   122608 /*
   122609 ** Implementation of SQLite REGEXP operator. This scalar function takes
   122610 ** two arguments. The first is a regular expression pattern to compile
   122611 ** the second is a string to match against that pattern. If either
   122612 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
   122613 ** is 1 if the string matches the pattern, or 0 otherwise.
   122614 **
   122615 ** SQLite maps the regexp() function to the regexp() operator such
   122616 ** that the following two are equivalent:
   122617 **
   122618 **     zString REGEXP zPattern
   122619 **     regexp(zPattern, zString)
   122620 **
   122621 ** Uses the following ICU regexp APIs:
   122622 **
   122623 **     uregex_open()
   122624 **     uregex_matches()
   122625 **     uregex_close()
   122626 */
   122627 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   122628   UErrorCode status = U_ZERO_ERROR;
   122629   URegularExpression *pExpr;
   122630   UBool res;
   122631   const UChar *zString = sqlite3_value_text16(apArg[1]);
   122632 
   122633   /* If the left hand side of the regexp operator is NULL,
   122634   ** then the result is also NULL.
   122635   */
   122636   if( !zString ){
   122637     return;
   122638   }
   122639 
   122640   pExpr = sqlite3_get_auxdata(p, 0);
   122641   if( !pExpr ){
   122642     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
   122643     if( !zPattern ){
   122644       return;
   122645     }
   122646     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
   122647 
   122648     if( U_SUCCESS(status) ){
   122649       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
   122650     }else{
   122651       assert(!pExpr);
   122652       icuFunctionError(p, "uregex_open", status);
   122653       return;
   122654     }
   122655   }
   122656 
   122657   /* Configure the text that the regular expression operates on. */
   122658   uregex_setText(pExpr, zString, -1, &status);
   122659   if( !U_SUCCESS(status) ){
   122660     icuFunctionError(p, "uregex_setText", status);
   122661     return;
   122662   }
   122663 
   122664   /* Attempt the match */
   122665   res = uregex_matches(pExpr, 0, &status);
   122666   if( !U_SUCCESS(status) ){
   122667     icuFunctionError(p, "uregex_matches", status);
   122668     return;
   122669   }
   122670 
   122671   /* Set the text that the regular expression operates on to a NULL
   122672   ** pointer. This is not really necessary, but it is tidier than
   122673   ** leaving the regular expression object configured with an invalid
   122674   ** pointer after this function returns.
   122675   */
   122676   uregex_setText(pExpr, 0, 0, &status);
   122677 
   122678   /* Return 1 or 0. */
   122679   sqlite3_result_int(p, res ? 1 : 0);
   122680 }
   122681 
   122682 /*
   122683 ** Implementations of scalar functions for case mapping - upper() and
   122684 ** lower(). Function upper() converts its input to upper-case (ABC).
   122685 ** Function lower() converts to lower-case (abc).
   122686 **
   122687 ** ICU provides two types of case mapping, "general" case mapping and
   122688 ** "language specific". Refer to ICU documentation for the differences
   122689 ** between the two.
   122690 **
   122691 ** To utilise "general" case mapping, the upper() or lower() scalar
   122692 ** functions are invoked with one argument:
   122693 **
   122694 **     upper('ABC') -> 'abc'
   122695 **     lower('abc') -> 'ABC'
   122696 **
   122697 ** To access ICU "language specific" case mapping, upper() or lower()
   122698 ** should be invoked with two arguments. The second argument is the name
   122699 ** of the locale to use. Passing an empty string ("") or SQL NULL value
   122700 ** as the second argument is the same as invoking the 1 argument version
   122701 ** of upper() or lower().
   122702 **
   122703 **     lower('I', 'en_us') -> 'i'
   122704 **     lower('I', 'tr_tr') -> '' (small dotless i)
   122705 **
   122706 ** http://www.icu-project.org/userguide/posix.html#case_mappings
   122707 */
   122708 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   122709   const UChar *zInput;
   122710   UChar *zOutput;
   122711   int nInput;
   122712   int nOutput;
   122713 
   122714   UErrorCode status = U_ZERO_ERROR;
   122715   const char *zLocale = 0;
   122716 
   122717   assert(nArg==1 || nArg==2);
   122718   if( nArg==2 ){
   122719     zLocale = (const char *)sqlite3_value_text(apArg[1]);
   122720   }
   122721 
   122722   zInput = sqlite3_value_text16(apArg[0]);
   122723   if( !zInput ){
   122724     return;
   122725   }
   122726   nInput = sqlite3_value_bytes16(apArg[0]);
   122727 
   122728   nOutput = nInput * 2 + 2;
   122729   zOutput = sqlite3_malloc(nOutput);
   122730   if( !zOutput ){
   122731     return;
   122732   }
   122733 
   122734   if( sqlite3_user_data(p) ){
   122735     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   122736   }else{
   122737     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
   122738   }
   122739 
   122740   if( !U_SUCCESS(status) ){
   122741     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
   122742     return;
   122743   }
   122744 
   122745   sqlite3_result_text16(p, zOutput, -1, xFree);
   122746 }
   122747 
   122748 /*
   122749 ** Collation sequence destructor function. The pCtx argument points to
   122750 ** a UCollator structure previously allocated using ucol_open().
   122751 */
   122752 static void icuCollationDel(void *pCtx){
   122753   UCollator *p = (UCollator *)pCtx;
   122754   ucol_close(p);
   122755 }
   122756 
   122757 /*
   122758 ** Collation sequence comparison function. The pCtx argument points to
   122759 ** a UCollator structure previously allocated using ucol_open().
   122760 */
   122761 static int icuCollationColl(
   122762   void *pCtx,
   122763   int nLeft,
   122764   const void *zLeft,
   122765   int nRight,
   122766   const void *zRight
   122767 ){
   122768   UCollationResult res;
   122769   UCollator *p = (UCollator *)pCtx;
   122770   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
   122771   switch( res ){
   122772     case UCOL_LESS:    return -1;
   122773     case UCOL_GREATER: return +1;
   122774     case UCOL_EQUAL:   return 0;
   122775   }
   122776   assert(!"Unexpected return value from ucol_strcoll()");
   122777   return 0;
   122778 }
   122779 
   122780 /*
   122781 ** Implementation of the scalar function icu_load_collation().
   122782 **
   122783 ** This scalar function is used to add ICU collation based collation
   122784 ** types to an SQLite database connection. It is intended to be called
   122785 ** as follows:
   122786 **
   122787 **     SELECT icu_load_collation(<locale>, <collation-name>);
   122788 **
   122789 ** Where <locale> is a string containing an ICU locale identifier (i.e.
   122790 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
   122791 ** collation sequence to create.
   122792 */
   122793 static void icuLoadCollation(
   122794   sqlite3_context *p,
   122795   int nArg,
   122796   sqlite3_value **apArg
   122797 ){
   122798   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
   122799   UErrorCode status = U_ZERO_ERROR;
   122800   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
   122801   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
   122802   UCollator *pUCollator;    /* ICU library collation object */
   122803   int rc;                   /* Return code from sqlite3_create_collation_x() */
   122804 
   122805   assert(nArg==2);
   122806   zLocale = (const char *)sqlite3_value_text(apArg[0]);
   122807   zName = (const char *)sqlite3_value_text(apArg[1]);
   122808 
   122809   if( !zLocale || !zName ){
   122810     return;
   122811   }
   122812 
   122813   pUCollator = ucol_open(zLocale, &status);
   122814   if( !U_SUCCESS(status) ){
   122815     icuFunctionError(p, "ucol_open", status);
   122816     return;
   122817   }
   122818   assert(p);
   122819 
   122820   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
   122821       icuCollationColl, icuCollationDel
   122822   );
   122823   if( rc!=SQLITE_OK ){
   122824     ucol_close(pUCollator);
   122825     sqlite3_result_error(p, "Error registering collation function", -1);
   122826   }
   122827 }
   122828 
   122829 /*
   122830 ** Register the ICU extension functions with database db.
   122831 */
   122832 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
   122833   struct IcuScalar {
   122834     const char *zName;                        /* Function name */
   122835     int nArg;                                 /* Number of arguments */
   122836     int enc;                                  /* Optimal text encoding */
   122837     void *pContext;                           /* sqlite3_user_data() context */
   122838     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   122839   } scalars[] = {
   122840     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
   122841 
   122842     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
   122843     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
   122844     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   122845     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
   122846 
   122847     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
   122848     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
   122849     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   122850     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
   122851 
   122852     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
   122853     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
   122854 
   122855     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
   122856   };
   122857 
   122858   int rc = SQLITE_OK;
   122859   int i;
   122860 
   122861   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
   122862     struct IcuScalar *p = &scalars[i];
   122863     rc = sqlite3_create_function(
   122864         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
   122865     );
   122866   }
   122867 
   122868   return rc;
   122869 }
   122870 
   122871 #if !SQLITE_CORE
   122872 SQLITE_API int sqlite3_extension_init(
   122873   sqlite3 *db,
   122874   char **pzErrMsg,
   122875   const sqlite3_api_routines *pApi
   122876 ){
   122877   SQLITE_EXTENSION_INIT2(pApi)
   122878   return sqlite3IcuInit(db);
   122879 }
   122880 #endif
   122881 
   122882 #endif
   122883 
   122884 /************** End of icu.c *************************************************/
   122885 /************** Begin file fts3_icu.c ****************************************/
   122886 /*
   122887 ** 2007 June 22
   122888 **
   122889 ** The author disclaims copyright to this source code.  In place of
   122890 ** a legal notice, here is a blessing:
   122891 **
   122892 **    May you do good and not evil.
   122893 **    May you find forgiveness for yourself and forgive others.
   122894 **    May you share freely, never taking more than you give.
   122895 **
   122896 *************************************************************************
   122897 ** This file implements a tokenizer for fts3 based on the ICU library.
   122898 **
   122899 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
   122900 */
   122901 
   122902 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
   122903 #ifdef SQLITE_ENABLE_ICU
   122904 
   122905 
   122906 #include <unicode/ubrk.h>
   122907 #include <unicode/utf16.h>
   122908 
   122909 typedef struct IcuTokenizer IcuTokenizer;
   122910 typedef struct IcuCursor IcuCursor;
   122911 
   122912 struct IcuTokenizer {
   122913   sqlite3_tokenizer base;
   122914   char *zLocale;
   122915 };
   122916 
   122917 struct IcuCursor {
   122918   sqlite3_tokenizer_cursor base;
   122919 
   122920   UBreakIterator *pIter;      /* ICU break-iterator object */
   122921   int nChar;                  /* Number of UChar elements in pInput */
   122922   UChar *aChar;               /* Copy of input using utf-16 encoding */
   122923   int *aOffset;               /* Offsets of each character in utf-8 input */
   122924 
   122925   int nBuffer;
   122926   char *zBuffer;
   122927 
   122928   int iToken;
   122929 };
   122930 
   122931 /*
   122932 ** Create a new tokenizer instance.
   122933 */
   122934 static int icuCreate(
   122935   int argc,                            /* Number of entries in argv[] */
   122936   const char * const *argv,            /* Tokenizer creation arguments */
   122937   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
   122938 ){
   122939   IcuTokenizer *p;
   122940   int n = 0;
   122941 
   122942   if( argc>0 ){
   122943     n = strlen(argv[0])+1;
   122944   }
   122945   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
   122946   if( !p ){
   122947     return SQLITE_NOMEM;
   122948   }
   122949   memset(p, 0, sizeof(IcuTokenizer));
   122950 
   122951   if( n ){
   122952     p->zLocale = (char *)&p[1];
   122953     memcpy(p->zLocale, argv[0], n);
   122954   }
   122955 
   122956   *ppTokenizer = (sqlite3_tokenizer *)p;
   122957 
   122958   return SQLITE_OK;
   122959 }
   122960 
   122961 /*
   122962 ** Destroy a tokenizer
   122963 */
   122964 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
   122965   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   122966   sqlite3_free(p);
   122967   return SQLITE_OK;
   122968 }
   122969 
   122970 /*
   122971 ** Prepare to begin tokenizing a particular string.  The input
   122972 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
   122973 ** used to incrementally tokenize this string is returned in
   122974 ** *ppCursor.
   122975 */
   122976 static int icuOpen(
   122977   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
   122978   const char *zInput,                    /* Input string */
   122979   int nInput,                            /* Length of zInput in bytes */
   122980   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
   122981 ){
   122982   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
   122983   IcuCursor *pCsr;
   122984 
   122985   const int32_t opt = U_FOLD_CASE_DEFAULT;
   122986   UErrorCode status = U_ZERO_ERROR;
   122987   int nChar;
   122988 
   122989   UChar32 c;
   122990   int iInput = 0;
   122991   int iOut = 0;
   122992 
   122993   *ppCursor = 0;
   122994 
   122995   if( nInput<0 ){
   122996     nInput = strlen(zInput);
   122997   }
   122998   nChar = nInput+1;
   122999   pCsr = (IcuCursor *)sqlite3_malloc(
   123000       sizeof(IcuCursor) +                /* IcuCursor */
   123001       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
   123002       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
   123003   );
   123004   if( !pCsr ){
   123005     return SQLITE_NOMEM;
   123006   }
   123007   memset(pCsr, 0, sizeof(IcuCursor));
   123008   pCsr->aChar = (UChar *)&pCsr[1];
   123009   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
   123010 
   123011   pCsr->aOffset[iOut] = iInput;
   123012   U8_NEXT(zInput, iInput, nInput, c);
   123013   while( c>0 ){
   123014     int isError = 0;
   123015     c = u_foldCase(c, opt);
   123016     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
   123017     if( isError ){
   123018       sqlite3_free(pCsr);
   123019       return SQLITE_ERROR;
   123020     }
   123021     pCsr->aOffset[iOut] = iInput;
   123022 
   123023     if( iInput<nInput ){
   123024       U8_NEXT(zInput, iInput, nInput, c);
   123025     }else{
   123026       c = 0;
   123027     }
   123028   }
   123029 
   123030   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
   123031   if( !U_SUCCESS(status) ){
   123032     sqlite3_free(pCsr);
   123033     return SQLITE_ERROR;
   123034   }
   123035   pCsr->nChar = iOut;
   123036 
   123037   ubrk_first(pCsr->pIter);
   123038   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
   123039   return SQLITE_OK;
   123040 }
   123041 
   123042 /*
   123043 ** Close a tokenization cursor previously opened by a call to icuOpen().
   123044 */
   123045 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
   123046   IcuCursor *pCsr = (IcuCursor *)pCursor;
   123047   ubrk_close(pCsr->pIter);
   123048   sqlite3_free(pCsr->zBuffer);
   123049   sqlite3_free(pCsr);
   123050   return SQLITE_OK;
   123051 }
   123052 
   123053 /*
   123054 ** Extract the next token from a tokenization cursor.
   123055 */
   123056 static int icuNext(
   123057   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
   123058   const char **ppToken,               /* OUT: *ppToken is the token text */
   123059   int *pnBytes,                       /* OUT: Number of bytes in token */
   123060   int *piStartOffset,                 /* OUT: Starting offset of token */
   123061   int *piEndOffset,                   /* OUT: Ending offset of token */
   123062   int *piPosition                     /* OUT: Position integer of token */
   123063 ){
   123064   IcuCursor *pCsr = (IcuCursor *)pCursor;
   123065 
   123066   int iStart = 0;
   123067   int iEnd = 0;
   123068   int nByte = 0;
   123069 
   123070   while( iStart==iEnd ){
   123071     UChar32 c;
   123072 
   123073     iStart = ubrk_current(pCsr->pIter);
   123074     iEnd = ubrk_next(pCsr->pIter);
   123075     if( iEnd==UBRK_DONE ){
   123076       return SQLITE_DONE;
   123077     }
   123078 
   123079     while( iStart<iEnd ){
   123080       int iWhite = iStart;
   123081       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
   123082       if( u_isspace(c) ){
   123083         iStart = iWhite;
   123084       }else{
   123085         break;
   123086       }
   123087     }
   123088     assert(iStart<=iEnd);
   123089   }
   123090 
   123091   do {
   123092     UErrorCode status = U_ZERO_ERROR;
   123093     if( nByte ){
   123094       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
   123095       if( !zNew ){
   123096         return SQLITE_NOMEM;
   123097       }
   123098       pCsr->zBuffer = zNew;
   123099       pCsr->nBuffer = nByte;
   123100     }
   123101 
   123102     u_strToUTF8(
   123103         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
   123104         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
   123105         &status                                  /* Output success/failure */
   123106     );
   123107   } while( nByte>pCsr->nBuffer );
   123108 
   123109   *ppToken = pCsr->zBuffer;
   123110   *pnBytes = nByte;
   123111   *piStartOffset = pCsr->aOffset[iStart];
   123112   *piEndOffset = pCsr->aOffset[iEnd];
   123113   *piPosition = pCsr->iToken++;
   123114 
   123115   return SQLITE_OK;
   123116 }
   123117 
   123118 /*
   123119 ** The set of routines that implement the simple tokenizer
   123120 */
   123121 static const sqlite3_tokenizer_module icuTokenizerModule = {
   123122   0,                           /* iVersion */
   123123   icuCreate,                   /* xCreate  */
   123124   icuDestroy,                  /* xCreate  */
   123125   icuOpen,                     /* xOpen    */
   123126   icuClose,                    /* xClose   */
   123127   icuNext,                     /* xNext    */
   123128 };
   123129 
   123130 /*
   123131 ** Set *ppModule to point at the implementation of the ICU tokenizer.
   123132 */
   123133 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
   123134   sqlite3_tokenizer_module const**ppModule
   123135 ){
   123136   *ppModule = &icuTokenizerModule;
   123137 }
   123138 
   123139 #endif /* defined(SQLITE_ENABLE_ICU) */
   123140 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
   123141 
   123142 /************** End of fts3_icu.c ********************************************/
   123143